Exemplo n.º 1
0
 /**
  * Check permissions for that entry
  * @return void
  */
 public static function check()
 {
     $session = \Session::getInstance()->getData();
     if (\Input::get('act') == 'delete' && in_array(\Input::get('id'), static::getUndeletableIds())) {
         \System::log('Product type ID ' . \Input::get('id') . ' is used in an order and can\'t be deleted', __METHOD__, TL_ERROR);
         \Controller::redirect('contao/main.php?act=error');
     } elseif (\Input::get('act') == 'deleteAll' && is_array($session['CURRENT']['IDS'])) {
         $arrDeletable = array_diff($session['CURRENT']['IDS'], static::getUndeletableIds());
         if (count($arrDeletable) != count($session['CURRENT']['IDS'])) {
             $session['CURRENT']['IDS'] = array_values($arrDeletable);
             \Session::getInstance()->setData($session);
             \Message::addInfo($GLOBALS['TL_LANG']['MSC']['undeletableRecords']);
         }
     }
     // Disable variants if no such attributes are available
     \Controller::loadDataContainer('tl_iso_product');
     $blnVariants = false;
     foreach ($GLOBALS['TL_DCA']['tl_iso_product']['fields'] as $strName => $arrConfig) {
         $objAttribute = $GLOBALS['TL_DCA']['tl_iso_product']['attributes'][$strName];
         if (null !== $objAttribute && $objAttribute->isVariantOption()) {
             $blnVariants = true;
             break;
         }
     }
     if (!$blnVariants) {
         \System::loadLanguageFile('explain');
         unset($GLOBALS['TL_DCA']['tl_iso_producttype']['subpalettes']['variants']);
         $GLOBALS['TL_DCA']['tl_iso_producttype']['fields']['variants']['input_field_callback'] = function ($dc) {
             // Make sure variants are disabled in this product type (see #1114)
             \Database::getInstance()->prepare("UPDATE " . $dc->table . " SET variants='' WHERE id=?")->execute($dc->id);
             return '<br><p class="tl_info">' . $GLOBALS['TL_LANG']['XPL']['noVariantAttributes'] . '</p>';
         };
     }
 }
Exemplo n.º 2
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']) . '" />'));
 }
Exemplo n.º 3
0
 /**
  * Find the longitute and latitude from a location string
  * @param type $strAddress
  * @param type $strCountry
  * @example http://wiki.openstreetmap.org/wiki/Nominatim#Examples
  */
 public static function getLonLat($strAddress, $strCountry = null)
 {
     $strQuery = 'https://nominatim.openstreetmap.org/search?' . 'q=' . rawurlencode($strAddress) . '&format=json' . '&accept-language=' . $GLOBALS['TL_LANGUAGE'] . '&limit=1';
     if ($strCountry) {
         $strQuery .= '&countrycodes=' . $strCountry;
     }
     $objRequest = new \Request();
     $objRequest->send($strQuery);
     // Return on error
     if ($objRequest->hasError()) {
         \System::log("Failed Request '{$strQuery}' with error '{$objRequest->error}'", __METHOD__, TL_ERROR);
         return false;
     }
     $arrResponse = json_decode($objRequest->response);
     // Return on empty response
     if (!count($arrResponse)) {
         \System::log("Empty Request for address '{$strAddress}': '{$strQuery}'", __METHOD__, TL_ERROR);
         return false;
     }
     // Display copyright and licence in backend
     if (TL_MODE == 'BE') {
         \Message::addInfo($arrResponse[0]->licence);
     }
     return array('licence' => $arrResponse[0]->licence, 'address' => $arrResponse[0]->display_name, 'latitude' => $arrResponse[0]->lat, 'longitude' => $arrResponse[0]->lon);
 }
Exemplo n.º 4
0
 public function showJsLibraryHint()
 {
     if ('edit' === \Input::get('act')) {
         $gallery = Gallery::findByPk(\Input::get('id'));
         if (null !== $gallery && 'elevatezoom' === $gallery->type) {
             \Message::addInfo($GLOBALS['TL_LANG']['tl_iso_gallery']['includeJQuery']);
         }
     }
 }
 protected function generateForumlayout($activeRecord)
 {
     Message::addInfo("Generating Layout");
     $row = $activeRecord->row();
     $row['skipInternalHook'] = true;
     $url = Controller::generateFrontendUrl($row, null, null, false);
     $frontendRequest = new \Contao\Request();
     $frontendRequest->send(Environment::get('url') . '/' . $url);
 }
Exemplo n.º 6
0
 /**
  * Check permissions for that entry
  * @return void
  */
 public static function check()
 {
     $session = \Session::getInstance()->getData();
     if (\Input::get('act') == 'delete' && in_array(\Input::get('id'), static::getUndeletableIds())) {
         \System::log('Product ID ' . \Input::get('id') . ' is used in an order and can\'t be deleted', __METHOD__, TL_ERROR);
         \Controller::redirect('contao/main.php?act=error');
     } elseif (\Input::get('act') == 'deleteAll' && is_array($session['CURRENT']['IDS'])) {
         $arrDeletable = array_diff($session['CURRENT']['IDS'], static::getUndeletableIds());
         if (count($arrDeletable) != count($session['CURRENT']['IDS'])) {
             // Unpublish all undeletable records
             \Database::getInstance()->query("\n                    UPDATE " . Product::getTable() . "\n                    SET published=''\n                    WHERE id IN (" . implode(',', array_intersect($session['CURRENT']['IDS'], static::getUndeletableIds())) . ")\n                ");
             // Remove undeletable products from selection
             $session['CURRENT']['IDS'] = array_values($arrDeletable);
             \Session::getInstance()->setData($session);
             \Message::addInfo($GLOBALS['TL_LANG']['MSC']['undeletableUnpublished']);
         }
     }
     $arrProducts = static::getAllowedIds();
     // Method will return true if no limits should be applied (e.g. user is admin)
     if (true === $arrProducts) {
         return;
     }
     // Filter by product type and group permissions
     if (empty($arrProducts)) {
         unset($session['CLIPBOARD']['tl_iso_product']);
         $session['CURRENT']['IDS'] = array();
         $GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['filter'][] = array('id=?', 0);
         if (false === $arrProducts) {
             $GLOBALS['TL_DCA']['tl_iso_product']['config']['closed'] = true;
         }
     } else {
         // Maybe another function has already set allowed product IDs
         if (is_array($GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root'])) {
             $arrProducts = array_intersect($GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root'], $arrProducts);
         }
         $GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root'] = $arrProducts;
         // Set allowed product IDs (edit multiple)
         if (is_array($session['CURRENT']['IDS'])) {
             $session['CURRENT']['IDS'] = array_intersect($session['CURRENT']['IDS'], $GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root']);
         }
         // Set allowed clipboard IDs
         if (is_array($session['CLIPBOARD']['tl_iso_product']['id'])) {
             $session['CLIPBOARD']['tl_iso_product']['id'] = array_intersect($session['CLIPBOARD']['tl_iso_product']['id'], $GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root'], \Database::getInstance()->query("SELECT id FROM tl_iso_product WHERE pid=0")->fetchEach('id'));
             if (empty($session['CLIPBOARD']['tl_iso_product']['id'])) {
                 unset($session['CLIPBOARD']['tl_iso_product']);
             }
         }
         // Overwrite session
         \Session::getInstance()->setData($session);
         // Check if the product is accessible by user
         if (\Input::get('id') > 0 && !in_array(\Input::get('id'), $GLOBALS['TL_DCA']['tl_iso_product']['list']['sorting']['root']) && (!is_array($session['new_records']['tl_iso_product']) || !in_array(\Input::get('id'), $session['new_records']['tl_iso_product']))) {
             \System::log('Cannot access product ID ' . \Input::get('id'), __METHOD__, TL_ERROR);
             \Controller::redirect('contao/main.php?act=error');
         }
     }
 }
Exemplo n.º 7
0
 /**
  * Remove synchronised fields from palettes
  *
  * @param \DataContainer $dc
  */
 public function disableSpecialFieldsFromSyncUser(\DataContainer $dc)
 {
     $objUser = \Database::getInstance()->prepare('SELECT * FROM `tl_user` WHERE id = ?')->execute($dc->id);
     if ($objUser->syncacc == true) {
         \Message::addInfo($GLOBALS['TL_LANG']['syncAcc']['under_sync']);
         $arrDisableFields = $GLOBALS['SYNCACC']['SYNC_FIELDS']['user'];
         foreach ($arrDisableFields as $field) {
             $GLOBALS['TL_DCA']['tl_user']['fields'][$field]['eval']['readonly'] = true;
         }
     }
 }
 /**
  * Show a hint if a JavaScript library needs to be included in the page layout
  */
 public function showJsLibraryHint($dc)
 {
     //if ($_POST || Input::get('act') != 'edit')
     //return;
     $objFfm = FormFieldModel::findByPk($dc->id);
     if ($objFfm === null) {
         return;
     }
     if ($objFfm->type == 'textarea' && $objFfm->fag_enabled) {
         Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplates'], 'moo_autogrow', 'j_autogrow'));
     }
 }
Exemplo n.º 9
0
 /**
  * Show a hint if a JavaScript library needs to be included in the page layout
  */
 public function showJsLibraryHint()
 {
     if ($_POST || Input::get('act') != 'edit') {
         return;
     }
     // Return if the user cannot access the layout module (see #6190)
     if (!$this->User->hasAccess('themes', 'modules') || !$this->User->hasAccess('layout', 'themes')) {
         return;
     }
     System::loadLanguageFile('tl_layout');
     Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_image_size']['picturefill'], $GLOBALS['TL_LANG']['tl_layout']['picturefill'][0]));
 }
 public static function getFields($varInputType = array())
 {
     $arrOptions = array();
     foreach (\HeimrichHannot\Haste\Dca\General::getFields('tl_submission', false, $varInputType, array(), false) as $strField) {
         if (!in_array($strField, static::getSkipFields())) {
             $arrOptions[] = $strField;
         }
     }
     if (empty($arrOptions) && TL_MODE == 'BE' && \Input::get('do') == 'submission') {
         \Message::addInfo($GLOBALS['TL_LANG']['MSC']['noSubmissionFields']);
     }
     return $arrOptions;
 }
Exemplo n.º 11
0
 /**
  * Remove synchronised fields from palettes
  *
  * @param \DataContainer $dc
  */
 public function disableSpecialFieldsFromSyncMember(\DataContainer $dc)
 {
     $objMember = \Database::getInstance()->prepare('SELECT * FROM `tl_member` WHERE id = ?')->execute($dc->id);
     if ($objMember->syncacc == true) {
         \Message::addInfo($GLOBALS['TL_LANG']['syncAcc']['under_sync']);
         $backendUser = \BackendUser::getInstance();
         $backendUser->authenticate();
         if (!empty($GLOBALS['SyncAcc']['sa']) && in_array($backendUser->id, $GLOBALS['SyncAcc']['sa'])) {
             \Message::addInfo($GLOBALS['TL_LANG']['syncAcc']['under_sync_sa']);
         } else {
             $arrDisableFields = $GLOBALS['SYNCACC']['SYNC_FIELDS']['member'];
             foreach ($arrDisableFields as $field) {
                 $GLOBALS['TL_DCA']['tl_member']['fields'][$field]['eval']['readonly'] = true;
             }
         }
     }
 }
Exemplo n.º 12
0
 public function generateForumlayout(DataContainer $dc)
 {
     // Return if there is no active record (override all)
     if (!$dc->activeRecord || $dc->activeRecord->type != 'phpbb_forum') {
         return;
     }
     $row = $dc->activeRecord->row();
     // If it's a new object with no values we can skip here
     if (empty($row['phpbb_path']) && empty($row['phpbb_alias'])) {
         return;
     }
     Message::addInfo("Generating Layout");
     $row['skipInternalHook'] = true;
     $url = Controller::generateFrontendUrl($row, null, null, false);
     $frontendRequest = new \Contao\Request();
     $frontendRequest->send(Environment::get('url') . '/' . $url);
 }
Exemplo n.º 13
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']);
                 }
             }
         }
     }
 }
 /**
  * Generate module
  */
 protected function compile()
 {
     // Create files
     if (\Input::post('FORM_SUBMIT') == 'tl_entity_import') {
         $objModel = EntityImportConfigModel::findByPk($this->objDc->id);
         if ($objModel === null) {
             return;
         }
         if (class_exists($objModel->importerClass)) {
             // use a particular importer (e.g. NewsImporter)
             \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['importerInfo'], $objModel->importerClass));
             $importer = new $objModel->importerClass($objModel);
         } else {
             \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['importerInfo'], 'Importer'));
             $importer = new Importer($objModel);
         }
         if ($importer->run(\Input::post('dry-run'))) {
             // Confirm and reload
             $strMessage = $GLOBALS['TL_LANG']['tl_entity_import_config']['confirm'];
             if (\Input::post('dry-run')) {
                 $strMessage = $GLOBALS['TL_LANG']['tl_entity_import_config']['confirmDry'];
             }
             \Message::addConfirmation($strMessage);
             \Controller::reload();
         }
     }
     $this->Template->base = \Environment::get('base');
     $this->Template->href = \Controller::getReferer(true);
     $this->Template->title = specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']);
     $this->Template->action = ampersand(\Environment::get('request'));
     $this->Template->selectAll = $GLOBALS['TL_LANG']['MSC']['selectAll'];
     $this->Template->button = $GLOBALS['TL_LANG']['MSC']['backBT'];
     $this->Template->message = \Message::generate();
     $this->Template->submit = specialchars($GLOBALS['TL_LANG']['tl_entity_import_config']['import'][0]);
     $this->Template->dryRun = specialchars($GLOBALS['TL_LANG']['tl_entity_import_config']['dryRun'][0]);
     $this->Template->headline = sprintf($GLOBALS['TL_LANG']['tl_entity_import_config']['headline'], \Input::get('id'));
     $this->Template->explain = $GLOBALS['TL_LANG']['tl_entity_import_config']['make'][1];
     $this->Template->label = $GLOBALS['TL_LANG']['tl_entity_import_config']['label'];
 }
