Example #1
0
 /**
  * @param GetEditModeButtonsEvent $objEvent
  */
 public function addButton(GetEditModeButtonsEvent $objEvent)
 {
     if (!$this->isRightContext($objEvent->getEnvironment())) {
         return;
     }
     // Check the file cache.
     $strInitFilePath = '/system/config/initconfig.php';
     if (file_exists(TL_ROOT . $strInitFilePath)) {
         $strFile = new \File($strInitFilePath);
         $arrFileContent = $strFile->getContentAsArray();
         foreach ($arrFileContent as $strContent) {
             if (!preg_match("/(\\/\\*|\\*|\\*\\/|\\/\\/)/", $strContent)) {
                 //system/tmp.
                 if (preg_match("/system\\/tmp/", $strContent)) {
                     // Set data.
                     \Message::addInfo($GLOBALS['TL_LANG']['MSC']['disabled_cache']);
                 }
             }
         }
     }
     // Update a field with last sync information
     $objSyncTime = \Database::getInstance()->prepare("SELECT cl.syncFrom_tstamp as syncFrom_tstamp, user.name as syncFrom_user, user.username as syncFrom_alias\n                         FROM tl_synccto_clients as cl\n                         INNER JOIN tl_user as user\n                         ON cl.syncTo_user = user.id\n                         WHERE cl.id = ?")->limit(1)->execute(\Input::get("id"));
     if ($objSyncTime->syncFrom_tstamp != 0 && strlen($objSyncTime->syncFrom_user) != 0 && strlen($objSyncTime->syncFrom_alias) != 0) {
         $strLastSync = vsprintf($GLOBALS['TL_LANG']['MSC']['last_sync'], array(date($GLOBALS['TL_CONFIG']['timeFormat'], $objSyncTime->syncFrom_tstamp), date($GLOBALS['TL_CONFIG']['dateFormat'], $objSyncTime->syncFrom_tstamp), $objSyncTime->syncFrom_user, $objSyncTime->syncFrom_alias));
         // Set data
         \Message::addInfo($strLastSync);
     }
     // Set buttons.
     $objEvent->setButtons(array('start_sync' => '<input type="submit" name="start_sync" id="start_sync" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['MSC']['sync']) . '" />', 'start_sync_all' => '<input type="submit" name="start_sync_all" id="start_sync_all" class="tl_submit" accesskey="o" value="' . specialchars($GLOBALS['TL_LANG']['MSC']['syncAll']) . '" />'));
 }
 protected function getPageUrlFromFile($path)
 {
     $file = new \File($path, true);
     if ($file->exists()) {
         $content = $file->getContentAsArray();
         $url = explode('/* ', $content[0])[1];
         $url = explode(' */', $url)[0];
         return $url;
     }
     return null;
 }
Example #3
0
 /**
  * write SystemMessageHook if update necessary
  */
 public function syncSwatchbookColors()
 {
     // Count DataSet
     $sql = \Database::getInstance()->prepare("SELECT id FROM tl_swatchbookColors")->execute();
     // Load File
     $file = new \File('src/CtEye/swatchbook-bundle/src/Resources/public/css/divElements.css');
     /**
      *  Dataset rows are not equal File rows
      *  @return SystemMessage => Sync
      */
     if ($sql->numRows !== count($file->getContentAsArray())) {
         \Message::add($GLOBALS['TL_LANG']['swatchbook']['syncSystemMessage'], 'TL_ERROR');
         $this->isUpdate = true;
     }
     return '';
 }
Example #4
0
 /**
  * Check if the file cache is active or not.
  */
 public static function checkFileCache()
 {
     // Check the file cache.
     $strInitFilePath = '/system/config/initconfig.php';
     if (file_exists(TL_ROOT . $strInitFilePath)) {
         $strFile = new \File($strInitFilePath);
         $arrFileContent = $strFile->getContentAsArray();
         foreach ($arrFileContent as $strContent) {
             if (!preg_match("/(\\/\\*|\\*|\\*\\/|\\/\\/)/", $strContent)) {
                 //system/tmp.
                 if (preg_match("/system\\/tmp/", $strContent)) {
                     // Set data.
                     \Message::addInfo($GLOBALS['TL_LANG']['MSC']['disabled_cache']);
                 }
             }
         }
     }
 }
 /**
  * Compares the current to the original template
  *
  * @param DataContainer $dc
  *
  * @return string
  */
 public function compareTemplate(DataContainer $dc)
 {
     $strCurrentPath = $dc->id;
     $strName = pathinfo($strCurrentPath, PATHINFO_FILENAME);
     $strExtension = pathinfo($strCurrentPath, PATHINFO_EXTENSION);
     $arrTemplates = TemplateLoader::getFiles();
     $blnOverridesAnotherTpl = isset($arrTemplates[$strName]);
     $strPrefix = '';
     if (($pos = strpos($strName, '_')) !== false) {
         $strPrefix = substr($strName, 0, $pos + 1);
     }
     $strBuffer = '';
     $strCompareName = null;
     $strComparePath = null;
     // By default it's the original template to compare against
     if ($blnOverridesAnotherTpl) {
         $strCompareName = $strName;
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
         if ($strComparePath !== null) {
             $strBuffer .= '<p class="tl_info" style="margin-bottom:1em">' . sprintf($GLOBALS['TL_LANG']['tl_templates']['overridesAnotherTpl'], $strComparePath) . '</p>';
         }
     }
     // User selected template to compare against
     if (\Input::post('from') && isset($arrTemplates[\Input::post('from')])) {
         $strCompareName = \Input::post('from');
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
     }
     if ($strComparePath !== null) {
         $objCurrentFile = new \File($strCurrentPath, true);
         $objCompareFile = new \File($strComparePath, true);
         // Abort if one file is missing
         if (!$objCurrentFile->exists() || !$objCompareFile->exists()) {
             $this->redirect('contao/main.php?act=error');
         }
         $objDiff = new Diff($objCompareFile->getContentAsArray(), $objCurrentFile->getContentAsArray());
         $strDiff = $objDiff->Render(new DiffRenderer(array('field' => $strCurrentPath)));
         // Identical versions
         if ($strDiff == '') {
             $strBuffer .= '<p>' . $GLOBALS['TL_LANG']['MSC']['identicalVersions'] . '</p>';
         } else {
             $strBuffer .= $strDiff;
         }
     } else {
         $strBuffer .= '<p class="tl_info">' . $GLOBALS['TL_LANG']['tl_templates']['pleaseSelect'] . '</p>';
     }
     // Templates to compare against
     $arrComparable = array();
     $intPrefixLength = strlen($strPrefix);
     foreach ($arrTemplates as $k => $v) {
         if (substr($k, 0, $intPrefixLength) === $strPrefix) {
             $arrComparable[$k] = array('version' => $k, 'info' => $k . '.' . $strExtension);
         }
     }
     /** @var \BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_diff');
     // Template variables
     $objTemplate->staticTo = $strCurrentPath;
     $objTemplate->versions = $arrComparable;
     $objTemplate->from = $strCompareName;
     $objTemplate->showLabel = specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->content = $strBuffer;
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->charset = \Config::get('characterSet');
     \Config::set('debugMode', false);
     $objTemplate->output();
     exit;
 }
 /**
  * Compares the current to the original template
  *
  * @param DataContainer $dc
  *
  * @return string
  *
  * @throws Contao\CoreBundle\Exception\InternalServerErrorException
  */
 public function compareTemplate(DataContainer $dc)
 {
     $objCurrentFile = new File($dc->id);
     $strName = $objCurrentFile->filename;
     $strExtension = $objCurrentFile->extension;
     $arrTemplates = TemplateLoader::getFiles();
     $blnOverridesAnotherTpl = isset($arrTemplates[$strName]);
     $strPrefix = '';
     if (($pos = strpos($strName, '_')) !== false) {
         $strPrefix = substr($strName, 0, $pos + 1);
     }
     $strBuffer = '';
     $strCompareName = null;
     $strComparePath = null;
     // By default it's the original template to compare against
     if ($blnOverridesAnotherTpl) {
         $strCompareName = $strName;
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
         if ($strComparePath !== null) {
             $strBuffer .= '<p class="tl_info" style="margin-bottom:1em">' . sprintf($GLOBALS['TL_LANG']['tl_templates']['overridesAnotherTpl'], $strComparePath) . '</p>';
         }
     } else {
         // Try to find the base template by strippig suffixes
         while (strpos($strName, '_') !== false) {
             $strName = substr($strName, 0, strrpos($strName, '_'));
             if (isset($arrTemplates[$strName])) {
                 $strCompareName = $strName;
                 $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
                 break;
             }
         }
     }
     // User selected template to compare against
     if (Input::post('from') && isset($arrTemplates[Input::post('from')])) {
         $strCompareName = Input::post('from');
         $strComparePath = $arrTemplates[$strCompareName] . '/' . $strCompareName . '.' . $strExtension;
     }
     if ($strComparePath !== null) {
         $objCompareFile = new File($strComparePath);
         // Abort if one file is missing
         if (!$objCurrentFile->exists() || !$objCompareFile->exists()) {
             throw new Contao\CoreBundle\Exception\InternalServerErrorException('The source or target file does not exist.');
         }
         $objDiff = new Diff($objCompareFile->getContentAsArray(), $objCurrentFile->getContentAsArray());
         $strDiff = $objDiff->render(new DiffRenderer(array('field' => $dc->id)));
         // Identical versions
         if ($strDiff == '') {
             $strBuffer .= '<p>' . $GLOBALS['TL_LANG']['MSC']['identicalVersions'] . '</p>';
         } else {
             $strBuffer .= $strDiff;
         }
     } else {
         $strBuffer .= '<p class="tl_info">' . $GLOBALS['TL_LANG']['tl_templates']['pleaseSelect'] . '</p>';
     }
     // Templates to compare against
     $arrComparable = array();
     $intPrefixLength = strlen($strPrefix);
     foreach ($arrTemplates as $k => $v) {
         if (substr($k, 0, $intPrefixLength) === $strPrefix) {
             $arrComparable[$k] = array('version' => $k, 'info' => $k . '.' . $strExtension);
         }
     }
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new BackendTemplate('be_diff');
     // Template variables
     $objTemplate->staticTo = $dc->id;
     $objTemplate->versions = $arrComparable;
     $objTemplate->from = $strCompareName;
     $objTemplate->showLabel = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->content = $strBuffer;
     $objTemplate->theme = Backend::getTheme();
     $objTemplate->base = Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']);
     $objTemplate->charset = Config::get('characterSet');
     Config::set('debugMode', false);
     throw new Contao\CoreBundle\Exception\ResponseException($objTemplate->getResponse());
 }
Example #7
0
 /**
  * Parse a sql file and try to get all table names
  * 
  * @param string $strPath Path to the SQL file
  * @return void
  */
 protected function parseSQL($strPath)
 {
     // Check if exists
     if (!file_exists(TL_ROOT . "/" . $strPath)) {
         return;
     }
     // Open file and read each single line
     $objFile = new File($strPath);
     foreach ($objFile->getContentAsArray() as $key => $value) {
         // Search for 'Create Table'
         if (preg_match("/.*CREATE TABLE `.*` \\(.*/", $value)) {
             $value = trim($value);
             $arrCreate = preg_split("/(.*CREATE TABLE `|` \\(.*)/", $value);
             $this->arrTables[] = trim($arrCreate[1]);
         }
     }
 }
 /**
  * @param \File $objCsvFile
  * @param $strTable
  * @param $strImportMode
  * @param null $arrSelectedFields
  * @param string $strFieldseparator
  * @param string $strFieldenclosure
  * @param string $strPrimaryKey
  * @param string $arrDelim
  */
 public function importCsv(\File $objCsvFile, $strTable, $strImportMode, $arrSelectedFields = null, $strFieldseparator = ';', $strFieldenclosure = '', $strPrimaryKey = 'id', $arrDelim = '||', $blnTestMode = false)
 {
     // store sucess or failure message in the session
     $_SESSION['import_from_csv']['report'] = array();
     // load language file
     \System::loadLanguageFile($strTable);
     // load dca
     $this->loadDataContainer($strTable);
     // store the options in $this->arrData
     $this->arrData = array('tablename' => $strTable, 'primaryKey' => $strPrimaryKey, 'importMode' => $strImportMode, 'selectedFields' => is_array($arrSelectedFields) ? $arrSelectedFields : array(), 'fieldSeparator' => $strFieldseparator, 'fieldEnclosure' => $strFieldenclosure);
     // truncate table
     if ($this->arrData['importMode'] == 'truncate_table') {
         $this->Database->execute('TRUNCATE TABLE `' . $strTable . '`');
     }
     if (count($this->arrData['selectedFields']) < 1) {
         return;
     }
     // get content as array
     $arrFileContent = $objCsvFile->getContentAsArray();
     $arrFieldnames = explode($this->arrData['fieldSeparator'], $arrFileContent[0]);
     // trim quotes in the first line and get the fieldnames
     $arrFieldnames = array_map(array($this, 'myTrim'), $arrFieldnames);
     // count rows
     $rows = 0;
     // count errors
     $insertError = 0;
     // store each line as an entry in the db
     foreach ($arrFileContent as $line => $lineContent) {
         $doNotSave = false;
         // line 0 contains the fieldnames
         if ($line == 0) {
             continue;
         }
         // count rows
         $rows++;
         // separate the line into the different fields
         $arrLine = explode($this->arrData['fieldSeparator'], $lineContent);
         // Set the associative Array with the line content
         $assocArrayLine = array();
         foreach ($arrFieldnames as $k => $fieldname) {
             $assocArrayLine[$fieldname] = $arrLine[$k];
         }
         $set = array();
         foreach ($arrFieldnames as $k => $fieldname) {
             $blnCustomValidation = false;
             // continue if field is excluded from import
             if (!in_array($fieldname, $this->arrData['selectedFields'])) {
                 continue;
             }
             // if entries are appended autoincrement id
             if ($this->arrData['importMode'] == 'append_entries' && strtolower($fieldname) == $this->arrData['primaryKey']) {
                 continue;
             }
             // get the field content
             $fieldValue = $arrLine[$k];
             // trim quotes
             $fieldValue = $this->myTrim($fieldValue);
             // convert variable to a string (see #2)
             $fieldValue = strval($fieldValue);
             // get the DCA of the current field
             $arrDCA =& $GLOBALS['TL_DCA'][$strTable]['fields'][$fieldname];
             $arrDCA = is_array($arrDCA) ? $arrDCA : array();
             // Prepare FormWidget object !set inputType to "text" if there is no definition
             $inputType = $arrDCA['inputType'] != '' ? $arrDCA['inputType'] : 'text';
             // Map checkboxWizards to regular checkbox widgets
             if ($inputType == 'checkboxWizard') {
                 $inputType = 'checkbox';
             }
             $strClass =& $GLOBALS['TL_FFL'][$inputType];
             // HOOK: add custom validation
             if (isset($GLOBALS['TL_HOOKS']['importFromCsv']) && is_array($GLOBALS['TL_HOOKS']['importFromCsv'])) {
                 $arrCustomValidation = array('strTable' => $strTable, 'arrDCA' => $arrDCA, 'fieldname' => $fieldname, 'value' => $fieldValue, 'arrayLine' => $assocArrayLine, 'line' => $line, 'objCsvFile' => $objCsvFile, 'skipWidgetValidation' => false, 'hasErrors' => false, 'errorMsg' => null, 'doNotSave' => false, 'blnTestMode' => $blnTestMode);
                 $blnCustomValidation = false;
                 foreach ($GLOBALS['TL_HOOKS']['importFromCsv'] as $callback) {
                     $this->import($callback[0]);
                     $arrCustomValidation = $this->{$callback[0]}->{$callback[1]}($arrCustomValidation, $this);
                     if (!is_array($arrCustomValidation)) {
                         die('Als Rückgabewert wird ein Array erwartet. Fehler in ' . __FILE__ . ' in Zeile ' . __LINE__ . '.');
                     }
                     $fieldValue = $arrCustomValidation['value'];
                     // Check if widget-validation should be skipped
                     if ($blnCustomValidation['skipWidgetValidation'] === true) {
                         $blnCustomValidation = true;
                     }
                 }
                 if ($arrCustomValidation['errorMsg'] != '') {
                     $fieldValue = sprintf('<span class="errMsg">%s</span>', $arrCustomValidation['errorMsg']);
                 }
                 if ($arrCustomValidation['doNotSave']) {
                     $doNotSave = true;
                 }
             }
             // Continue if the class does not exist
             // Use form widgets for input validation
             if (class_exists($strClass) && $blnCustomValidation === false) {
                 $objWidget = new $strClass($strClass::getAttributesFromDca($arrDCA, $fieldname, $fieldValue, '', '', $this));
                 $objWidget->storeValues = false;
                 // Set post var, so the content can be validated
                 \Input::setPost($fieldname, $fieldValue);
                 if ($fieldname == 'password') {
                     \Input::setPost('password_confirm', $fieldValue);
                 }
                 // add option values in the csv like this: value1||value2||value3
                 if ($inputType == 'radio' || $inputType == 'checkbox' || $inputType == 'select') {
                     if ($arrDCA['eval']['multiple'] === true) {
                         // Security issues in Contao #6695
                         if (version_compare(VERSION . BUILD, '3.2.5', '>=')) {
                             $fieldValue = $fieldValue != '' ? explode($arrDelim, $fieldValue) : null;
                         }
                         \Input::setPost($fieldname, $fieldValue);
                         $objWidget->value = $fieldValue;
                     }
                 }
                 // validate input
                 $objWidget->validate();
                 $fieldValue = $objWidget->value;
                 // Convert date formats into timestamps
                 $rgxp = $arrDCA['eval']['rgxp'];
                 if (($rgxp == 'date' || $rgxp == 'time' || $rgxp == 'datim') && $fieldValue != '' && !$objWidget->hasErrors()) {
                     try {
                         $strTimeFormat = $GLOBALS['TL_CONFIG'][$rgxp . 'Format'];
                         $objDate = new \Date($fieldValue, $strTimeFormat);
                         $fieldValue = $objDate->tstamp;
                     } catch (\OutOfBoundsException $e) {
                         $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $fieldValue));
                     }
                 }
                 // Make sure that unique fields are unique
                 if ($arrDCA['eval']['unique'] && $fieldValue != '' && !$this->Database->isUniqueValue($strTable, $fieldname, $fieldValue, null)) {
                     $objWidget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $arrDCA['label'][0] ?: $fieldname));
                 }
                 // Do not save the field if there are errors
                 if ($objWidget->hasErrors()) {
                     $doNotSave = true;
                     $fieldValue = sprintf('"%s" => <span class="errMsg">%s</span>', $fieldValue, $objWidget->getErrorsAsString());
                 } else {
                     // Set the correct empty value
                     if ($fieldValue === '') {
                         $fieldValue = $objWidget->getEmptyValue();
                     }
                 }
             }
             $set[$fieldname] = is_array($fieldValue) ? serialize($fieldValue) : $fieldValue;
         }
         // insert data record
         if (!$doNotSave) {
             // insert tstamp
             if ($this->Database->fieldExists('tstamp', $strTable)) {
                 if (!$set['tstamp'] > 0) {
                     $set['tstamp'] = time();
                 }
             }
             // insert dateAdded (tl_member)
             if ($this->Database->fieldExists('dateAdded', $strTable)) {
                 if (!$set['dateAdded'] > 0) {
                     $set['dateAdded'] = time();
                 }
             }
             // add new member to newsletter recipient list
             if ($strTable == 'tl_member' && $set['email'] != '' && $set['newsletter'] != '') {
                 foreach (deserialize($set['newsletter'], true) as $newsletterId) {
                     // check for unique email-address
                     $objRecipient = $this->Database->prepare("SELECT * FROM tl_newsletter_recipients WHERE email=? AND pid=(SELECT pid FROM tl_newsletter_recipients WHERE id=?) AND id!=?")->execute($set['email'], $newsletterId, $newsletterId);
                     if (!$objRecipient->numRows) {
                         $arrRecipient = array();
                         $arrRecipient['tstamp'] = time();
                         $arrRecipient['pid'] = $newsletterId;
                         $arrRecipient['email'] = $set['email'];
                         $arrRecipient['active'] = '1';
                         if ($blnTestMode !== true) {
                             $this->Database->prepare('INSERT INTO tl_newsletter_recipients %s')->set($arrRecipient)->execute();
                         }
                     }
                 }
             }
             try {
                 if ($blnTestMode !== true) {
                     // insert entry into database
                     $this->Database->prepare('INSERT INTO ' . $strTable . ' %s')->set($set)->execute();
                 }
             } catch (\Exception $e) {
                 $set['insertError'] = $e->getMessage();
                 $doNotSave = true;
             }
         }
         // generate html markup for the import report table
         $htmlReport = '';
         $cssClass = 'allOk';
         if ($doNotSave) {
             $cssClass = 'error';
             $htmlReport .= sprintf('<tr class="%s"><td class="tdTitle" colspan="2">#%s Datensatz konnte nicht angelegt werden!</td></tr>', $cssClass, $line);
             // increment error counter if necessary
             $insertError++;
         } else {
             $htmlReport .= sprintf('<tr class="%s"><td class="tdTitle" colspan="2">#%s Datensatz erfolgreich angelegt!</td></tr>', $cssClass, $line);
         }
         foreach ($set as $k => $v) {
             if (is_array($v)) {
                 $v = serialize($v);
             }
             $htmlReport .= sprintf('<tr class="%s"><td>%s</td><td>%s</td></tr>', $cssClass, \StringUtil::substr($k, 30), \StringUtil::substrHtml($v, 90));
         }
         $htmlReport .= '<tr class="delim"><td>&nbsp;</td><td>&nbsp;</td></tr>';
         $_SESSION['import_from_csv']['report'][] = $htmlReport;
     }
     $_SESSION['import_from_csv']['status'] = array('blnTestMode' => $blnTestMode, 'rows' => $rows, 'success' => $rows - $insertError, 'errors' => $insertError);
 }
    /**
     * field_callback generateExplanationMarkup
     * @return string
     */
    public function generateFileContent()
    {
        $objDb = $this->Database->prepare('SELECT fileSRC FROM tl_import_from_csv WHERE id=?')->execute(Input::get('id'));
        $objFile = FilesModel::findByUuid($objDb->fileSRC);
        // call the import class if file exists
        if (!is_file(TL_ROOT . '/' . $objFile->path)) {
            return;
        }
        $objFile = new File($objFile->path, true);
        $arrFileContent = $objFile->getContentAsArray();
        $fileContent = '';
        foreach ($arrFileContent as $line) {
            $fileContent .= '<p class="tl_help">' . $line . '</p>';
        }
        return '
<div class="parsedFile">
       <label><h2>' . $GLOBALS['TL_LANG']['tl_import_from_csv']['fileContent'][0] . '</h2></label>
       <div class="fileContentBox">
              <div>
                     ' . $fileContent . '
              </div>
       </div>
</div>
             ';
    }