Exemplo n.º 15
0
 /**
  * Add an info message
  * 
  * @param string $strMessage The info message
  * 
  * @deprecated Use Message::addInfo() instead
  */
 protected function addInfoMessage($strMessage)
 {
     \Message::addInfo($strMessage);
 }
Exemplo n.º 16
0
 /**
  * Show a hint if a JavaScript library needs to be included in the page layout
  *
  * @param DataContainer $dc
  */
 public function showJsLibraryHint(DataContainer $dc)
 {
     if ($_POST || Input::get('act') != 'edit') {
         return;
     }
     // Return if the user cannot access the layout module (see #6190)
     if (!$this->User->hasAccess('themes', 'modules') || !$this->User->hasAccess('layout', 'themes')) {
         return;
     }
     $objCte = ContentModel::findByPk($dc->id);
     if ($objCte === null) {
         return;
     }
     switch ($objCte->type) {
         case 'gallery':
             Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplates'], 'moo_mediabox', 'j_colorbox'));
             break;
         case 'sliderStart':
         case 'sliderStop':
             Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplates'], 'moo_slider', 'j_slider'));
             break;
         case 'accordionSingle':
         case 'accordionStart':
         case 'accordionStop':
             Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplates'], 'moo_accordion', 'j_accordion'));
             break;
         case 'player':
         case 'youtube':
             Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplate'], 'j_mediaelement'));
             break;
         case 'table':
             if ($objCte->sortable) {
                 Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_content']['includeTemplates'], 'moo_tablesort', 'j_tablesort'));
             }
             break;
     }
 }
Exemplo n.º 17
0
    /**
     * Return a checkbox to delete session data
     *
     * @param DataContainer $dc
     *
     * @return string
     */
    public function protectFolder(DataContainer $dc)
    {
        $count = 0;
        $strPath = $dc->id;
        // Check whether the temporary name has been replaced already (see #6432)
        if (Input::post('name') && ($strNewPath = str_replace('__new__', Input::post('name'), $strPath, $count)) && $count > 0 && is_dir(TL_ROOT . '/' . $strNewPath)) {
            $strPath = $strNewPath;
        }
        // Only show for folders (see #5660)
        if (!is_dir(TL_ROOT . '/' . $strPath)) {
            return '';
        }
        $blnProtected = file_exists(TL_ROOT . '/' . $strPath . '/.htaccess');
        // Protect or unprotect the folder
        if (Input::post('FORM_SUBMIT') == 'tl_files') {
            if (Input::post('protected')) {
                if (!$blnProtected) {
                    $blnProtected = true;
                    $objFolder = new Folder($strPath);
                    $objFolder->protect();
                }
            } else {
                if ($blnProtected) {
                    $blnProtected = false;
                    $objFolder = new Folder($strPath);
                    $objFolder->unprotect();
                }
            }
        }
        // Show a note for non-Apache servers
        if (strpos(Environment::get('serverSoftware'), 'Apache') === false) {
            Message::addInfo($GLOBALS['TL_LANG']['tl_files']['htaccessInfo']);
        }
        return '
<div class="' . $GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]['eval']['tl_class'] . ' cbx">
  <div id="ctrl_' . $dc->field . '" class="tl_checkbox_single_container">
    <input type="hidden" name="' . $dc->inputName . '" value=""><input type="checkbox" name="' . $dc->inputName . '" id="opt_' . $dc->field . '_0" class="tl_checkbox" value="1"' . ($blnProtected ? ' checked="checked"' : '') . ' onfocus="Backend.getScrollOffset()"> <label for="opt_' . $dc->field . '_0">' . $GLOBALS['TL_LANG']['tl_files']['protected'][0] . '</label>
  </div>' . (Config::get('showHelp') ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_files']['protected'][1] . '</p>' : '') . '
</div>';
    }
 /**
  *
  * Sync the autologin expire value
  * The value must be dividable by a day in seconds = 86400
  *
  * @throws Exception
  * @param $varvalue
  * @return mixed
  */
 public function updateAutologinConfig($varvalue)
 {
     if ($varvalue % 86400 != 0) {
         throw new Exception('Value must be dividable by 86400 (seconds of day)');
     } else {
         $result = System::getContainer()->get('phpbb_bridge.connector')->updateDbConfig('max_autologin_time', $varvalue / 86400);
         if ($result > 0) {
             Message::addInfo("phpBB Bridge: Autologin Expire Timeout updated in Forum to " . $varvalue / 86400 . " days");
             $this->clearPhpbbCache = true;
         }
     }
     return $varvalue;
 }
Exemplo n.º 19
0
 /**
  * Import files from selected folder
  *
  * @param string $strPath
  */
 protected function importFromPath($strPath)
 {
     $arrFiles = scan(TL_ROOT . '/' . $strPath);
     if (empty($arrFiles)) {
         \Message::addError($GLOBALS['TL_LANG']['MSC']['noFilesInFolder']);
         \Controller::reload();
     }
     $blnEmpty = true;
     $arrDelete = array();
     $objProducts = \Database::getInstance()->prepare("SELECT * FROM tl_iso_product WHERE pid=0")->execute();
     while ($objProducts->next()) {
         $arrImageNames = array();
         $arrImages = deserialize($objProducts->images);
         if (!is_array($arrImages)) {
             $arrImages = array();
         } else {
             foreach ($arrImages as $row) {
                 if ($row['src']) {
                     $arrImageNames[] = $row['src'];
                 }
             }
         }
         $arrPattern = array();
         $arrPattern[] = $objProducts->alias ? standardize($objProducts->alias) : null;
         $arrPattern[] = $objProducts->sku ? $objProducts->sku : null;
         $arrPattern[] = $objProducts->sku ? standardize($objProducts->sku) : null;
         $arrPattern[] = !empty($arrImageNames) ? implode('|', $arrImageNames) : null;
         // !HOOK: add custom import regex patterns
         if (isset($GLOBALS['ISO_HOOKS']['addAssetImportRegexp']) && is_array($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'])) {
             foreach ($GLOBALS['ISO_HOOKS']['addAssetImportRegexp'] as $callback) {
                 $objCallback = \System::importStatic($callback[0]);
                 $arrPattern = $objCallback->{$callback}[1]($arrPattern, $objProducts);
             }
         }
         $strPattern = '@^(' . implode('|', array_filter($arrPattern)) . ')@i';
         $arrMatches = preg_grep($strPattern, $arrFiles);
         if (!empty($arrMatches)) {
             $arrNewImages = array();
             foreach ($arrMatches as $file) {
                 if (is_dir(TL_ROOT . '/' . $strPath . '/' . $file)) {
                     $arrSubfiles = scan(TL_ROOT . '/' . $strPath . '/' . $file);
                     if (!empty($arrSubfiles)) {
                         foreach ($arrSubfiles as $subfile) {
                             if (is_file($strPath . '/' . $file . '/' . $subfile)) {
                                 $objFile = new \File($strPath . '/' . $file . '/' . $subfile);
                                 if ($objFile->isGdImage) {
                                     $arrNewImages[] = $strPath . '/' . $file . '/' . $subfile;
                                 }
                             }
                         }
                     }
                 } elseif (is_file(TL_ROOT . '/' . $strPath . '/' . $file)) {
                     $objFile = new \File($strPath . '/' . $file);
                     if ($objFile->isGdImage) {
                         $arrNewImages[] = $strPath . '/' . $file;
                     }
                 }
             }
             if (!empty($arrNewImages)) {
                 foreach ($arrNewImages as $strFile) {
                     $pathinfo = pathinfo(TL_ROOT . '/' . $strFile);
                     // Will recursively create the folder
                     $objFolder = new \Folder('isotope/' . strtolower(substr($pathinfo['filename'], 0, 1)));
                     $strCacheName = $pathinfo['filename'] . '-' . substr(md5_file(TL_ROOT . '/' . $strFile), 0, 8) . '.' . $pathinfo['extension'];
                     \Files::getInstance()->copy($strFile, $objFolder->path . '/' . $strCacheName);
                     $arrImages[] = array('src' => $strCacheName);
                     $arrDelete[] = $strFile;
                     \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['assetImportConfirmation'], $pathinfo['filename'] . '.' . $pathinfo['extension'], $objProducts->name));
                     $blnEmpty = false;
                 }
                 \Database::getInstance()->prepare("UPDATE tl_iso_product SET images=? WHERE id=?")->execute(serialize($arrImages), $objProducts->id);
             }
         }
     }
     if (!empty($arrDelete)) {
         $arrDelete = array_unique($arrDelete);
         foreach ($arrDelete as $file) {
             \Files::getInstance()->delete($file);
         }
     }
     if ($blnEmpty) {
         \Message::addInfo($GLOBALS['TL_LANG']['MSC']['assetImportNoFilesFound']);
     }
     \Controller::reload();
 }
Exemplo n.º 20
0
    /**
     * Generate the autoload.php files
     */
    protected function createAutoloadFiles()
    {
        $arrModules = \Input::post('modules');
        if (empty($arrModules)) {
            \Message::addError($GLOBALS['TL_LANG']['tl_autoload']['emptySelection']);
            return;
        }
        $intYear = date('Y');
        foreach ($arrModules as $strModule) {
            // The autoload.php file exists
            if (!\Input::post('override') && file_exists(TL_ROOT . '/system/modules/' . $strModule . '/config/autoload.php')) {
                \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_autoload']['autoloadExists'], $strModule));
                continue;
            }
            $intClassWidth = 0;
            $arrFiles = array();
            $arrClassLoader = array();
            $arrNamespaces = array();
            // Default configuration
            $arrDefaultConfig = array('register_namespaces' => true, 'register_classes' => true, 'register_templates' => true);
            // Create the autoload.ini file if it does not yet exist
            if (!file_exists(TL_ROOT . '/system/modules/' . $strModule . '/config/autoload.ini')) {
                $objIni = new \File('system/modules/devtools/templates/dev_ini.html5', true);
                $objIni->copyTo('system/modules/' . $strModule . '/config/autoload.ini');
            }
            $arrDefaultConfig = array_merge($arrDefaultConfig, parse_ini_file(TL_ROOT . '/system/modules/' . $strModule . '/config/autoload.ini', true));
            /** @var \SplFileInfo[] $objFiles */
            $objFiles = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(TL_ROOT . '/system/modules/' . $strModule, \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS));
            // Get all PHP files
            foreach ($objFiles as $objFile) {
                if ($objFile->getExtension() == 'php') {
                    $strRelpath = str_replace(TL_ROOT . '/system/modules/' . $strModule . '/', '', $objFile->getPathname());
                    if (strncmp($strRelpath, 'assets/', 7) !== 0 && strncmp($strRelpath, 'config/', 7) !== 0 && strncmp($strRelpath, 'dca/', 4) !== 0 && strncmp($strRelpath, 'languages/', 10) !== 0 && strncmp($strRelpath, 'templates/', 10) !== 0) {
                        $arrFiles[] = $strRelpath;
                    }
                }
            }
            // Scan for classes
            foreach ($arrFiles as $strFile) {
                $arrConfig = $arrDefaultConfig;
                // Search for a path configuration (see #4776)
                foreach ($arrDefaultConfig as $strPattern => $arrPathConfig) {
                    // Merge the path configuration with the global configuration
                    if (is_array($arrPathConfig) && fnmatch($strPattern, $strFile)) {
                        $arrConfig = array_merge($arrDefaultConfig, $arrPathConfig);
                        break;
                    }
                }
                // Continue if neither namespaces nor classes shall be registered
                if (!$arrConfig['register_namespaces'] && !$arrConfig['register_classes']) {
                    continue;
                }
                $strBuffer = '';
                $arrMatches = array();
                // Store the file size for fread()
                $size = filesize(TL_ROOT . '/system/modules/' . $strModule . '/' . $strFile);
                $fh = fopen(TL_ROOT . '/system/modules/' . $strModule . '/' . $strFile, 'rb');
                // Read until a class or interface definition has been found
                while (!preg_match('/(class|interface|trait) ' . preg_quote(basename($strFile, '.php'), '/') . '/', $strBuffer, $arrMatches) && $size > 0 && !feof($fh)) {
                    $length = min(512, $size);
                    $strBuffer .= fread($fh, $length);
                    $size -= $length;
                    // see #4876
                }
                fclose($fh);
                // The file does not contain a class or interface
                if (empty($arrMatches)) {
                    continue;
                }
                $strNamespace = preg_replace('/^.*namespace ([^; ]+);.*$/s', '$1', $strBuffer);
                // No namespace declaration found
                if ($strNamespace == $strBuffer) {
                    $strNamespace = '';
                }
                unset($strBuffer);
                // Register the namespace
                if ($strNamespace != '') {
                    if ($arrConfig['register_namespaces'] && $strNamespace != 'Contao') {
                        // Register only the first chunk as namespace
                        if (strpos($strNamespace, '\\') !== false) {
                            $arrNamespaces[] = substr($strNamespace, 0, strpos($strNamespace, '\\'));
                        } else {
                            $arrNamespaces[] = $strNamespace;
                        }
                    }
                    $strNamespace .= '\\';
                }
                // Register the class
                if ($arrConfig['register_classes']) {
                    $strKey = $strNamespace . basename($strFile, '.php');
                    $arrClassLoader[$strKey] = 'system/modules/' . $strModule . '/' . $strFile;
                    $intClassWidth = max(strlen($strKey), $intClassWidth);
                }
            }
            $intTplWidth = 0;
            $arrTplLoader = array();
            // Scan for templates
            if (is_dir(TL_ROOT . '/system/modules/' . $strModule . '/templates')) {
                /** @var \SplFileInfo[] $objFiles */
                $objFiles = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(TL_ROOT . '/system/modules/' . $strModule . '/templates', \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS));
                foreach ($objFiles as $objFile) {
                    $arrConfig = $arrDefaultConfig;
                    $strRelpath = str_replace(TL_ROOT . '/system/modules/' . $strModule . '/', '', $objFile->getPathname());
                    // Search for a path configuration (see #4776)
                    foreach ($arrDefaultConfig as $strPattern => $arrPathConfig) {
                        // Merge the path configuration with the global configuration
                        if (is_array($arrPathConfig) && fnmatch($strPattern, $strRelpath)) {
                            $arrConfig = array_merge($arrDefaultConfig, $arrPathConfig);
                            break;
                        }
                    }
                    // Continue if templates shall not be registered
                    if (!$arrConfig['register_templates']) {
                        continue;
                    }
                    $arrTplExts = trimsplit(',', strtolower(\Config::get('templateFiles')));
                    // Add all known template types (see #5857)
                    if (in_array(strtolower($objFile->getExtension()), $arrTplExts)) {
                        $strRelpath = str_replace(TL_ROOT . '/', '', $objFile->getPathname());
                        $strKey = basename($strRelpath, strrchr($strRelpath, '.'));
                        $arrTplLoader[$strKey] = dirname($strRelpath);
                        $intTplWidth = max(strlen($strKey), $intTplWidth);
                    }
                }
            }
            // Neither classes nor templates found
            if (empty($arrNamespaces) && empty($arrClassLoader) && empty($arrTplLoader)) {
                continue;
            }
            $objFile = new \File('system/modules/' . $strModule . '/config/autoload.php', true);
            $objFile->write(<<<EOT
<?php

/**
 * Contao Open Source CMS
 *
 * Copyright (c) 2005-{$intYear} Leo Feyer
 *
 * @license LGPL-3.0+
 */

EOT
);
            // Namespaces
            if (!empty($arrNamespaces)) {
                $arrNamespaces = array_unique($arrNamespaces);
                if (!empty($arrNamespaces)) {
                    $objFile->append(<<<EOT


/**
 * Register the namespaces
 */
ClassLoader::addNamespaces(array
(
EOT
);
                    foreach ($arrNamespaces as $strNamespace) {
                        $objFile->append("\t'" . $strNamespace . "',");
                    }
                    $objFile->append('));');
                }
            }
            // Classes
            if (!empty($arrClassLoader)) {
                $objFile->append(<<<EOT


/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
EOT
);
                $strGroup = null;
                foreach ($arrClassLoader as $strClass => $strPath) {
                    $strRelpath = str_replace('system/modules/' . $strModule . '/', '', $strPath);
                    $strBasedir = substr($strRelpath, 0, strpos($strRelpath, '/'));
                    if ($strBasedir != '') {
                        if ($strGroup === null) {
                            $strGroup = $strBasedir;
                            $objFile->append("\t// " . ucfirst($strBasedir));
                        } elseif ($strBasedir != $strGroup) {
                            $strGroup = $strBasedir;
                            $objFile->append("\n\t// " . ucfirst($strBasedir));
                        }
                    }
                    $strClass = "'" . $strClass . "'";
                    $objFile->append("\t" . str_pad($strClass, $intClassWidth + 2) . " => '{$strPath}',");
                }
                $objFile->append('));');
            }
            // Templates
            if (!empty($arrTplLoader)) {
                $objFile->append(<<<EOT


/**
 * Register the templates
 */
TemplateLoader::addFiles(array
(
EOT
);
                foreach ($arrTplLoader as $strName => $strPath) {
                    $strName = "'" . $strName . "'";
                    $objFile->append("\t" . str_pad($strName, $intTplWidth + 2) . " => '{$strPath}',");
                }
                $objFile->append('));');
            }
            $objFile->close();
            \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_autoload']['autoloadConfirm'], $strModule));
        }
    }
Exemplo n.º 21
0
 /**
  * Resize an uploaded image if neccessary
  *
  * @param string $strImage
  *
  * @return boolean
  */
 protected function resizeUploadedImage($strImage)
 {
     // The feature is disabled
     if (\Config::get('imageWidth') < 1 && \Config::get('imageHeight') < 1) {
         return false;
     }
     $objFile = new \File($strImage);
     // Not an image
     if (!$objFile->isSvgImage && !$objFile->isGdImage) {
         return false;
     }
     $arrImageSize = $objFile->imageSize;
     // The image is too big to be handled by the GD library
     if ($objFile->isGdImage && ($arrImageSize[0] > \Config::get('gdMaxImgWidth') || $arrImageSize[1] > \Config::get('gdMaxImgHeight'))) {
         \Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileExceeds'], $objFile->basename));
         $this->log('File "' . $objFile->basename . '" uploaded successfully but was too big to be resized automatically', __METHOD__, TL_FILES);
         return false;
     }
     $blnResize = false;
     // The image exceeds the maximum image width
     if ($arrImageSize[0] > \Config::get('imageWidth')) {
         $blnResize = true;
         $intWidth = \Config::get('imageWidth');
         $intHeight = round(\Config::get('imageWidth') * $arrImageSize[1] / $arrImageSize[0]);
         $arrImageSize = array($intWidth, $intHeight);
     }
     // The image exceeds the maximum image height
     if ($arrImageSize[1] > \Config::get('imageHeight')) {
         $blnResize = true;
         $intWidth = round(\Config::get('imageHeight') * $arrImageSize[0] / $arrImageSize[1]);
         $intHeight = \Config::get('imageHeight');
         $arrImageSize = array($intWidth, $intHeight);
     }
     // Resized successfully
     if ($blnResize) {
         \Image::resize($strImage, $arrImageSize[0], $arrImageSize[1]);
         \Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileResized'], $objFile->basename));
         $this->log('File "' . $objFile->basename . '" uploaded successfully and was scaled down to the maximum dimensions', __METHOD__, TL_FILES);
         $this->blnHasResized = true;
         return true;
     }
     return false;
 }
Exemplo n.º 22
0
 /**
  * Resize an uploaded image if neccessary
  * @param string
  * @return boolean
  */
 protected function resizeUploadedImage($strImage)
 {
     // The feature is disabled
     if ($GLOBALS['TL_CONFIG']['imageWidth'] < 1 && $GLOBALS['TL_CONFIG']['imageHeight'] < 1) {
         return false;
     }
     // Not an image
     if (($arrImageSize = @getimagesize(TL_ROOT . '/' . $strImage)) === false) {
         return false;
     }
     $strName = basename($strImage);
     // The image is too big to be handled by the GD library
     if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['gdMaxImgWidth'] || $arrImageSize[1] > $GLOBALS['TL_CONFIG']['gdMaxImgHeight']) {
         \Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileExceeds'], $strName));
         $this->log('File "' . $strName . '" uploaded successfully but was too big to be resized automatically', 'Uploader resizeUploadedImage()', TL_FILES);
         return false;
     }
     $blnResize = false;
     // The image exceeds the maximum image width
     if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth']) {
         $blnResize = true;
         $intWidth = $GLOBALS['TL_CONFIG']['imageWidth'];
         $intHeight = round($GLOBALS['TL_CONFIG']['imageWidth'] * $arrImageSize[1] / $arrImageSize[0]);
         $arrImageSize = array($intWidth, $intHeight);
     }
     // The image exceeds the maximum image height
     if ($arrImageSize[1] > $GLOBALS['TL_CONFIG']['imageHeight']) {
         $blnResize = true;
         $intWidth = round($GLOBALS['TL_CONFIG']['imageHeight'] * $arrImageSize[0] / $arrImageSize[1]);
         $intHeight = $GLOBALS['TL_CONFIG']['imageHeight'];
         $arrImageSize = array($intWidth, $intHeight);
     }
     // Resized successfully
     if ($blnResize) {
         \Image::resize($strImage, $arrImageSize[0], $arrImageSize[1]);
         \Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileResized'], $strName));
         $this->log('File "' . $strName . '" uploaded successfully and was scaled down to the maximum dimensions', 'Uploader resizeUploadedImage()', TL_FILES);
         $this->blnHasResized = true;
         return true;
     }
     return false;
 }
Exemplo n.º 23
0
 /**
  * Update order on Saferpay terminal when changing order status in backend
  *
  * @param Order       $objOrder
  * @param int         $intOldStatus
  * @param OrderStatus $objNewStatus
  */
 public function onOrderStatusUpdate(Order $objOrder, $intOldStatus, OrderStatus $objNewStatus)
 {
     if ($objNewStatus->saferpay_status == 'capture') {
         $arrPayment = deserialize($objOrder->payment_data, true);
         $blnResult = $this->sendPayComplete($arrPayment['PAYCONFIRM']['ID'], $arrPayment['PAYCONFIRM']['TOKEN']);
         if (TL_MODE == 'BE') {
             if ($blnResult) {
                 \Message::addInfo($GLOBALS['TL_LANG']['tl_iso_product_collection']['saferpayStatusSuccess']);
             } else {
                 \Message::addError($GLOBALS['TL_LANG']['tl_iso_product_collection']['saferpayStatusError']);
             }
         }
     } elseif ($objNewStatus->saferpay_status == 'cancel' && TL_MODE == 'BE') {
         \Message::addInfo($GLOBALS['TL_LANG']['tl_iso_product_collection']['saferpayStatusCancel']);
     }
 }
Exemplo n.º 24
0
    /**
     * Generate module
     */
    protected function compile()
    {
        $this->loadLanguageFile('tl_autoload');
        // Create the config/autoload.php file
        if (\Input::post('FORM_SUBMIT') == 'tl_autoload') {
            // Always scan all modules in ide_compat mode
            if (\Input::post('ide_compat')) {
                $arrModules = array_filter(scan(TL_ROOT . '/system/modules'), function ($e) {
                    return is_dir(TL_ROOT . '/system/modules/' . $e) ? $e : null;
                });
            } else {
                $arrModules = \Input::post('modules');
            }
            $intYear = date('Y');
            if (empty($arrModules)) {
                \Message::adError($GLOBALS['TL_LANG']['tl_merge']['emptySelection']);
            } else {
                $arrCompat = array();
                foreach ($arrModules as $strModule) {
                    // config/autoload.php exists
                    if (!\Input::post('ide_compat') && !\Input::post('override') && file_exists(TL_ROOT . '/system/modules/' . $strModule . '/config/autoload.php')) {
                        \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_merge']['autoloadExists'], $strModule));
                        continue;
                    }
                    $intClassWidth = 0;
                    $arrClassLoader = array();
                    $arrNamespaces = array();
                    $arrFiles = scan(TL_ROOT . '/system/modules/' . $strModule);
                    // Support subfolders
                    foreach ($arrFiles as $strFolder) {
                        if ($strFolder != 'config' && $strFolder != 'dca' && $strFolder != 'html' && $strFolder != 'languages' && $strFolder != 'templates') {
                            if (is_dir(TL_ROOT . '/system/modules/' . $strModule . '/' . $strFolder)) {
                                $files = scan(TL_ROOT . '/system/modules/' . $strModule . '/' . $strFolder);
                                $files = array_map(function ($val) use($strFolder) {
                                    return $strFolder . '/' . $val;
                                }, $files);
                                $arrFiles = array_merge($arrFiles, $files);
                            }
                        }
                    }
                    // Scan for classes
                    foreach ($arrFiles as $strFile) {
                        if (strrchr($strFile, '.') != '.php') {
                            continue;
                        }
                        // Read the first 1200 characters of the file (should include the namespace tag)
                        $fh = fopen(TL_ROOT . '/system/modules/' . $strModule . '/' . $strFile, 'rb');
                        $strBuffer = fread($fh, 1200);
                        fclose($fh);
                        if (strpos($strBuffer, 'namespace') === false) {
                            $strNamespace = '';
                        } else {
                            $strNamespace = preg_replace('/^.*namespace ([^;]+).*$/s', '$1', $strBuffer);
                            $strNamespace = str_replace('\\', '\\\\', $strNamespace);
                            if ($strNamespace != 'Contao') {
                                $arrNamespaces[] = $strNamespace;
                            } else {
                                $arrCompat[$strModule][] = basename($strFile, '.php');
                            }
                            $strNamespace .= '\\\\';
                        }
                        $strKey = $strNamespace . basename($strFile, '.php');
                        $arrClassLoader[$strKey] = 'system/modules/' . $strModule . '/' . $strFile;
                        $intClassWidth = max(strlen($strKey), $intClassWidth);
                    }
                    $intTplWidth = 0;
                    $arrTplLoader = array();
                    // Scan for templates
                    if (is_dir(TL_ROOT . '/system/modules/' . $strModule . '/templates')) {
                        foreach (scan(TL_ROOT . '/system/modules/' . $strModule . '/templates') as $strFile) {
                            if (strrchr($strFile, '.') != '.html5' && strrchr($strFile, '.') != '.xhtml') {
                                continue;
                            }
                            $strKey = basename($strFile, strrchr($strFile, '.'));
                            $arrTplLoader[$strKey] = 'system/modules/' . $strModule . '/templates';
                            $intTplWidth = max(strlen($strKey), $intTplWidth);
                        }
                    }
                    // Neither classes nor templates found
                    if (empty($arrClassLoader) && empty($arrTplLoader)) {
                        continue;
                    }
                    $strPackage = ucfirst($strModule);
                    $objFile = new \File('system/modules/' . $strModule . '/config/autoload.php');
                    $objFile->write(<<<EOT
<?php

/**
 * Contao Open Source CMS
 * 
 * Copyright (C) 2005-{$intYear} Leo Feyer
 * 
 * @package {$strPackage}
 * @link    http://www.contao.org
 * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
 */

EOT
);
                    // Namespaces
                    $arrNamespaces = array_unique($arrNamespaces);
                    if (!empty($arrNamespaces)) {
                        $objFile->append(<<<EOT


/**
 * Register the namespaces
 */
ClassLoader::addNamespaces(array
(
EOT
);
                        foreach ($arrNamespaces as $strNamespace) {
                            $objFile->append("\t'" . $strNamespace . "',");
                        }
                        $objFile->append('));');
                    }
                    // Classes
                    if (!empty($arrClassLoader)) {
                        $objFile->append(<<<EOT


/**
 * Register the classes
 */
ClassLoader::addClasses(array
(
EOT
);
                        $strGroup = null;
                        foreach ($arrClassLoader as $strClass => $strPath) {
                            if ($strGroup === null) {
                                $strGroup = dirname($strPath);
                                $objFile->append("\t// " . ucfirst(basename($strGroup)));
                            } elseif (dirname($strPath) != $strGroup) {
                                $strGroup = dirname($strPath);
                                $objFile->append("\n\t// " . ucfirst(basename($strGroup)));
                            }
                            $strClass = "'" . $strClass . "'";
                            $objFile->append("\t" . str_pad($strClass, $intClassWidth + 2) . " => '{$strPath}',");
                        }
                        $objFile->append('));');
                    }
                    // Templates
                    if (!empty($arrTplLoader)) {
                        $objFile->append(<<<EOT


/**
 * Register the templates
 */
TemplateLoader::addFiles(array
(
EOT
);
                        foreach ($arrTplLoader as $strName => $strPath) {
                            $strName = "'" . $strName . "'";
                            $objFile->append("\t" . str_pad($strName, $intTplWidth + 2) . " => '{$strPath}',");
                        }
                        $objFile->append('));');
                    }
                    $objFile->close();
                    \Message::addConfirmation('Module "' . $strModule . '" has been merged');
                }
            }
            // IDE compatibility
            if (\Input::post('ide_compat')) {
                $objFile = new \File('system/helper/ide_compat.php');
                $objFile->write(<<<EOT
<?php

/**
 * Contao Open Source CMS
 * 
 * Copyright (C) 2005-{$intYear} Leo Feyer
 * 
 * @package Core
 * @link    http://www.contao.org
 * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
 */

/**
 * This file is not used in Contao. Its only purpose is to make
 * PHP IDEs like Eclipse, Zend Studio or PHPStorm realize the
 * class origins, since the dynamic class aliasing we are using
 * is a bit too complex for them to understand.
 */

EOT
);
                $arrLibrary = array();
                // library/Contao
                foreach (scan(TL_ROOT . '/system/library/Contao') as $strFile) {
                    if (strncmp($strFile, '.', 1) === 0) {
                        continue;
                    }
                    if (is_file(TL_ROOT . '/system/library/Contao/' . $strFile)) {
                        $arrLibrary[] = basename($strFile, '.php');
                    } elseif ($strFile != 'Database') {
                        foreach (scan(TL_ROOT . '/system/library/Contao/' . $strFile) as $strSubfile) {
                            if (is_file(TL_ROOT . '/system/library/Contao/' . $strFile . '/' . $strSubfile)) {
                                $arrLibrary[] = basename($strFile, '.php') . '_' . basename($strSubfile, '.php');
                            }
                        }
                    }
                }
                // library/Contao/Database
                foreach (scan(TL_ROOT . '/system/library/Contao/Database') as $strFile) {
                    if (strncmp($strFile, '.', 1) === 0) {
                        continue;
                    }
                    if (is_file(TL_ROOT . '/system/library/Contao/Database/' . $strFile)) {
                        $arrLibrary[] = 'Database_' . basename($strFile, '.php');
                    } else {
                        foreach (scan(TL_ROOT . '/system/library/Contao/Database/' . $strFile) as $strSubfile) {
                            if (is_file(TL_ROOT . '/system/library/Contao/Database/' . $strFile . '/' . $strSubfile)) {
                                $arrLibrary[] = 'Database_' . basename($strFile, '.php') . '_' . basename($strSubfile, '.php');
                            }
                        }
                    }
                }
                array_unshift($arrCompat, $arrLibrary);
                $arrIsAbstract = array('Database', 'Database_Statement', 'Database_Result', 'Files', 'User', 'Widget', 'BackendModule', 'Events', 'ContentElement', 'Hybrid', 'Module', 'ModuleNews');
                // Add the classes
                foreach ($arrCompat as $strModule => $arrClasses) {
                    $objFile->append("\n// " . ($strModule ?: 'library'));
                    foreach ($arrClasses as $strClass) {
                        $objFile->append((in_array($strClass, $arrIsAbstract) ? 'abstract ' : '') . "class {$strClass} extends Contao\\{$strClass} {}");
                    }
                }
                $objFile->close();
            }
            $this->reload();
        }
        $arrModules = array();
        // List all modules
        foreach (scan(TL_ROOT . '/system/modules') as $strFile) {
            if (strncmp($strFile, '.', 1) === 0 || !is_dir(TL_ROOT . '/system/modules/' . $strFile)) {
                continue;
            }
            $arrModules[] = $strFile;
        }
        $this->Template->modules = $arrModules;
        $this->Template->messages = \Message::generate();
        $this->Template->href = $this->getReferer(true);
        $this->Template->title = specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']);
        $this->Template->button = $GLOBALS['TL_LANG']['MSC']['backBT'];
        $this->Template->headline = $GLOBALS['TL_LANG']['tl_merge']['headline'];
        $this->Template->action = ampersand(\Environment::get('request'));
        $this->Template->available = $GLOBALS['TL_LANG']['tl_merge']['available'];
        $this->Template->selectAll = $GLOBALS['TL_LANG']['MSC']['selectAll'];
        $this->Template->override = $GLOBALS['TL_LANG']['tl_merge']['override'];
        $this->Template->explain = $GLOBALS['TL_LANG']['tl_merge']['explain'];
        $this->Template->submitButton = specialchars($GLOBALS['TL_LANG']['MSC']['continue']);
        $this->Template->options = $GLOBALS['TL_LANG']['tl_merge']['options'];
        $this->Template->ide_compat = $GLOBALS['TL_LANG']['tl_merge']['ide_compat'];
    }
Exemplo n.º 25
0
    /**
     * Return a form to choose a CSV file and import it
     *
     * @return string
     */
    public function importRecipients()
    {
        if (\Input::get('key') != 'import') {
            return '';
        }
        $this->import('BackendUser', 'User');
        $class = $this->User->uploader;
        // See #4086 and #7046
        if (!class_exists($class) || $class == 'DropZone') {
            $class = 'FileUpload';
        }
        /** @var \FileUpload $objUploader */
        $objUploader = new $class();
        // Import CSS
        if (\Input::post('FORM_SUBMIT') == 'tl_recipients_import') {
            $arrUploaded = $objUploader->uploadTo('system/tmp');
            if (empty($arrUploaded)) {
                \Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']);
                $this->reload();
            }
            $time = time();
            $intTotal = 0;
            $intInvalid = 0;
            foreach ($arrUploaded as $strCsvFile) {
                $objFile = new \File($strCsvFile, true);
                if ($objFile->extension != 'csv') {
                    \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
                    continue;
                }
                // Get separator
                switch (\Input::post('separator')) {
                    case 'semicolon':
                        $strSeparator = ';';
                        break;
                    case 'tabulator':
                        $strSeparator = "\t";
                        break;
                    case 'linebreak':
                        $strSeparator = "\n";
                        break;
                    default:
                        $strSeparator = ',';
                        break;
                }
                $arrRecipients = array();
                $resFile = $objFile->handle;
                while (($arrRow = @fgetcsv($resFile, null, $strSeparator)) !== false) {
                    $arrRecipients = array_merge($arrRecipients, $arrRow);
                }
                $arrRecipients = array_filter(array_unique($arrRecipients));
                foreach ($arrRecipients as $strRecipient) {
                    // Skip invalid entries
                    if (!\Validator::isEmail($strRecipient)) {
                        $this->log('Recipient address "' . $strRecipient . '" seems to be invalid and has been skipped', __METHOD__, TL_ERROR);
                        ++$intInvalid;
                        continue;
                    }
                    // Check whether the e-mail address exists
                    $objRecipient = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_recipients WHERE pid=? AND email=?")->execute(\Input::get('id'), $strRecipient);
                    if ($objRecipient->count < 1) {
                        $this->Database->prepare("INSERT INTO tl_newsletter_recipients SET pid=?, tstamp={$time}, email=?, active=1")->execute(\Input::get('id'), $strRecipient);
                        ++$intTotal;
                    }
                }
            }
            \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_newsletter_recipients']['confirm'], $intTotal));
            if ($intInvalid > 0) {
                \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_newsletter_recipients']['invalid'], $intInvalid));
            }
            \System::setCookie('BE_PAGE_OFFSET', 0, 0);
            $this->reload();
        }
        // Return form
        return '
<div id="tl_buttons">
<a href="' . ampersand(str_replace('&key=import', '', \Environment::get('request'))) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>
' . \Message::generate() . '
<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_recipients_import" class="tl_form" method="post" enctype="multipart/form-data">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_recipients_import">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<input type="hidden" name="MAX_FILE_SIZE" value="' . \Config::get('maxFileSize') . '">

<div class="tl_tbox">
  <h3><label for="separator">' . $GLOBALS['TL_LANG']['MSC']['separator'][0] . '</label></h3>
  <select name="separator" id="separator" class="tl_select" onfocus="Backend.getScrollOffset()">
    <option value="comma">' . $GLOBALS['TL_LANG']['MSC']['comma'] . '</option>
    <option value="semicolon">' . $GLOBALS['TL_LANG']['MSC']['semicolon'] . '</option>
    <option value="tabulator">' . $GLOBALS['TL_LANG']['MSC']['tabulator'] . '</option>
    <option value="linebreak">' . $GLOBALS['TL_LANG']['MSC']['linebreak'] . '</option>
  </select>' . ($GLOBALS['TL_LANG']['MSC']['separator'][1] != '' ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['MSC']['separator'][1] . '</p>' : '') . '
  <h3>' . $GLOBALS['TL_LANG']['MSC']['source'][0] . '</h3>' . $objUploader->generateMarkup() . (isset($GLOBALS['TL_LANG']['MSC']['source'][1]) ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['MSC']['source'][1] . '</p>' : '') . '
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_newsletter_recipients']['import'][0]) . '">
</div>

</div>
</form>';
    }
    /**
     * Renturn a form to choose an existing style sheet and import it
     * @param \DataContainer
     * @return string
     */
    public function send(\DataContainer $objDc)
    {
        if (TL_MODE == 'BE') {
            $GLOBALS['TL_CSS'][] = 'system/modules/newsletter_content/assets/css/style.css';
            if ($this->isFlexible) {
                $GLOBALS['TL_CSS'][] = 'system/modules/newsletter_content/assets/css/style-flexible.css';
            }
        }
        $objNewsletter = $this->Database->prepare("SELECT n.*, c.useSMTP, c.smtpHost, c.smtpPort, c.smtpUser, c.smtpPass FROM tl_newsletter n LEFT JOIN tl_newsletter_channel c ON n.pid=c.id WHERE n.id=?")->limit(1)->execute($objDc->id);
        // Return if there is no newsletter
        if ($objNewsletter->numRows < 1) {
            return '';
        }
        // Overwrite the SMTP configuration
        if ($objNewsletter->useSMTP) {
            $GLOBALS['TL_CONFIG']['useSMTP'] = true;
            $GLOBALS['TL_CONFIG']['smtpHost'] = $objNewsletter->smtpHost;
            $GLOBALS['TL_CONFIG']['smtpUser'] = $objNewsletter->smtpUser;
            $GLOBALS['TL_CONFIG']['smtpPass'] = $objNewsletter->smtpPass;
            $GLOBALS['TL_CONFIG']['smtpEnc'] = $objNewsletter->smtpEnc;
            $GLOBALS['TL_CONFIG']['smtpPort'] = $objNewsletter->smtpPort;
        }
        // Add default sender address
        if ($objNewsletter->sender == '') {
            list($objNewsletter->senderName, $objNewsletter->sender) = \String::splitFriendlyEmail($GLOBALS['TL_CONFIG']['adminEmail']);
        }
        $arrAttachments = array();
        $blnAttachmentsFormatError = false;
        // Add attachments
        if ($objNewsletter->addFile) {
            $files = deserialize($objNewsletter->files);
            if (!empty($files) && is_array($files)) {
                $objFiles = \FilesModel::findMultipleByUuids($files);
                if ($objFiles === null) {
                    if (!\Validator::isUuid($files[0])) {
                        $blnAttachmentsFormatError = true;
                        \Message::addError($GLOBALS['TL_LANG']['ERR']['version2format']);
                    }
                } else {
                    while ($objFiles->next()) {
                        if (is_file(TL_ROOT . '/' . $objFiles->path)) {
                            $arrAttachments[] = $objFiles->path;
                        }
                    }
                }
            }
        }
        // Get content
        $html = '';
        $objContentElements = \ContentModel::findPublishedByPidAndTable($objNewsletter->id, 'tl_newsletter');
        if ($objContentElements !== null) {
            if (!defined('NEWSLETTER_CONTENT_PREVIEW')) {
                define('NEWSLETTER_CONTENT_PREVIEW', true);
            }
            while ($objContentElements->next()) {
                $html .= $this->getContentElement($objContentElements->id);
            }
        }
        // Replace insert tags
        $text = $this->replaceInsertTags($objNewsletter->text);
        $html = $this->replaceInsertTags($html);
        // Convert relative URLs
        $html = $this->convertRelativeUrls($html);
        // Set back to object
        $objNewsletter->content = $html;
        // Send newsletter
        if (!$blnAttachmentsFormatError && \Input::get('token') != '' && \Input::get('token') == $this->Session->get('tl_newsletter_send')) {
            $referer = preg_replace('/&(amp;)?(start|mpc|token|recipient|preview)=[^&]*/', '', \Environment::get('request'));
            // Preview
            if (isset($_GET['preview'])) {
                // Check the e-mail address
                if (!\Validator::isEmail(\Input::get('recipient', true))) {
                    $_SESSION['TL_PREVIEW_MAIL_ERROR'] = true;
                    $this->redirect($referer);
                }
                // get preview recipient
                $arrRecipient = array();
                $strEmail = urldecode(\Input::get('recipient', true));
                $objRecipient = $this->Database->prepare("SELECT * FROM tl_member m WHERE email=? ORDER BY email")->limit(1)->execute($strEmail);
                if ($objRecipient->num_rows < 1) {
                    $arrRecipient['email'] = $strEmail;
                } else {
                    $arrRecipient = $objRecipient->row();
                }
                $arrRecipient = array_merge($arrRecipient, array('extra' => '&preview=1', 'tracker_png' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $strEmail . '&preview=1&t=png', 'tracker_gif' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $strEmail . '&preview=1&t=gif', 'tracker_css' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $strEmail . '&preview=1&t=css', 'tracker_js' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $strEmail . '&preview=1&t=js'));
                // Send
                $objEmail = $this->generateEmailObject($objNewsletter, $arrAttachments);
                $objNewsletter->email = $strEmail;
                $this->sendNewsletter($objEmail, $objNewsletter, $arrRecipient, $text, $html);
                // Redirect
                \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['confirm'], 1));
                $this->redirect($referer);
            }
            // Get the total number of recipients
            $objTotal = $this->Database->prepare("SELECT COUNT(DISTINCT email) AS count FROM tl_newsletter_recipients WHERE pid=? AND active=1")->execute($objNewsletter->pid);
            // Return if there are no recipients
            if ($objTotal->count < 1) {
                $this->Session->set('tl_newsletter_send', null);
                \Message::addError($GLOBALS['TL_LANG']['tl_newsletter']['error']);
                $this->redirect($referer);
            }
            $intTotal = $objTotal->count;
            // Get page and timeout
            $intTimeout = \Input::get('timeout') > 0 ? \Input::get('timeout') : 1;
            $intStart = \Input::get('start') ? \Input::get('start') : 0;
            $intPages = \Input::get('mpc') ? \Input::get('mpc') : 10;
            // Get recipients
            $objRecipients = $this->Database->prepare("SELECT *, r.email FROM tl_newsletter_recipients r LEFT JOIN tl_member m ON(r.email=m.email) WHERE r.pid=? AND r.active=1 GROUP BY r.email ORDER BY r.email")->limit($intPages, $intStart)->execute($objNewsletter->pid);
            echo '<div style="font-family:Verdana,sans-serif;font-size:11px;line-height:16px;margin-bottom:12px">';
            // Send newsletter
            if ($objRecipients->numRows > 0) {
                // Update status
                if ($intStart == 0) {
                    $this->Database->prepare("UPDATE tl_newsletter SET sent=1, date=? WHERE id=?")->execute(time(), $objNewsletter->id);
                    $_SESSION['REJECTED_RECIPIENTS'] = array();
                }
                while ($objRecipients->next()) {
                    $objEmail = $this->generateEmailObject($objNewsletter, $arrAttachments);
                    $objNewsletter->email = $objRecipients->email;
                    $arrRecipient = array_merge($objRecipients->row(), array('tracker_png' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $objRecipients->email . '&t=png', 'tracker_gif' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $objRecipients->email . '&t=gif', 'tracker_css' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $objRecipients->email . '&t=css', 'tracker_js' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $objRecipients->email . '&t=js'));
                    $this->sendNewsletter($objEmail, $objNewsletter, $arrRecipient, $text, $html);
                    echo 'Sending newsletter to <strong>' . $objRecipients->email . '</strong><br>';
                }
            }
            echo '<div style="margin-top:12px">';
            // Redirect back home
            if ($objRecipients->numRows < 1 || $intStart + $intPages >= $intTotal) {
                $this->Session->set('tl_newsletter_send', null);
                // Deactivate rejected addresses
                if (!empty($_SESSION['REJECTED_RECIPIENTS'])) {
                    $intRejected = count($_SESSION['REJECTED_RECIPIENTS']);
                    \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['rejected'], $intRejected));
                    $intTotal -= $intRejected;
                    foreach ($_SESSION['REJECTED_RECIPIENTS'] as $strRecipient) {
                        $this->Database->prepare("UPDATE tl_newsletter_recipients SET active='' WHERE email=?")->execute($strRecipient);
                        $this->log('Recipient address "' . $strRecipient . '" was rejected and has been deactivated', __METHOD__, TL_ERROR);
                    }
                }
                $this->Database->prepare("UPDATE tl_newsletter SET recipients=?, rejected=? WHERE id=?")->execute($intTotal, $intRejected, $objNewsletter->id);
                \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['confirm'], $intTotal));
                echo '<script>setTimeout(\'window.location="' . \Environment::get('base') . $referer . '"\',1000)</script>';
                echo '<a href="' . \Environment::get('base') . $referer . '">Please click here to proceed if you are not using JavaScript</a>';
            } else {
                $url = preg_replace('/&(amp;)?(start|mpc|recipient)=[^&]*/', '', \Environment::get('request')) . '&start=' . ($intStart + $intPages) . '&mpc=' . $intPages;
                echo '<script>setTimeout(\'window.location="' . \Environment::get('base') . $url . '"\',' . $intTimeout * 1000 . ')</script>';
                echo '<a href="' . \Environment::get('base') . $url . '">Please click here to proceed if you are not using JavaScript</a>';
            }
            echo '</div></div>';
            exit;
        }
        $strToken = md5(uniqid(mt_rand(), true));
        $this->Session->set('tl_newsletter_send', $strToken);
        $sprintf = $objNewsletter->senderName != '' ? $objNewsletter->senderName . ' &lt;%s&gt;' : '%s';
        $this->import('BackendUser', 'User');
        // prepare preview
        $preview = $text;
        if (!$objNewsletter->sendText) {
            // Default template
            if ($objNewsletter->template == '') {
                $objNewsletter->template = 'mail_default';
            }
            // Load the mail template
            $objTemplate = new \BackendTemplate($objNewsletter->template);
            $objTemplate->setData($objNewsletter->row());
            $objTemplate->title = $objNewsletter->subject;
            $objTemplate->body = $html;
            $objTemplate->charset = $GLOBALS['TL_CONFIG']['characterSet'];
            $objTemplate->css = $css;
            // Backwards compatibility
            // Parse template
            $preview = $objTemplate->parse();
        }
        // Replace inserttags
        $arrName = explode(' ', $this->User->name);
        $preview = $this->replaceInsertTags($preview);
        $preview = $this->prepareLinkTracking($preview, $objNewsletter->id, $this->User->email, '&preview=1');
        $preview = $this->parseSimpleTokens($preview, array('firstname' => $arrName[0], 'lastname' => $arrName[sizeof($arrName) - 1], 'street' => 'Königsbrücker Str. 9', 'postal' => '01099', 'city' => 'Dresden', 'phone' => '0351 30966184', 'email' => $this->User->email, 'tracker_png' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $this->User->email . '&preview=1&t=png', 'tracker_gif' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $this->User->email . '&preview=1&t=gif', 'tracker_css' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $this->User->email . '&preview=1&t=css', 'tracker_js' => \Environment::get('base') . 'tracking/?n=' . $objNewsletter->id . '&e=' . $this->User->email . '&preview=1&t=js'));
        // Create cache folder
        if (!file_exists(TL_ROOT . '/system/cache/newsletter')) {
            mkdir(TL_ROOT . '/system/cache/newsletter');
            file_put_contents(TL_ROOT . '/system/cache/newsletter/.htaccess', '<IfModule !mod_authz_core.c>
  Order allow,deny
  Allow from all
</IfModule>
<IfModule mod_authz_core.c>
  Require all granted
</IfModule>');
        }
        // Cache preview
        file_put_contents(TL_ROOT . '/system/cache/newsletter/' . $objNewsletter->alias . '.html', preg_replace('/^\\s+|\\n|\\r|\\s+$/m', '', $preview));
        // Preview newsletter
        $return = '
<div id="tl_buttons">
<a href="' . $this->getReferer(true) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>

<h2 class="sub_headline">' . sprintf($GLOBALS['TL_LANG']['tl_newsletter']['send'][1], $objNewsletter->id) . '</h2>
' . \Message::generate() . '
<form action="' . ampersand(\Environment::get('script'), true) . '" id="tl_newsletter_send" class="tl_form" method="get">
<div class="tl_formbody_edit tl_newsletter_send">
<input type="hidden" name="do" value="' . \Input::get('do') . '">
<input type="hidden" name="table" value="' . \Input::get('table') . '">
<input type="hidden" name="key" value="' . \Input::get('key') . '">
<input type="hidden" name="id" value="' . \Input::get('id') . '">
<input type="hidden" name="token" value="' . $strToken . '">
<table class="prev_header">
  <tr class="row_0">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['from'] . '</td>
    <td class="col_1">' . sprintf($sprintf, $objNewsletter->sender) . '</td>
  </tr>
  <tr class="row_1">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['subject'][0] . '</td>
    <td class="col_1">' . $objNewsletter->subject . '</td>
  </tr>
  <tr class="row_2">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['template'][0] . '</td>
    <td class="col_1">' . $objNewsletter->template . '</td>
  </tr>' . (!empty($arrAttachments) && is_array($arrAttachments) ? '
  <tr class="row_3">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['attachments'] . '</td>
    <td class="col_1">' . implode(', ', $arrAttachments) . '</td>
  </tr>' : '') . '
</table>' . (!$objNewsletter->sendText ? '
<iframe class="preview_html" id="preview_html" seamless border="0" width="703px" height="503px" style="padding:0" src="system/cache/newsletter/' . $objNewsletter->alias . '.html"></iframe>
' : '') . '
<div class="preview_text">
' . nl2br_html5($text) . '
</div>

<div class="tl_tbox">
<div class="w50">
  <h3><label for="ctrl_mpc">' . $GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][0] . '</label></h3>
  <input type="text" name="mpc" id="ctrl_mpc" value="10" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][1] && $GLOBALS['TL_CONFIG']['showHelp'] ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][1] . '</p>' : '') . '
</div>
<div class="w50">
  <h3><label for="ctrl_timeout">' . $GLOBALS['TL_LANG']['tl_newsletter']['timeout'][0] . '</label></h3>
  <input type="text" name="timeout" id="ctrl_timeout" value="1" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['timeout'][1] && $GLOBALS['TL_CONFIG']['showHelp'] ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['timeout'][1] . '</p>' : '') . '
</div>
<div class="w50">
  <h3><label for="ctrl_start">' . $GLOBALS['TL_LANG']['tl_newsletter']['start'][0] . '</label></h3>
  <input type="text" name="start" id="ctrl_start" value="0" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['start'][1] && $GLOBALS['TL_CONFIG']['showHelp'] ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['start'][1] . '</p>' : '') . '
</div>
<div class="w50">
  <h3><label for="ctrl_recipient">' . $GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][0] . '</label></h3>
  <input type="text" name="recipient" id="ctrl_recipient" value="' . $this->User->email . '" class="tl_text" onfocus="Backend.getScrollOffset()">' . (isset($_SESSION['TL_PREVIEW_MAIL_ERROR']) ? '
  <div class="tl_error">' . $GLOBALS['TL_LANG']['ERR']['email'] . '</div>' : ($GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][1] && $GLOBALS['TL_CONFIG']['showHelp'] ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][1] . '</p>' : '')) . '
</div>
<div class="clear"></div>
</div>
</div>';
        // Do not send the newsletter if there is an attachment format error
        if (!$blnAttachmentsFormatError) {
            $return .= '

<div class="tl_formbody_submit">
<div class="tl_submit_container">
<input type="submit" name="preview" class="tl_submit" accesskey="p" value="' . specialchars($GLOBALS['TL_LANG']['tl_newsletter']['preview']) . '">
<input type="submit" id="send" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_newsletter']['send'][0]) . '" onclick="return confirm(\'' . str_replace("'", "\\'", $GLOBALS['TL_LANG']['tl_newsletter']['sendConfirm']) . '\')">
</div>
</div>';
        }
        $return .= '

</form>';
        unset($_SESSION['TL_PREVIEW_MAIL_ERROR']);
        return $return;
    }
Exemplo n.º 27
0
    /**
     * Return a form to choose an existing style sheet and import it
     *
     * @return string
     *
     * @throws \Exception
     */
    public function importStyleSheet()
    {
        if (\Input::get('key') != 'import') {
            return '';
        }
        $this->import('BackendUser', 'User');
        $class = $this->User->uploader;
        // See #4086 and #7046
        if (!class_exists($class) || $class == 'DropZone') {
            $class = 'FileUpload';
        }
        /** @var \FileUpload $objUploader */
        $objUploader = new $class();
        // Import CSS
        if (\Input::post('FORM_SUBMIT') == 'tl_style_sheet_import') {
            $arrUploaded = $objUploader->uploadTo('system/tmp');
            if (empty($arrUploaded)) {
                \Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']);
                $this->reload();
            }
            foreach ($arrUploaded as $strCssFile) {
                // Folders cannot be imported
                if (is_dir(TL_ROOT . '/' . $strCssFile)) {
                    \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile)));
                    continue;
                }
                $objFile = new \File($strCssFile, true);
                // Check the file extension
                if ($objFile->extension != 'css') {
                    \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
                    continue;
                }
                // Check the file name
                $strName = preg_replace('/\\.css$/i', '', basename($strCssFile));
                $strName = $this->checkStyleSheetName($strName);
                // Create the new style sheet
                $objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)")->execute(\Input::get('id'), time(), $strName, array('all'));
                $insertId = $objStyleSheet->insertId;
                if (!is_numeric($insertId) || $insertId < 0) {
                    throw new \Exception('Invalid insert ID');
                }
                // Read the file and remove carriage returns
                $strFile = $objFile->getContent();
                $strFile = str_replace("\r", '', $strFile);
                $arrTokens = array();
                $strBuffer = '';
                $intSorting = 0;
                $strComment = '';
                $strCategory = '';
                $intLength = strlen($strFile);
                // Tokenize
                for ($i = 0; $i < $intLength; $i++) {
                    $char = $strFile[$i];
                    // Whitespace
                    if ($char == '' || $char == "\n" || $char == "\t") {
                        // Ignore
                    } elseif ($char == '/') {
                        if ($strFile[$i + 1] == '*') {
                            while ($i < $intLength) {
                                $strBuffer .= $strFile[$i++];
                                if ($strFile[$i] == '/' && $strFile[$i - 1] == '*') {
                                    $arrTokens[] = array('type' => 'comment', 'content' => $strBuffer . $strFile[$i]);
                                    $strBuffer = '';
                                    break;
                                }
                            }
                        }
                    } elseif ($char == '@') {
                        $intLevel = 0;
                        $strSelector = '';
                        while ($i < $intLength) {
                            $strBuffer .= $strFile[$i++];
                            if ($strFile[$i] == '{') {
                                if (++$intLevel == 1) {
                                    ++$i;
                                    $strSelector = $strBuffer;
                                    $strBuffer = '';
                                }
                            } elseif ($strFile[$i] == '}') {
                                if (--$intLevel == 0) {
                                    $arrTokens[] = array('type' => 'atblock', 'selector' => $strSelector, 'content' => $strBuffer);
                                    $strBuffer = '';
                                    break;
                                }
                            }
                        }
                    } else {
                        $strSelector = '';
                        while ($i < $intLength) {
                            $strBuffer .= $strFile[$i++];
                            if ($strFile[$i] == '{') {
                                ++$i;
                                $strSelector = $strBuffer;
                                $strBuffer = '';
                            } elseif ($strFile[$i] == '}') {
                                $arrTokens[] = array('type' => 'block', 'selector' => $strSelector, 'content' => $strBuffer);
                                $strBuffer = '';
                                break;
                            }
                        }
                    }
                }
                foreach ($arrTokens as $arrToken) {
                    // Comments
                    if ($arrToken['type'] == 'comment') {
                        // Category (comments start with /** and contain only one line)
                        if (strncmp($arrToken['content'], '/**', 3) === 0 && substr_count($arrToken['content'], "\n") == 2) {
                            $strCategory = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
                        } elseif (strpos($arrToken['content'], "\n") === false) {
                            $strComment = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content']));
                        }
                    } elseif ($arrToken['type'] == 'atblock') {
                        $arrSet = array('pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => trim($arrToken['selector']), 'own' => $arrToken['content']);
                        $this->Database->prepare("INSERT INTO tl_style %s")->set($arrSet)->execute();
                        $strComment = '';
                    } else {
                        $arrDefinition = array('pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => trim($arrToken['selector']), 'attributes' => $arrToken['content']);
                        $this->createDefinition($arrDefinition);
                        $strComment = '';
                    }
                }
                // Write the style sheet
                $this->updateStyleSheet($insertId);
                // Notify the user
                if ($strName . '.css' != basename($strCssFile)) {
                    \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css'));
                } else {
                    \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css'));
                }
            }
            // Redirect
            \System::setCookie('BE_PAGE_OFFSET', 0, 0);
            $this->redirect(str_replace('&key=import', '', \Environment::get('request')));
        }
        // Return form
        return '
<div id="tl_buttons">
<a href="' . ampersand(str_replace('&key=import', '', \Environment::get('request'))) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>
' . \Message::generate() . '
<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_style_sheet_import" class="tl_form" method="post" enctype="multipart/form-data">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<input type="hidden" name="MAX_FILE_SIZE" value="' . \Config::get('maxFileSize') . '">

<div class="tl_tbox">
  <h3>' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][0] . '</h3>' . $objUploader->generateMarkup() . (isset($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][1] . '</p>' : '') . '
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_style_sheet']['import'][0]) . '">
</div>

</div>
</form>';
    }
Exemplo n.º 28
0
    /**
     * Return a form to choose an existing style sheet and import it
     * @return string
     * @throws \Exception
     */
    public function importStyleSheet()
    {
        if (\Input::get('key') != 'import') {
            return '';
        }
        $this->import('BackendUser', 'User');
        $class = $this->User->uploader;
        // See #4086
        if (!class_exists($class)) {
            $class = 'FileUpload';
        }
        $objUploader = new $class();
        // Import CSS
        if (\Input::post('FORM_SUBMIT') == 'tl_style_sheet_import') {
            $arrUploaded = $objUploader->uploadTo('system/tmp');
            if (empty($arrUploaded)) {
                \Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']);
                $this->reload();
            }
            foreach ($arrUploaded as $strCssFile) {
                // Folders cannot be imported
                if (is_dir(TL_ROOT . '/' . $strCssFile)) {
                    \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile)));
                    continue;
                }
                $objFile = new \File($strCssFile);
                // Check the file extension
                if ($objFile->extension != 'css') {
                    \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
                    continue;
                }
                $strFile = $objFile->getContent();
                $strFile = str_replace("\r", '', $strFile);
                $strName = preg_replace('/\\.css$/i', '', basename($strCssFile));
                $strName = $this->checkStyleSheetName($strName);
                // Create the new style sheet
                $objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)")->execute(\Input::get('id'), time(), $strName, array('all'));
                $insertId = $objStyleSheet->insertId;
                $intSorting = 0;
                $strComment = '';
                $strCategory = '';
                if (!is_numeric($insertId) || $insertId < 0) {
                    throw new \Exception('Invalid insert ID');
                }
                $strFile = str_replace('/**/', '[__]', $strFile);
                $strFile = preg_replace(array('/\\/\\*\\*\\n( *\\*.*\\n){2,} *\\*\\//', '/\\/\\*[^\\*]+\\{[^\\}]+\\}[^\\*]+\\*\\//'), '', $strFile);
                $arrChunks = preg_split('/\\{([^\\}]*)\\}|\\*\\//U', $strFile, -1, PREG_SPLIT_DELIM_CAPTURE);
                for ($i = 0; $i < count($arrChunks); $i++) {
                    $strChunk = trim($arrChunks[$i]);
                    if ($strChunk == '') {
                        continue;
                    }
                    $strChunk = preg_replace('/[\\n\\r\\t]+/', ' ', $strChunk);
                    // Category
                    if (strncmp($strChunk, '/**', 3) === 0) {
                        $strCategory = str_replace(array('/*', '*/', '*', '[__]'), '', $strChunk);
                        $strCategory = trim(preg_replace('/\\s+/', ' ', $strCategory));
                    } elseif (strncmp($strChunk, '/*', 2) === 0) {
                        $strComment = str_replace(array('/*', '*/', '*', '[__]'), '', $strChunk);
                        $strComment = trim(preg_replace('/\\s+/', ' ', $strComment));
                    } else {
                        $strNext = trim($arrChunks[$i + 1]);
                        $strNext = preg_replace('/[\\n\\r\\t]+/', ' ', $strNext);
                        $arrDefinition = array('pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => $strChunk, 'attributes' => $strNext);
                        $this->createDefinition($arrDefinition);
                        ++$i;
                        $strComment = '';
                    }
                }
                // Write the style sheet
                $this->updateStyleSheet($insertId);
                // Notify the user
                if ($strName . '.css' != basename($strCssFile)) {
                    \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css'));
                } else {
                    \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css'));
                }
            }
            // Redirect
            setcookie('BE_PAGE_OFFSET', 0, 0, '/');
            $this->redirect(str_replace('&key=import', '', \Environment::get('request')));
        }
        // Return form
        return '
<div id="tl_buttons">
<a href="' . ampersand(str_replace('&key=import', '', \Environment::get('request'))) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>

<h2 class="sub_headline">' . $GLOBALS['TL_LANG']['tl_style_sheet']['import'][1] . '</h2>
' . \Message::generate() . '
<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_style_sheet_import" class="tl_form" method="post" enctype="multipart/form-data">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<input type="hidden" name="MAX_FILE_SIZE" value="' . $GLOBALS['TL_CONFIG']['maxFileSize'] . '">

<div class="tl_tbox">
  <h3>' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][0] . '</h3>' . $objUploader->generateMarkup() . (isset($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][1] . '</p>' : '') . '
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_style_sheet']['import'][0]) . '">
</div>

</div>
</form>';
    }
 public function onSubmitCallback()
 {
     Message::addInfo("phpBB Bridge: Regenerating Forum Layout Files.");
     System::getContainer()->get('phpbb_bridge.connector')->generateForumLayoutFiles();
 }
 public static function generate()
 {
     if (($objEntityTemplate = EntityTemplateModel::findByPk(\Input::get('id'))) !== null) {
         if ($objEntityTemplate->addOutputDir) {
             $objFolder = Files::getFolderFromUuid($objEntityTemplate->outputDir);
         } else {
             $objFolder = new \Folder('system/modules', true);
         }
         // output dir
         if (!$objFolder) {
             \Message::addError($GLOBALS['TL_LANG']['MSC']['entity_generator']['outputDirNotFound']);
             static::redirectToList();
         }
         static::prepareData($objEntityTemplate);
         // create module folder in output dir if not existing
         $objTargetDir = new \Folder($objFolder->path . '/' . $objEntityTemplate->moduleName);
         $strTargetDir = $objTargetDir->path;
         // assets
         $objEntityTemplate->addAssets = deserialize($objEntityTemplate->addAssets, true);
         if (!empty($objEntityTemplate->addAssets)) {
             new \Folder($strTargetDir . '/assets');
             foreach ($objEntityTemplate->addAssets as $strType) {
                 if ($strType == 'htaccess') {
                     copy(TL_ROOT . '/system/modules/entity_generator/templates/assets/htaccess.html5', TL_ROOT . '/' . $strTargetDir . '/assets/.htaccess');
                 } else {
                     new \Folder($strTargetDir . '/assets/' . $strType);
                 }
             }
             \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['entity_generator']['assetsSuccessfullyGenerated'], $strTargetDir . '/assets/'));
         }
         // config
         $objDcaEntityTemplates = static::getLinkedDcas($objEntityTemplate->id);
         if ($objEntityTemplate->addConfig) {
             $arrData = array();
             $blnAddUserPermissions = false;
             if ($objEntityTemplate->addDcas) {
                 foreach ($objDcaEntityTemplates as $objDcaEntityTemplate) {
                     if ($objDcaEntityTemplate->addModel) {
                         $arrData[$objDcaEntityTemplate->dcaName] = array('entityClassName' => $objDcaEntityTemplate->entityClassName, 'addParentDca' => $objDcaEntityTemplate->addParentDca, 'parentDcaName' => EntityTemplateModel::findByPk($objDcaEntityTemplate->parentDca)->dcaName);
                     }
                     if ($objDcaEntityTemplate->addUserPermissions) {
                         $blnAddUserPermissions = true;
                     }
                 }
             }
             $strTargetFile = $strTargetDir . '/config/config.php';
             static::parseTemplate($objEntityTemplate->configTemplate, $objEntityTemplate, $strTargetFile, array('dcas' => $arrData, 'addUserPermissions' => $blnAddUserPermissions));
             // modules lang
             if ($objEntityTemplate->addBackendModule) {
                 foreach (static::$arrLanguages as $strLanguage) {
                     $strTargetFile = $strTargetDir . '/languages/' . $strLanguage . '/modules.php';
                     $arrData = array();
                     if ($objEntityTemplate->addDcas) {
                         foreach (deserialize($objEntityTemplate->dcas) as $intId) {
                             if (($objDcaEntityTemplate = EntityTemplateModel::findByPk($intId)) !== null) {
                                 $arrData[$objDcaEntityTemplate->dcaName] = $objDcaEntityTemplate->localizedEntityNamePlural;
                             }
                         }
                     }
                     $strPrefix = $strLanguage != 'en' ? $strLanguage . '_' : '';
                     \System::loadLanguageFile('default', $strLanguage, true);
                     static::parseTemplate($strPrefix . $objEntityTemplate->modulesLangTemplate, $objEntityTemplate, $strTargetFile, array('dcaLocalizations' => $arrData));
                     \System::loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
                 }
             }
         }
         // dca
         if ($objEntityTemplate->addDcas) {
             foreach ($objDcaEntityTemplates as $objDcaEntityTemplate) {
                 static::prepareData($objDcaEntityTemplate);
                 // dca
                 $strTargetFile = $strTargetDir . '/dca/tl_' . $objDcaEntityTemplate->dcaName . '.php';
                 static::parseTemplate($objDcaEntityTemplate->dcaTemplate, $objDcaEntityTemplate, $strTargetFile);
                 // user permissions
                 if ($objDcaEntityTemplate->addUserPermissions) {
                     // tl_user - dca
                     $strTargetFile = $strTargetDir . '/dca/tl_user.php';
                     static::parseTemplate($objDcaEntityTemplate->userTemplate, $objDcaEntityTemplate, $strTargetFile, array('moduleName' => $objEntityTemplate->moduleName));
                     // tl_user_group - dca
                     $strTargetFile = $strTargetDir . '/dca/tl_user_group.php';
                     static::parseTemplate($objDcaEntityTemplate->userGroupTemplate, $objDcaEntityTemplate, $strTargetFile, array('moduleName' => $objEntityTemplate->moduleName));
                     foreach (static::$arrLanguages as $strLanguage) {
                         $strPrefix = $strLanguage != 'en' ? $strLanguage . '_' : '';
                         // tl_user - language
                         $strTargetFile = $strTargetDir . '/languages/' . $strLanguage . '/tl_user.php';
                         \System::loadLanguageFile('default', $strLanguage, true);
                         static::parseTemplate($strPrefix . $objDcaEntityTemplate->userLanguageTemplate, $objDcaEntityTemplate, $strTargetFile, array('moduleName' => $objEntityTemplate->moduleName));
                         \System::loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
                     }
                     foreach (static::$arrLanguages as $strLanguage) {
                         $strPrefix = $strLanguage != 'en' ? $strLanguage . '_' : '';
                         // tl_user_group - language
                         $strTargetFile = $strTargetDir . '/languages/' . $strLanguage . '/tl_user_group.php';
                         \System::loadLanguageFile('default', $strLanguage, true);
                         static::parseTemplate($strPrefix . $objDcaEntityTemplate->userGroupLanguageTemplate, $objDcaEntityTemplate, $strTargetFile, array('moduleName' => $objEntityTemplate->moduleName));
                         \System::loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
                     }
                 }
                 // languages
                 if ($objDcaEntityTemplate->addLanguages) {
                     foreach (static::$arrLanguages as $strLanguage) {
                         $strPrefix = $strLanguage != 'en' ? $strLanguage . '_' : '';
                         $strTargetFile = $strTargetDir . '/languages/' . $strLanguage . '/tl_' . $objDcaEntityTemplate->dcaName . '.php';
                         \System::loadLanguageFile('default', $strLanguage, true);
                         static::parseTemplate($strPrefix . $objDcaEntityTemplate->dcaLangTemplate, $objDcaEntityTemplate, $strTargetFile);
                         \System::loadLanguageFile('default', $GLOBALS['TL_LANGUAGE'], true);
                     }
                 }
                 // models
                 if ($objDcaEntityTemplate->addModel) {
                     $strTargetFile = $strTargetDir . '/models/' . $objDcaEntityTemplate->entityClassName . 'Model.php';
                     static::parseTemplate($objDcaEntityTemplate->modelTemplate, $objDcaEntityTemplate, $strTargetFile, array('moduleNamespace' => $objEntityTemplate->moduleNamespace));
                 }
             }
         }
     }
     \Message::addInfo($GLOBALS['TL_LANG']['MSC']['entity_generator']['updateDatabase']);
     static::redirectToList();
 }