protected function generate()
 {
     if (!is_dir(TL_ROOT . '/' . $this->cacheDirectory)) {
         $this->makeCacheDirectory();
     }
     $file = new \File($this->cacheFile);
     $file->truncate();
     $file->putContent($file->path, json_encode($this->cacheUrl));
     $automator = new \Automator();
     $automator->purgePageCache();
 }
 /**
  * create CSS File
  * file :: assets/css/divElements.css
  */
 public function createCSS()
 {
     // create File if doesn`t exists
     $file = new \File('system/modules/swatchBook/assets/css/divElements.css');
     // result Color
     $groupPalette = \Database::getInstance()->execute("SELECT pid,count(pid) AS count FROM tl_swatchBookColors GROUP BY pid")->fetchAllAssoc();
     $palettes = \Database::getInstance()->execute("SELECT id,pid,title,color FROM tl_swatchBookColors")->fetchAllAssoc();
     foreach ($groupPalette as $c) {
         $i = 1;
         foreach ($palettes as $v) {
             if ($c['pid'] == $v['pid']) {
                 $css[] = sprintf("#sb-container-%s div:nth-child(%s){background-color: #%s;box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);-webkit-box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);-moz-box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);}", $v['pid'], $i <= $c['count'] ? $i : $c['count'], $v['color'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id']);
                 $i++;
             }
         }
     }
     \File::putContent('system/modules/swatchBook/assets/css/divElements.css', implode("\n", $css));
 }
Example #3
0
 /**
  * create/update CSS File
  * file :: web/bundles/swatchbook/css/divElements.css
  */
 public function writeCSS()
 {
     $this->syncSwatchbookColors();
     $objTemplate = new BackendTemplate('be_swatchbookSync');
     $objTemplate->hrefBack = ampersand(str_replace('&key=sync', '', \Environment::get('request')));
     $objTemplate->goBack = $GLOBALS['TL_LANG']['MSC']['goBack'];
     if (!$this->isUpdate) {
         $objTemplate->headline = $GLOBALS['TL_LANG']['swatchbook']['syncHeadlineNo'];
         return $objTemplate->parse();
     } else {
         /**
          * load File if doesn`t exists
          */
         $file = new \File('src/CtEye/swatchbook-bundle/src/Resources/public/css/divElements.css');
         /**
          * result Color
          */
         $groupPallets = \Database::getInstance()->execute("SELECT pid,count(pid) AS count FROM tl_swatchbookColors GROUP BY pid")->fetchAllAssoc();
         $pallets = \Database::getInstance()->execute("SELECT id,pid,title,color FROM tl_swatchbookColors")->fetchAllAssoc();
         foreach ($groupPallets as $c) {
             $i = 1;
             foreach ($pallets as $v) {
                 if ($c['pid'] == $v['pid']) {
                     $pal[$v['pid']] = $v['pid'];
                     $css[] = sprintf("#sb-container-%s div:nth-child(%s){background-color: #%s;box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);-webkit-box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);-moz-box-shadow: -1px -1px 3px rgba(0,0,0,0.1), %spx %spx %spx rgba(0,0,0,0.1);}", $v['pid'], $i <= $c['count'] ? $i : $c['count'], $v['color'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id'], $v['id']);
                     $i++;
                 }
             }
         }
         /**
          * write CSS content
          */
         \File::putContent('src/CtEye/swatchbook-bundle/src/Resources/public/css/divElements.css', implode("\n", $css));
         $objTemplate->headline = $GLOBALS['TL_LANG']['swatchbook']['syncHeadline'];
         $objTemplate->pallets = $i > 1 ? sprintf($GLOBALS['TL_LANG']['swatchbook']['syncPalletMulti'], $i) : sprintf($GLOBALS['TL_LANG']['swatchbook']['syncPalletSingle'], $i);
         return $objTemplate->parse();
     }
 }
Example #4
0
 /**
  * Generate an XML files and save them to the root directory
  * @param array
  */
 protected function generateFiles($arrFeed)
 {
     $arrArchives = deserialize($arrFeed['archives']);
     if (!is_array($arrArchives) || empty($arrArchives)) {
         return;
     }
     $strType = $arrFeed['format'] == 'atom' ? 'generateAtom' : 'generateRss';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new \Feed($strFile);
     $objFeed->link = $strLink;
     $objFeed->title = $arrFeed['title'];
     $objFeed->description = $arrFeed['description'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->published = $arrFeed['tstamp'];
     $arrCategories = deserialize($arrFeed['categories']);
     // Filter by categories
     if (is_array($arrCategories) && !empty($arrCategories)) {
         $GLOBALS['NEWS_FILTER_CATEGORIES'] = true;
         $GLOBALS['NEWS_FILTER_DEFAULT'] = $arrCategories;
     } else {
         $GLOBALS['NEWS_FILTER_CATEGORIES'] = false;
     }
     // Get the items
     if ($arrFeed['maxItems'] > 0) {
         $objArticle = \NewsModel::findPublishedByPids($arrArchives, null, $arrFeed['maxItems']);
     } else {
         $objArticle = \NewsModel::findPublishedByPids($arrArchives);
     }
     // Parse the items
     if ($objArticle !== null) {
         $arrUrls = array();
         while ($objArticle->next()) {
             $jumpTo = $objArticle->getRelated('pid')->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $this->generateFrontendUrl($objParent->row(), $GLOBALS['TL_CONFIG']['useAutoItem'] && !$GLOBALS['TL_CONFIG']['disableAlias'] ? '/%s' : '/items/%s', $objParent->language);
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objArticle->source == 'default') {
                 continue;
             }
             // Get the categories
             if ($arrFeed['categories_show']) {
                 $arrCategories = array();
                 if (($objCategories = NewsCategoryModel::findPublishedByIds(deserialize($objArticle->categories, true))) !== null) {
                     $arrCategories = $objCategories->fetchEach('title');
                 }
             }
             $strUrl = $arrUrls[$jumpTo];
             $objItem = new \FeedItem();
             // Add the categories to the title
             if ($arrFeed['categories_show'] == 'title') {
                 $objItem->title = sprintf('[%s] %s', implode(', ', $arrCategories), $objArticle->headline);
             } else {
                 $objItem->title = $objArticle->headline;
             }
             $objItem->link = $this->getLink($objArticle, $strUrl, $strLink);
             $objItem->published = $objArticle->date;
             $objItem->author = $objArticle->authorName;
             // Prepare the description
             if ($arrFeed['source'] == 'source_text') {
                 $strDescription = '';
                 $objElement = \ContentModel::findPublishedByPidAndTable($objArticle->id, 'tl_news');
                 if ($objElement !== null) {
                     while ($objElement->next()) {
                         $strDescription .= $this->getContentElement($objElement->id);
                     }
                 }
             } else {
                 $strDescription = $objArticle->teaser;
             }
             // Add the categories to the description
             if ($arrFeed['categories_show'] == 'text_before' || $arrFeed['categories_show'] == 'text_after') {
                 $strCategories = '<p>' . $GLOBALS['TL_LANG']['MSC']['newsCategories'] . ' ' . implode(', ', $arrCategories) . '</p>';
                 if ($arrFeed['categories_show'] == 'text_before') {
                     $strDescription = $strCategories . $strDescription;
                 } else {
                     $strDescription .= $strCategories;
                 }
             }
             $strDescription = $this->replaceInsertTags($strDescription, false);
             $objItem->description = $this->convertRelativeUrls($strDescription, $strLink);
             // Add the article image as enclosure
             if ($objArticle->addImage) {
                 $objFile = \FilesModel::findByUuid($objArticle->singleSRC);
                 if ($objFile !== null) {
                     $objItem->addEnclosure($objFile->path);
                 }
             }
             // Enclosures
             if ($objArticle->addEnclosure) {
                 $arrEnclosure = deserialize($objArticle->enclosure, true);
                 if (is_array($arrEnclosure)) {
                     $objFile = \FilesModel::findMultipleByUuids($arrEnclosure);
                     if ($objFile !== null) {
                         while ($objFile->next()) {
                             $objItem->addEnclosure($objFile->path);
                         }
                     }
                 }
             }
             $objFeed->addItem($objItem);
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
Example #5
0
File: Theme.php Project: Jobu/core
 /**
  * Extract the theme files and write the data to the database
  *
  * @param array $arrFiles
  * @param array $arrDbFields
  */
 protected function extractThemeFiles($arrFiles, $arrDbFields)
 {
     foreach ($arrFiles as $strZipFile) {
         $xml = null;
         // Open the archive
         $objArchive = new \ZipReader($strZipFile);
         // Extract all files
         while ($objArchive->next()) {
             // Load the XML file
             if ($objArchive->file_name == 'theme.xml') {
                 $xml = new \DOMDocument();
                 $xml->preserveWhiteSpace = false;
                 $xml->loadXML($objArchive->unzip());
                 continue;
             }
             // Limit file operations to files and the templates directory
             if (strncmp($objArchive->file_name, 'files/', 6) !== 0 && strncmp($objArchive->file_name, 'tl_files/', 9) !== 0 && strncmp($objArchive->file_name, 'templates/', 10) !== 0) {
                 \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidFile'], $objArchive->file_name));
                 continue;
             }
             // Extract the files
             try {
                 \File::putContent($this->customizeUploadPath($objArchive->file_name), $objArchive->unzip());
             } catch (\Exception $e) {
                 \Message::addError($e->getMessage());
             }
         }
         // Continue if there is no XML file
         if (!$xml instanceof \DOMDocument) {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['tl_theme']['missing_xml'], basename($strZipFile)));
             continue;
         }
         $arrMapper = array();
         $tables = $xml->getElementsByTagName('table');
         $arrNewFolders = array();
         // Extract the folder names from the XML file
         for ($i = 0; $i < $tables->length; $i++) {
             if ($tables->item($i)->getAttribute('name') == 'tl_theme') {
                 $fields = $tables->item($i)->childNodes->item(0)->childNodes;
                 for ($k = 0; $k < $fields->length; $k++) {
                     if ($fields->item($k)->getAttribute('name') == 'folders') {
                         $arrNewFolders = deserialize($fields->item($k)->nodeValue);
                         break;
                     }
                 }
                 break;
             }
         }
         // Sync the new folder(s)
         if (!empty($arrNewFolders) && is_array($arrNewFolders)) {
             foreach ($arrNewFolders as $strFolder) {
                 \Dbafs::addResource($this->customizeUploadPath($strFolder));
             }
         }
         // Lock the tables
         $arrLocks = array('tl_files' => 'WRITE', 'tl_theme' => 'WRITE', 'tl_style_sheet' => 'WRITE', 'tl_style' => 'WRITE', 'tl_module' => 'WRITE', 'tl_layout' => 'WRITE', 'tl_image_size' => 'WRITE', 'tl_image_size_item' => 'WRITE');
         // Load the DCAs of the locked tables (see #7345)
         foreach (array_keys($arrLocks) as $table) {
             $this->loadDataContainer($table);
         }
         $this->Database->lockTables($arrLocks);
         // Get the current auto_increment values
         $tl_files = $this->Database->getNextId('tl_files');
         $tl_theme = $this->Database->getNextId('tl_theme');
         $tl_style_sheet = $this->Database->getNextId('tl_style_sheet');
         $tl_style = $this->Database->getNextId('tl_style');
         $tl_module = $this->Database->getNextId('tl_module');
         $tl_layout = $this->Database->getNextId('tl_layout');
         $tl_image_size = $this->Database->getNextId('tl_image_size');
         $tl_image_size_item = $this->Database->getNextId('tl_image_size_item');
         // Loop through the tables
         for ($i = 0; $i < $tables->length; $i++) {
             $rows = $tables->item($i)->childNodes;
             $table = $tables->item($i)->getAttribute('name');
             // Skip invalid tables
             if (!in_array($table, array_keys($arrLocks))) {
                 continue;
             }
             // Get the order fields
             $objDcaExtractor = \DcaExtractor::getInstance($table);
             $arrOrder = $objDcaExtractor->getOrderFields();
             // Loop through the rows
             for ($j = 0; $j < $rows->length; $j++) {
                 $set = array();
                 $fields = $rows->item($j)->childNodes;
                 // Loop through the fields
                 for ($k = 0; $k < $fields->length; $k++) {
                     $value = $fields->item($k)->nodeValue;
                     $name = $fields->item($k)->getAttribute('name');
                     // Skip NULL values
                     if ($value == 'NULL') {
                         continue;
                     } elseif ($name == 'id') {
                         $id = ${$table}++;
                         $arrMapper[$table][$value] = $id;
                         $value = $id;
                     } elseif ($name == 'pid') {
                         if ($table == 'tl_style') {
                             $value = $arrMapper['tl_style_sheet'][$value];
                         } elseif ($table == 'tl_image_size_item') {
                             $value = $arrMapper['tl_image_size'][$value];
                         } else {
                             $value = $arrMapper['tl_theme'][$value];
                         }
                     } elseif ($name == 'fallback') {
                         $value = '';
                     } elseif ($table == 'tl_layout' && $name == 'stylesheet') {
                         $stylesheets = deserialize($value);
                         if (is_array($stylesheets)) {
                             foreach (array_keys($stylesheets) as $key) {
                                 $stylesheets[$key] = $arrMapper['tl_style_sheet'][$stylesheets[$key]];
                             }
                             $value = serialize($stylesheets);
                         }
                     } elseif ($table == 'tl_layout' && $name == 'modules') {
                         $modules = deserialize($value);
                         if (is_array($modules)) {
                             foreach ($modules as $key => $mod) {
                                 if ($mod['mod'] > 0) {
                                     $modules[$key]['mod'] = $arrMapper['tl_module'][$mod['mod']];
                                 }
                             }
                             $value = serialize($modules);
                         }
                     } elseif (($table == 'tl_theme' || $table == 'tl_style_sheet') && $name == 'name') {
                         $objCount = $this->Database->prepare("SELECT COUNT(*) AS count FROM " . $table . " WHERE name=?")->execute($value);
                         if ($objCount->count > 0) {
                             $value = preg_replace('/( |\\-)[0-9]+$/', '', $value);
                             $value .= ($table == 'tl_style_sheet' ? '-' : ' ') . ${$table};
                         }
                     } elseif (($table == 'tl_style_sheet' || $table == 'tl_style' || $table == 'tl_files' && $name == 'path') && strpos($value, 'files') !== false) {
                         $tmp = deserialize($value);
                         if (is_array($tmp)) {
                             foreach ($tmp as $kk => $vv) {
                                 $tmp[$kk] = $this->customizeUploadPath($vv);
                             }
                             $value = serialize($tmp);
                         } else {
                             $value = $this->customizeUploadPath($value);
                         }
                     } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'fileTree' && !$GLOBALS['TL_DCA'][$table]['fields'][$name]['eval']['multiple']) {
                         if (!$value) {
                             $value = null;
                             // Contao >= 3.2
                         } else {
                             // Do not use the FilesModel here – tables are locked!
                             $objFile = $this->Database->prepare("SELECT uuid FROM tl_files WHERE path=?")->limit(1)->execute($this->customizeUploadPath($value));
                             $value = $objFile->uuid;
                         }
                     } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'fileTree' || in_array($name, $arrOrder)) {
                         $tmp = deserialize($value);
                         if (is_array($tmp)) {
                             foreach ($tmp as $kk => $vv) {
                                 // Do not use the FilesModel here – tables are locked!
                                 $objFile = $this->Database->prepare("SELECT uuid FROM tl_files WHERE path=?")->limit(1)->execute($this->customizeUploadPath($vv));
                                 $tmp[$kk] = $objFile->uuid;
                             }
                             $value = serialize($tmp);
                         }
                     } elseif ($GLOBALS['TL_DCA'][$table]['fields'][$name]['inputType'] == 'imageSize') {
                         $imageSizes = deserialize($value, true);
                         if (!empty($imageSizes)) {
                             if (is_numeric($imageSizes[2])) {
                                 $imageSizes[2] = $arrMapper['tl_image_size'][$imageSizes[2]];
                             }
                         }
                         $value = serialize($imageSizes);
                     }
                     $set[$name] = $value;
                 }
                 // Skip fields that are not in the database (e.g. because of missing extensions)
                 foreach ($set as $k => $v) {
                     if (!in_array($k, $arrDbFields[$table])) {
                         unset($set[$k]);
                     }
                 }
                 // Create the templates folder even if it is empty (see #4793)
                 if ($table == 'tl_theme' && isset($set['templates']) && strncmp($set['templates'], 'templates/', 10) === 0 && !is_dir(TL_ROOT . '/' . $set['templates'])) {
                     new \Folder($set['templates']);
                 }
                 // Update tl_files (entries have been created by the Dbafs class)
                 if ($table == 'tl_files') {
                     $this->Database->prepare("UPDATE {$table} %s WHERE path=?")->set($set)->execute($set['path']);
                 } else {
                     $this->Database->prepare("INSERT INTO {$table} %s")->set($set)->execute();
                 }
             }
         }
         // Unlock the tables
         $this->Database->unlockTables();
         // Update the style sheets
         $this->import('StyleSheets');
         $this->StyleSheets->updateStyleSheets();
         // Notify the user
         \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_theme']['theme_imported'], basename($strZipFile)));
         // HOOK: add custom logic
         if (isset($GLOBALS['TL_HOOKS']['extractThemeFiles']) && is_array($GLOBALS['TL_HOOKS']['extractThemeFiles'])) {
             $intThemeId = empty($arrMapper['tl_theme']) ? null : reset($arrMapper['tl_theme']);
             foreach ($GLOBALS['TL_HOOKS']['extractThemeFiles'] as $callback) {
                 \System::importStatic($callback[0])->{$callback}[1]($xml, $objArchive, $intThemeId, $arrMapper);
             }
         }
         unset($tl_files, $tl_theme, $tl_style_sheet, $tl_style, $tl_module, $tl_layout, $tl_image_size, $tl_image_size_item);
     }
     \System::setCookie('BE_PAGE_OFFSET', 0, 0);
     $this->Session->remove('uploaded_themes');
     // Redirect
     $this->redirect(str_replace('&key=importTheme', '', \Environment::get('request')));
 }
Example #6
0
 /**
  * Unprotect the folder by adding a .public file
  */
 public function unprotect()
 {
     if (!file_exists(TL_ROOT . '/' . $this->strFolder . '/.public')) {
         \File::putContent($this->strFolder . '/.public', '');
     }
 }
Example #7
0
 /**
  * Protect the folder by adding an .htaccess file
  */
 public function protect()
 {
     if (!file_exists(TL_ROOT . '/' . $this->strFolder . '/.htaccess')) {
         \File::putContent($this->strFolder . '/.htaccess', "<IfModule !mod_authz_core.c>\n  Order deny,allow\n  Deny from all\n</IfModule>\n<IfModule mod_authz_core.c>\n  Require all denied\n</IfModule>");
     }
 }
Example #8
0
 /**
  * Generate an XML files and save them to the root directory
  * @param array
  */
 protected function generateFiles($arrFeed)
 {
     $arrArchives = deserialize($arrFeed['archives']);
     if (!is_array($arrArchives) || empty($arrArchives)) {
         return;
     }
     switch ($arrFeed['format']) {
         case 'rss':
             $strType = 'generateRss';
             break;
         case 'atom':
             $strType = 'generateAtom';
             break;
         case 'podcast':
             $strType = 'generatePodcast';
             break;
     }
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new FeedPodcast($strFile);
     $objFeed->link = $strLink;
     $objFeed->title = $arrFeed['title'];
     $objFeed->description = $arrFeed['description'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->published = $arrFeed['tstamp'];
     //Add Feed Image
     if ($arrFeed['format'] == 'podcast') {
         $objFile = \FilesModel::findByUuid($arrFeed['podcastSingleSRC']);
         if ($objFile !== null) {
             $objFeed->imageUrl = \Environment::get('base') . $objFile->path;
         }
     }
     // Get the items
     if ($arrFeed['maxItems'] > 0) {
         $objSermons = \SermonerItemsModel::findPublishedByPids($arrArchives, $arrFeed['maxItems']);
     } else {
         $objSermons = \SermonerItemsModel::findPublishedByPids($arrArchives);
     }
     // Parse the items
     if ($objSermons !== null) {
         $arrUrls = array();
         while ($objSermons->next()) {
             $jumpTo = $objSermons->getRelated('pid')->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $this->generateFrontendUrl($objParent->row(), $GLOBALS['TL_CONFIG']['useAutoItem'] && !$GLOBALS['TL_CONFIG']['disableAlias'] ? '/%s' : '/items/%s', $objParent->language);
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objSermons->source == 'default') {
                 continue;
             }
             $strUrl = $arrUrls[$jumpTo];
             $objItem = new \FeedItem();
             $objItem->title = $objSermons->title;
             $objItem->link = $strLink . sprintf($strUrl, $objSermons->alias != '' && !$GLOBALS['TL_CONFIG']['disableAlias'] ? $objSermons->alias : $objSermons->id);
             $objItem->published = $objSermons->date;
             $objItem->author = $objSermons->speaker;
             // Prepare the description
             if ($arrFeed['format'] == 'podcast') {
                 $objItem->description = $this->replaceSermonInsertTags($arrFeed['podcastSubtitle'], $objSermons);
             }
             // Add the article image as enclosure
             if ($objSermons->addImage) {
                 $objFile = \FilesModel::findByUuid($objSermons->singleSRC);
                 if ($objFile !== null) {
                     $objItem->addEnclosure($objFile->path);
                 }
             }
             // Add the Sermon Audio File
             if ($objSermons->audioSingleSRC) {
                 $objFile = \FilesModel::findByUuid($objSermons->audioSingleSRC);
                 if ($objFile !== null) {
                     $objItem->addEnclosure($objFile->path);
                     //Prepare the duration if it's a podcast
                     if ($arrFeed['format'] == 'podcast') {
                         $this->import('getid3');
                         $getID3 = new \getID3();
                         $mp3FileInfo = $getID3->analyze(TL_ROOT . '/' . $objFile->path);
                         $objItem->duration = @$mp3FileInfo['playtime_string'];
                     }
                 }
             }
             $objFeed->addItem($objItem);
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}()));
 }
Example #9
0
 /**
  * Generate module
  */
 protected function compile()
 {
     // Create files
     if (\Input::post('FORM_SUBMIT') == 'tl_extension') {
         $objModule = $this->Database->prepare("SELECT * FROM tl_extension WHERE id=?")->limit(1)->execute($this->objDc->id);
         if ($objModule->numRows < 1) {
             return;
         }
         // Disable the debug mode (see #7068)
         \Config::set('debugMode', false);
         // config/config.php
         $tplConfig = $this->newTemplate('dev_config', $objModule);
         \File::putContent('system/modules/' . $objModule->folder . '/config/config.php', $tplConfig->parse());
         // config/autoload.ini
         $tplConfig = $this->newTemplate('dev_ini', $objModule);
         \File::putContent('system/modules/' . $objModule->folder . '/config/autoload.ini', $tplConfig->parse());
         // Back end
         if ($objModule->addBeMod) {
             $arrClasses = array_filter(trimsplit(',', $objModule->beClasses));
             // Classes
             foreach ($arrClasses as $strClass) {
                 $tplClass = $this->newTemplate('dev_beClass', $objModule);
                 $tplClass->class = $strClass;
                 \File::putContent('system/modules/' . $objModule->folder . '/' . $this->guessSubfolder($strClass) . '/' . $strClass . '.php', $tplClass->parse());
             }
             $arrTables = array_filter(trimsplit(',', $objModule->beTables));
             // Back end data container files
             foreach ($arrTables as $strTable) {
                 $tplTable = $this->newTemplate('dev_dca', $objModule);
                 $tplTable->table = $strTable;
                 \File::putContent('system/modules/' . $objModule->folder . '/dca/' . $strTable . '.php', $tplTable->parse());
             }
             $arrTemplates = array_filter(trimsplit(',', $objModule->beTemplates));
             // Templates
             foreach ($arrTemplates as $strTemplate) {
                 $tplTemplate = $this->newTemplate('dev_beTemplate', $objModule);
                 \File::putContent('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.html5', $tplTemplate->parse());
             }
         }
         $arrTables = array();
         // Front end
         if ($objModule->addFeMod) {
             $arrClasses = array_filter(trimsplit(',', $objModule->feClasses));
             // Classes
             foreach ($arrClasses as $strClass) {
                 $tplClass = $this->newTemplate('dev_feClass', $objModule);
                 $tplClass->class = $strClass;
                 $tplClass->extends = $this->guessParentClass($strClass);
                 \File::putContent('system/modules/' . $objModule->folder . '/' . $this->guessSubfolder($strClass) . '/' . $strClass . '.php', $tplClass->parse());
             }
             $arrTables = array_filter(trimsplit(',', $objModule->feTables));
             // Front end data container files
             foreach ($arrTables as $strTable) {
                 $tplTable = $this->newTemplate('dev_feDca', $objModule);
                 $tplTable->table = $strTable;
                 \File::putContent('system/modules/' . $objModule->folder . '/dca/' . $strTable . '.php', $tplTable->parse());
             }
             // Models
             foreach ($arrTables as $strTable) {
                 $strModel = \Model::getClassFromTable($strTable);
                 $tplTable = $this->newTemplate('dev_model', $objModule);
                 $tplTable->table = $strTable;
                 $tplTable->class = $strModel;
                 \File::putContent('system/modules/' . $objModule->folder . '/models/' . $strModel . '.php', $tplTable->parse());
             }
             $arrTemplates = array_filter(trimsplit(',', $objModule->feTemplates));
             // Templates
             foreach ($arrTemplates as $strTemplate) {
                 $tplTemplate = $this->newTemplate('dev_feTemplate', $objModule);
                 $objTemplate = new \File('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.html5', true);
                 $objTemplate->write($tplTemplate->parse());
                 $objTemplate->close();
                 $objTemplate->copyTo('system/modules/' . $objModule->folder . '/templates/' . $strTemplate . '.xhtml');
             }
         }
         // Language packs
         if ($objModule->addLanguage) {
             $arrLanguages = array_filter(trimsplit(',', $objModule->languages));
             foreach ($arrLanguages as $strLanguage) {
                 // languages/xx/default.php
                 $tplLanguage = $this->newTemplate('dev_default', $objModule);
                 $tplLanguage->language = $strLanguage;
                 \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/default.php', $tplLanguage->parse());
                 // languages/xx/modules.php
                 $tplLanguage = $this->newTemplate('dev_modules', $objModule);
                 $tplLanguage->language = $strLanguage;
                 \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/modules.php', $tplLanguage->parse());
                 // languages/xx/<table>.php
                 foreach ($arrTables as $strTable) {
                     $tplLanguage = $this->newTemplate('dev_table', $objModule);
                     $tplLanguage->language = $strLanguage;
                     $tplLanguage->table = $strTable;
                     \File::putContent('system/modules/' . $objModule->folder . '/languages/' . $strLanguage . '/' . $strTable . '.php', $tplLanguage->parse());
                 }
             }
         }
         // Public folder
         $tplConfig = $this->newTemplate('dev_htaccess', $objModule);
         \File::putContent('system/modules/' . $objModule->folder . '/assets/.htaccess', $tplConfig->parse());
         // Confirm and reload
         \Message::addConfirmation($GLOBALS['TL_LANG']['tl_extension']['confirm']);
         $this->reload();
     }
     $this->Template->base = \Environment::get('base');
     $this->Template->href = $this->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_extension']['make'][0]);
     $this->Template->headline = sprintf($GLOBALS['TL_LANG']['tl_extension']['headline'], \Input::get('id'));
     $this->Template->explain = $GLOBALS['TL_LANG']['tl_extension']['make'][1];
     $this->Template->label = $GLOBALS['TL_LANG']['tl_extension']['label'];
 }
Example #10
0
 /**
  * Generate an XML files and save them to the root directory
  *
  * @param array $arrFeed
  */
 protected function generateFiles($arrFeed)
 {
     $arrArchives = deserialize($arrFeed['archives']);
     if (!is_array($arrArchives) || empty($arrArchives)) {
         return;
     }
     $strType = $arrFeed['format'] == 'atom' ? 'generateAtom' : 'generateRss';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new \Feed($strFile);
     $objFeed->link = $strLink;
     $objFeed->title = $arrFeed['title'];
     $objFeed->description = $arrFeed['description'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->published = $arrFeed['tstamp'];
     // Get the items
     if ($arrFeed['maxItems'] > 0) {
         $objArticle = \NewsModel::findPublishedByPids($arrArchives, null, $arrFeed['maxItems']);
     } else {
         $objArticle = \NewsModel::findPublishedByPids($arrArchives);
     }
     // Parse the items
     if ($objArticle !== null) {
         $arrUrls = array();
         while ($objArticle->next()) {
             /** @var \PageModel $objPage */
             $objPage = $objArticle->getRelated('pid');
             $jumpTo = $objPage->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $objParent->getFrontendUrl(\Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/%s' : '/items/%s');
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objArticle->source == 'default') {
                 continue;
             }
             $strUrl = $arrUrls[$jumpTo];
             $objItem = new \FeedItem();
             $objItem->title = $objArticle->headline;
             $objItem->link = $this->getLink($objArticle, $strUrl, $strLink);
             $objItem->published = $objArticle->date;
             $objItem->author = $objArticle->authorName;
             // Prepare the description
             if ($arrFeed['source'] == 'source_text') {
                 $strDescription = '';
                 $objElement = \ContentModel::findPublishedByPidAndTable($objArticle->id, 'tl_news');
                 if ($objElement !== null) {
                     // Overwrite the request (see #7756)
                     $strRequest = \Environment::get('request');
                     \Environment::set('request', $objItem->link);
                     while ($objElement->next()) {
                         $strDescription .= $this->getContentElement($objElement->current());
                     }
                     \Environment::set('request', $strRequest);
                 }
             } else {
                 $strDescription = $objArticle->teaser;
             }
             $strDescription = $this->replaceInsertTags($strDescription, false);
             $objItem->description = $this->convertRelativeUrls($strDescription, $strLink);
             // Add the article image as enclosure
             if ($objArticle->addImage) {
                 $objFile = \FilesModel::findByUuid($objArticle->singleSRC);
                 if ($objFile !== null) {
                     $objItem->addEnclosure($objFile->path, $strLink);
                 }
             }
             // Enclosures
             if ($objArticle->addEnclosure) {
                 $arrEnclosure = deserialize($objArticle->enclosure, true);
                 if (is_array($arrEnclosure)) {
                     $objFile = \FilesModel::findMultipleByUuids($arrEnclosure);
                     if ($objFile !== null) {
                         while ($objFile->next()) {
                             $objItem->addEnclosure($objFile->path, $strLink);
                         }
                     }
                 }
             }
             $objFeed->addItem($objItem);
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
 protected function putContentForCacheFile()
 {
     $this->cacheFile->truncate();
     $this->cacheFile->putContent($this->cacheFile->path, json_encode($this->cacheUrl));
 }
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var \PageModel $objPage */
     global $objPage;
     // Mark the x and y parameter as used (see #4277)
     if (isset($_GET['x'])) {
         \Input::get('x');
         \Input::get('y');
     }
     // Trigger the search module from a custom form
     if (!isset($_GET['keywords']) && \Input::post('FORM_SUBMIT') == 'tl_search') {
         $_GET['keywords'] = \Input::post('keywords');
         $_GET['query_type'] = \Input::post('query_type');
         $_GET['per_page'] = \Input::post('per_page');
     }
     $blnFuzzy = $this->fuzzy;
     $strQueryType = \Input::get('query_type') ?: $this->queryType;
     $strKeywords = trim(\Input::get('keywords'));
     /** @var \FrontendTemplate|object $objFormTemplate */
     $objFormTemplate = new \FrontendTemplate($this->searchType == 'advanced' ? 'mod_search_advanced' : 'mod_search_simple');
     $objFormTemplate->uniqueId = $this->id;
     $objFormTemplate->queryType = $strQueryType;
     $objFormTemplate->keyword = specialchars($strKeywords);
     $objFormTemplate->keywordLabel = $GLOBALS['TL_LANG']['MSC']['keywords'];
     $objFormTemplate->optionsLabel = $GLOBALS['TL_LANG']['MSC']['options'];
     $objFormTemplate->search = specialchars($GLOBALS['TL_LANG']['MSC']['searchLabel']);
     $objFormTemplate->matchAll = specialchars($GLOBALS['TL_LANG']['MSC']['matchAll']);
     $objFormTemplate->matchAny = specialchars($GLOBALS['TL_LANG']['MSC']['matchAny']);
     $objFormTemplate->id = \Config::get('disableAlias') && \Input::get('id') ? \Input::get('id') : false;
     $objFormTemplate->action = ampersand(\Environment::get('indexFreeRequest'));
     // Redirect page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $objFormTemplate->action = $this->generateFrontendUrl($objTarget->row());
     }
     $this->Template->form = $objFormTemplate->parse();
     $this->Template->pagination = '';
     $this->Template->results = '';
     // Execute the search if there are keywords
     if ($strKeywords != '' && $strKeywords != '*' && !$this->jumpTo) {
         // Reference page
         if ($this->rootPage > 0) {
             $intRootId = $this->rootPage;
             $arrPages = $this->Database->getChildRecords($this->rootPage, 'tl_page');
             array_unshift($arrPages, $this->rootPage);
         } else {
             $intRootId = $objPage->rootId;
             $arrPages = $this->Database->getChildRecords($objPage->rootId, 'tl_page');
         }
         // HOOK: add custom logic (see #5223)
         if (isset($GLOBALS['TL_HOOKS']['customizeSearch']) && is_array($GLOBALS['TL_HOOKS']['customizeSearch'])) {
             foreach ($GLOBALS['TL_HOOKS']['customizeSearch'] as $callback) {
                 $this->import($callback[0]);
                 $this->{$callback[0]}->{$callback[1]}($arrPages, $strKeywords, $strQueryType, $blnFuzzy);
             }
         }
         // Return if there are no pages
         if (!is_array($arrPages) || empty($arrPages)) {
             $this->log('No searchable pages found', __METHOD__, TL_ERROR);
             return;
         }
         $arrResult = null;
         $strChecksum = md5($strKeywords . $strQueryType . $intRootId . $blnFuzzy);
         $query_starttime = microtime(true);
         $strCacheFile = 'system/cache/search/' . $strChecksum . '.json';
         // Load the cached result
         if (file_exists(TL_ROOT . '/' . $strCacheFile)) {
             $objFile = new \File($strCacheFile, true);
             if ($objFile->mtime > time() - 1800) {
                 $arrResult = json_decode($objFile->getContent(), true);
             } else {
                 $objFile->delete();
             }
         }
         // Cache the result
         if ($arrResult === null) {
             try {
                 $objSearch = \Search::searchFor($strKeywords, $strQueryType == 'or', $arrPages, 0, 0, $blnFuzzy);
                 $arrResult = $objSearch->fetchAllAssoc();
             } catch (\Exception $e) {
                 $this->log('Website search failed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
                 $arrResult = array();
             }
             \File::putContent($strCacheFile, json_encode($arrResult));
         }
         $query_endtime = microtime(true);
         // Sort out protected pages
         if (\Config::get('indexProtected') && !BE_USER_LOGGED_IN) {
             $this->import('FrontendUser', 'User');
             foreach ($arrResult as $k => $v) {
                 if ($v['protected']) {
                     if (!FE_USER_LOGGED_IN) {
                         unset($arrResult[$k]);
                     } else {
                         $groups = deserialize($v['groups']);
                         if (!is_array($groups) || empty($groups) || !count(array_intersect($groups, $this->User->groups))) {
                             unset($arrResult[$k]);
                         }
                     }
                 }
             }
             $arrResult = array_values($arrResult);
         }
         $count = count($arrResult);
         $this->Template->count = $count;
         $this->Template->page = null;
         $this->Template->keywords = $strKeywords;
         // No results
         if ($count < 1) {
             $this->Template->header = sprintf($GLOBALS['TL_LANG']['MSC']['sEmpty'], $strKeywords);
             $this->Template->duration = substr($query_endtime - $query_starttime, 0, 6) . ' ' . $GLOBALS['TL_LANG']['MSC']['seconds'];
             return;
         }
         $from = 1;
         $to = $count;
         // Pagination
         if ($this->perPage > 0) {
             $id = 'page_s' . $this->id;
             $page = \Input::get($id) !== null ? \Input::get($id) : 1;
             $per_page = \Input::get('per_page') ?: $this->perPage;
             // Do not index or cache the page if the page number is outside the range
             if ($page < 1 || $page > max(ceil($count / $per_page), 1)) {
                 /** @var \PageError404 $objHandler */
                 $objHandler = new $GLOBALS['TL_PTY']['error_404']();
                 $objHandler->generate($objPage->id);
             }
             $from = ($page - 1) * $per_page + 1;
             $to = $from + $per_page > $count ? $count : $from + $per_page - 1;
             // Pagination menu
             if ($to < $count || $from > 1) {
                 $objPagination = new \Pagination($count, $per_page, \Config::get('maxPaginationLinks'), $id);
                 $this->Template->pagination = $objPagination->generate("\n  ");
             }
             $this->Template->page = $page;
         }
         // Get the results
         for ($i = $from - 1; $i < $to && $i < $count; $i++) {
             /** @var \FrontendTemplate|object $objTemplate */
             $objTemplate = new \FrontendTemplate($this->searchTpl ?: 'search_default');
             $objTemplate->url = $arrResult[$i]['url'];
             $objTemplate->link = $arrResult[$i]['title'];
             $objTemplate->href = $arrResult[$i]['url'];
             $objTemplate->title = specialchars($arrResult[$i]['title']);
             $objTemplate->class = ($i == $from - 1 ? 'first ' : '') . ($i == $to - 1 || $i == $count - 1 ? 'last ' : '') . ($i % 2 == 0 ? 'even' : 'odd');
             $objTemplate->relevance = sprintf($GLOBALS['TL_LANG']['MSC']['relevance'], number_format($arrResult[$i]['relevance'] / $arrResult[0]['relevance'] * 100, 2) . '%');
             $objTemplate->filesize = $arrResult[$i]['filesize'];
             $objTemplate->matches = $arrResult[$i]['matches'];
             $arrContext = array();
             $arrMatches = trimsplit(',', $arrResult[$i]['matches']);
             // Get the context
             foreach ($arrMatches as $strWord) {
                 $arrChunks = array();
                 preg_match_all('/(^|\\b.{0,' . $this->contextLength . '}\\PL)' . str_replace('+', '\\+', $strWord) . '(\\PL.{0,' . $this->contextLength . '}\\b|$)/ui', $arrResult[$i]['text'], $arrChunks);
                 foreach ($arrChunks[0] as $strContext) {
                     $arrContext[] = ' ' . $strContext . ' ';
                 }
             }
             // Shorten the context and highlight all keywords
             if (!empty($arrContext)) {
                 $objTemplate->context = trim(\StringUtil::substrHtml(implode('…', $arrContext), $this->totalLength));
                 $objTemplate->context = preg_replace('/(\\PL)(' . implode('|', $arrMatches) . ')(\\PL)/ui', '$1<span class="highlight">$2</span>$3', $objTemplate->context);
                 $objTemplate->hasContext = true;
             }
             $this->Template->results .= $objTemplate->parse();
         }
         $this->Template->header = vsprintf($GLOBALS['TL_LANG']['MSC']['sResults'], array($from, $to, $count, $strKeywords));
         $this->Template->duration = substr($query_endtime - $query_starttime, 0, 6) . ' ' . $GLOBALS['TL_LANG']['MSC']['seconds'];
     }
 }
Example #13
0
 /**
  * Generate an XML files and save them to the root directory
  *
  * @param array
  */
 protected function generateFiles($arrFeed)
 {
     $arrArchives = deserialize($arrFeed['archives']);
     if (!is_array($arrArchives) || empty($arrArchives)) {
         return;
     }
     $strType = 'generateItunes';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new iTunesFeed($strFile);
     $objFeed->link = $strLink;
     $objFeed->podcastUrl = $strLink . 'share/' . $strFile . '.xml';
     $objFeed->title = $arrFeed['title'];
     $objFeed->subtitle = $arrFeed['subtitle'];
     $objFeed->description = $this->cleanHtml($arrFeed['description']);
     $objFeed->explicit = $arrFeed['explicit'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->author = $arrFeed['author'];
     $objFeed->owner = $arrFeed['owner'];
     $objFeed->email = $arrFeed['email'];
     $objFeed->category = $arrFeed['category'];
     $objFeed->published = $arrFeed['tstamp'];
     //Add Feed Image
     $objFile = \FilesModel::findByUuid($arrFeed['image']);
     if ($objFile !== null) {
         $objFeed->imageUrl = \Environment::get('base') . $objFile->path;
     }
     // Get the items
     if ($arrFeed['maxItems'] > 0) {
         $objPodcasts = \NewsPodcastsModel::findPublishedByPids($arrArchives, null, $arrFeed['maxItems']);
     } else {
         $objPodcasts = \NewsPodcastsModel::findPublishedByPids($arrArchives);
     }
     // Parse the items
     if ($objPodcasts !== null) {
         $arrUrls = array();
         while ($objPodcasts->next()) {
             $jumpTo = $objPodcasts->getRelated('pid')->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $this->generateFrontendUrl($objParent->row(), $GLOBALS['TL_CONFIG']['useAutoItem'] && !$GLOBALS['TL_CONFIG']['disableAlias'] ? '/%s' : '/items/%s', $objParent->language);
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objPodcasts->source == 'default') {
                 continue;
             }
             $strUrl = $arrUrls[$jumpTo];
             $objItem = new \FeedItem();
             $objItem->headline = $this->cleanHtml($objPodcasts->headline);
             $objItem->subheadline = $this->cleanHtml($objPodcasts->subheadline !== null ? $objPodcasts->subheadline : $objPodcasts->description);
             $objItem->link = $strLink . sprintf($strUrl, $objPodcasts->alias != '' && !$GLOBALS['TL_CONFIG']['disableAlias'] ? $objPodcasts->alias : $objPodcasts->id);
             $objItem->published = $objPodcasts->date;
             $objAuthor = $objPodcasts->getRelated('author');
             $objItem->author = $objAuthor->name;
             $objItem->description = $this->cleanHtml($objPodcasts->teaser);
             $objItem->explicit = $objPodcasts->explicit;
             // Add the article image as enclosure
             $objItem->addEnclosure($objFeed->imageUrl);
             // Add the Audio File
             if ($objPodcasts->podcast) {
                 $objFile = \FilesModel::findByUuid($objPodcasts->podcast);
                 if ($objFile !== null) {
                     // Add statistics service
                     if (!empty($arrFeed['addStatistics'])) {
                         // If no trailing slash given, add one
                         $statisticsPrefix = rtrim($arrFeed['statisticsPrefix'], '/') . '/';
                         $podcastPath = $statisticsPrefix . \Environment::get('host') . '/' . preg_replace('(^https?://)', '', $objFile->path);
                     } else {
                         $podcastPath = \Environment::get('base') . \System::urlEncode($objFile->path);
                     }
                     $objItem->podcastUrl = $podcastPath;
                     // Prepare the duration / prefer linux tool mp3info
                     $mp3file = new GetMp3Duration(TL_ROOT . '/' . $objFile->path);
                     if ($this->checkMp3InfoInstalled()) {
                         $shell_command = 'mp3info -p "%S" ' . escapeshellarg(TL_ROOT . '/' . $objFile->path);
                         $duration = shell_exec($shell_command);
                     } else {
                         $duration = $mp3file->getDuration();
                     }
                     $objPodcastFile = new \File($objFile->path, true);
                     $objItem->length = $objPodcastFile->size;
                     $objItem->type = $objPodcastFile->mime;
                     $objItem->duration = $mp3file->formatTime($duration);
                 }
             }
             $objFeed->addItem($objItem);
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
 /**
  * Generate the XML files and save them to the root directory
  * @param array
  */
 protected function generateFiles($arrFeed)
 {
     $arrConfigs = deserialize($arrFeed['configs']);
     if (!is_array($arrConfigs) || count($arrConfigs) < 1) {
         return;
     }
     $strType = $arrFeed['format'] == 'atom' ? 'generateAtom' : 'generateRss';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new \Feed($strFile);
     $objFeed->link = $strLink;
     $objFeed->title = $arrFeed['title'];
     $objFeed->description = $arrFeed['description'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->published = $arrFeed['tstamp'];
     $objJumpTo = \PageModel::findByPk($arrFeed['jumpTo']);
     // find the source attributes
     $objDescriptionAttribute = \PCT\CustomElements\Core\AttributeFactory::fetchById($arrFeed['descriptionField']);
     $objPublishedAttribute = \PCT\CustomElements\Core\AttributeFactory::fetchById($arrFeed['publishedField']);
     $objTitleAttribute = \PCT\CustomElements\Core\AttributeFactory::fetchById($arrFeed['titleField']);
     $objAuthorAttribute = \PCT\CustomElements\Core\AttributeFactory::fetchById($arrFeed['authorField']);
     $objImageAttribute = \PCT\CustomElements\Core\AttributeFactory::fetchById($arrFeed['imageField']);
     $arrFields = array('id', 'pid', 'tstamp', 'description' => $objDescriptionAttribute->alias, 'title' => $objTitleAttribute->alias, 'published' => $objPublishedAttribute->alias, 'author' => $objAuthorAttribute->alias, 'singleSRC' => $objImageAttribute->alias);
     foreach ($arrConfigs as $config_id) {
         $objCC = CustomCatalogFactory::findById($config_id);
         if ($objCC === null) {
             continue;
         }
         // set visibles to source attribute only
         $objCC->setVisibles(array_filter(array_values($arrFields)));
         if ($arrFeed['maxItems'] > 0) {
             $objCC->setLimit($arrFeed['maxItems']);
         }
         // fetch the entries
         $objEntries = $objCC->prepare();
         if ($objEntries->numRows < 1) {
             continue;
         }
         while ($objEntries->next()) {
             $objItem = new \FeedItem();
             $objItem->title = $objEntries->{$arrFields['title']};
             $objItem->link = $strLink . $objCC->generateDetailsUrl($objEntries, $objJumpTo);
             $objItem->published = $objEntries->{$arrFields['published']} ?: $objEntries->tstamp;
             $objItem->author = $objEntries->{$arrFields['author']} ?: '';
             $strDescription = $this->replaceInsertTags($objEntries->{$arrFields['description']}, false);
             $objItem->description = $this->convertRelativeUrls($strDescription, $strLink);
             if ($objEntries->{$arrFields['singleSRC']} && $objImageAttribute->published) {
                 $objFile = \FilesModel::findByUuid($objEntries->{$arrFields['singleSRC']});
                 if ($objFile !== null) {
                     $objItem->addEnclosure($objFile->path);
                 }
             }
             // add feed item
             $objFeed->addItem($objItem);
         }
     }
     // create file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
Example #15
0
 /**
  * Generate the combined file and return its path
  *
  * @param string $strUrl An optional URL to prepend
  *
  * @return string The path to the combined file
  */
 public function getCombinedFile($strUrl = null)
 {
     if ($strUrl === null) {
         $strUrl = TL_ASSETS_URL;
     }
     $strTarget = substr($this->strMode, 1);
     $strKey = substr(md5($this->strKey), 0, 12);
     // Do not combine the files in debug mode (see #6450)
     if (\Config::get('debugMode')) {
         $return = array();
         foreach ($this->arrFiles as $arrFile) {
             $content = file_get_contents(TL_ROOT . '/' . $arrFile['name']);
             // Compile SCSS/LESS files into temporary files
             if ($arrFile['extension'] == self::SCSS || $arrFile['extension'] == self::LESS) {
                 $strPath = 'assets/' . $strTarget . '/' . str_replace('/', '_', $arrFile['name']) . $this->strMode;
                 $objFile = new \File($strPath, true);
                 $objFile->write($this->handleScssLess($content, $arrFile));
                 $objFile->close();
                 $return[] = $strPath;
             } else {
                 $name = $arrFile['name'];
                 // Add the media query (see #7070)
                 if ($arrFile['media'] != '' && $arrFile['media'] != 'all' && strpos($content, '@media') === false) {
                     $name .= '" media="' . $arrFile['media'];
                 }
                 $return[] = $name;
             }
         }
         if ($this->strMode == self::JS) {
             return implode('"></script><script src="', $return);
         } else {
             return implode('"><link rel="stylesheet" href="', $return);
         }
     }
     // Load the existing file
     if (file_exists(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode)) {
         return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
     }
     // Create the file
     $objFile = new \File('assets/' . $strTarget . '/' . $strKey . $this->strMode, true);
     $objFile->truncate();
     foreach ($this->arrFiles as $arrFile) {
         $content = file_get_contents(TL_ROOT . '/' . $arrFile['name']);
         // HOOK: modify the file content
         if (isset($GLOBALS['TL_HOOKS']['getCombinedFile']) && is_array($GLOBALS['TL_HOOKS']['getCombinedFile'])) {
             foreach ($GLOBALS['TL_HOOKS']['getCombinedFile'] as $callback) {
                 $this->import($callback[0]);
                 $content = $this->{$callback}[0]->{$callback}[1]($content, $strKey, $this->strMode, $arrFile);
             }
         }
         if ($arrFile['extension'] == self::CSS) {
             $content = $this->handleCss($content, $arrFile);
         } elseif ($arrFile['extension'] == self::SCSS || $arrFile['extension'] == self::LESS) {
             $content = $this->handleScssLess($content, $arrFile);
         }
         $objFile->append($content);
     }
     unset($content);
     $objFile->close();
     // Create a gzipped version
     if (\Config::get('gzipScripts') && function_exists('gzencode')) {
         \File::putContent('assets/' . $strTarget . '/' . $strKey . $this->strMode . '.gz', gzencode(file_get_contents(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode), 9));
     }
     return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
 }
Example #16
0
 /**
  * Update the cron.txt file
  *
  * @param integer $time
  */
 protected function updateCronTxt($time)
 {
     \File::putContent('system/cron/cron.txt', $time);
 }
Example #17
0
 /**
  * Version 3.0.0 update
  */
 public function run300Update()
 {
     // Create the files table
     $this->Database->query("CREATE TABLE `tl_files` (\n\t\t\t  `id` int(10) unsigned NOT NULL auto_increment,\n\t\t\t  `pid` binary(16) NULL,\n\t\t\t  `tstamp` int(10) unsigned NOT NULL default '0',\n\t\t\t  `uuid` binary(16) NULL,\n\t\t\t  `type` varchar(16) NOT NULL default '',\n\t\t\t  `path` varchar(1022) NOT NULL default '',\n\t\t\t  `extension` varchar(16) NOT NULL default '',\n\t\t\t  `hash` varchar(32) NOT NULL default '',\n\t\t\t  `found` char(1) NOT NULL default '1',\n\t\t\t  `name` varchar(255) NOT NULL default '',\n\t\t\t  `meta` blob NULL,\n\t\t\t  PRIMARY KEY  (`id`),\n\t\t\t  KEY `pid` (`pid`),\n\t\t\t  UNIQUE KEY `uuid` (`uuid`),\n\t\t\t  KEY `extension` (`extension`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
     // Add the "numberOfItems" field
     $this->Database->query("ALTER TABLE `tl_module` ADD `numberOfItems` smallint(5) unsigned NOT NULL default '0'");
     $this->Database->query("UPDATE `tl_module` SET `numberOfItems`=`rss_numberOfItems` WHERE `rss_numberOfItems`>0");
     $this->Database->query("UPDATE `tl_module` SET `numberOfItems`=`news_numberOfItems` WHERE `news_numberOfItems`>0");
     // Add the "addMooTools" field
     $this->Database->query("ALTER TABLE `tl_layout` ADD `addMooTools` char(1) NOT NULL default ''");
     $this->Database->query("UPDATE `tl_layout` SET `addMooTools`=1 WHERE `mootools`!=''");
     // Add the "notified" field
     $this->Database->query("ALTER TABLE `tl_comments` ADD `notified` char(1) NOT NULL default ''");
     $this->Database->query("UPDATE `tl_comments` SET `notified`=1");
     // Add the "rows" field
     $this->Database->query("ALTER TABLE `tl_layout` ADD `rows` varchar(8) NOT NULL default ''");
     $this->Database->query("UPDATE `tl_layout` SET `rows`='1rw' WHERE `header`='' AND `footer`=''");
     $this->Database->query("UPDATE `tl_layout` SET `rows`='2rwh' WHERE `header`!='' AND `footer`=''");
     $this->Database->query("UPDATE `tl_layout` SET `rows`='2rwf' WHERE `header`='' AND `footer`!=''");
     $this->Database->query("UPDATE `tl_layout` SET `rows`='3rw' WHERE `header`!='' AND `footer`!=''");
     // Update the "mooType" field
     $this->Database->query("UPDATE `tl_content` SET `mooType`='mooStart' WHERE `mooType`='start'");
     $this->Database->query("UPDATE `tl_content` SET `mooType`='mooStop' WHERE `mooType`='stop'");
     $this->Database->query("UPDATE `tl_content` SET `mooType`='mooSingle' WHERE `mooType`='single'");
     // Add the "framework" field
     $this->Database->query("ALTER TABLE `tl_layout` ADD `framework` varchar(255) NOT NULL default ''");
     $this->Database->query("UPDATE `tl_layout` SET `framework`='a:2:{i:0;s:10:\"layout.css\";i:1;s:11:\"tinymce.css\";}'");
     $this->Database->query("UPDATE `tl_layout` SET `framework`='a:1:{i:0;s:10:\"layout.css\";}' WHERE skipTinymce=1");
     // Make sure the "skipFramework" field exists (see #4624)
     if ($this->Database->fieldExists('skipFramework', 'tl_layout')) {
         $this->Database->query("UPDATE `tl_layout` SET `framework`='' WHERE skipFramework=1");
     }
     // Add the "ptable" field
     $this->Database->query("ALTER TABLE `tl_content` ADD ptable varchar(64) NOT NULL default ''");
     // Create a content element for each news article
     $objNews = $this->Database->execute("SELECT * FROM tl_news WHERE text!='' AND source='default'");
     while ($objNews->next()) {
         $this->createContentElement($objNews, 'tl_news', 'text');
     }
     // Create a content element for each event
     $objEvents = $this->Database->execute("SELECT * FROM tl_calendar_events WHERE details!='' AND source='default'");
     while ($objEvents->next()) {
         $this->createContentElement($objEvents, 'tl_calendar_events', 'details');
     }
     // Add an .htaccess file to the modules' html folders so they can be accessed via HTTP
     foreach (scan(TL_ROOT . '/system/modules') as $strFolder) {
         if (is_dir(TL_ROOT . '/system/modules/' . $strFolder) && is_dir(TL_ROOT . '/system/modules/' . $strFolder . '/html')) {
             if (!file_exists(TL_ROOT . '/system/modules/' . $strFolder . '/html/.htaccess')) {
                 \File::putContent('system/modules/' . $strFolder . '/html/.htaccess', "<IfModule !mod_authz_core.c>\n  Order allow,deny\n  Allow from all\n</IfModule>\n<IfModule mod_authz_core.c>\n  Require all granted\n</IfModule>");
             }
         }
     }
     // Convert the gradient angle syntax (see #4569)
     if ($this->Database->fieldExists('gradientAngle', 'tl_style')) {
         $objStyle = $this->Database->execute("SELECT id, gradientAngle FROM tl_style WHERE gradientAngle!=''");
         while ($objStyle->next()) {
             $angle = '';
             if (strpos($objStyle->gradientAngle, 'deg') !== false) {
                 $angle = abs(450 - intval($objStyle->gradientAngle)) % 360 . 'deg';
             } else {
                 switch ($objStyle->gradientAngle) {
                     case 'top':
                         $angle = 'to bottom';
                         break;
                     case 'right':
                         $angle = 'to left';
                         break;
                     case 'bottom':
                         $angle = 'to top';
                         break;
                     case 'left':
                         $angle = 'to right';
                         break;
                     case 'top left':
                         $angle = 'to bottom right';
                         break;
                     case 'top right':
                         $angle = 'to bottom left';
                         break;
                     case 'bottom left':
                         $angle = 'to top right';
                         break;
                     case 'bottom right':
                         $angle = 'to top left';
                         break;
                 }
             }
             $this->Database->prepare("UPDATE tl_style SET gradientAngle=? WHERE id=?")->execute($angle, $objStyle->id);
         }
     }
     // Make unlimited recurrences end on 2038-01-01 00:00:00 (see #4862)
     $this->Database->query("UPDATE `tl_calendar_events` SET `repeatEnd`=2145913200 WHERE `recurring`=1 AND `recurrences`=0");
 }
Example #18
0
 /**
  * Run the Live Update
  *
  * @param \BackendTemplate|object $objTemplate
  */
 protected function runLiveUpdate(\BackendTemplate $objTemplate)
 {
     $archive = 'system/tmp/' . \Input::get('token');
     // Download the archive
     if (!file_exists(TL_ROOT . '/' . $archive)) {
         // HOOK: proxy module
         if (Config::get('useProxy')) {
             $objRequest = new \ProxyRequest();
         } else {
             $objRequest = new \Request();
         }
         $objRequest->send(\Config::get('liveUpdateBase') . 'request.php?token=' . \Input::get('token'));
         if ($objRequest->hasError()) {
             $objTemplate->updateClass = 'tl_error';
             $objTemplate->updateMessage = $objRequest->response;
             return;
         }
         \File::putContent($archive, $objRequest->response);
     }
     $objArchive = new \ZipReader($archive);
     // Extract
     while ($objArchive->next()) {
         if ($objArchive->file_name != 'TOC.txt') {
             try {
                 \File::putContent($objArchive->file_name, $objArchive->unzip());
             } catch (\Exception $e) {
                 /** @var \BackendTemplate|object $objTemplate */
                 $objTemplate->updateClass = 'tl_error';
                 $objTemplate->updateMessage = 'Error updating ' . $objArchive->file_name . ': ' . $e->getMessage();
                 return;
             }
         }
     }
     // Delete the archive
     $this->import('Files');
     $this->Files->delete($archive);
     // Run once
     $this->handleRunOnce();
 }
Example #19
0
 /**
  * Generate an XML file and save it to the root directory
  *
  * @param array $arrFeed
  */
 protected function generateFiles($arrFeed)
 {
     $arrCalendars = deserialize($arrFeed['calendars']);
     if (!is_array($arrCalendars) || empty($arrCalendars)) {
         return;
     }
     $strType = $arrFeed['format'] == 'atom' ? 'generateAtom' : 'generateRss';
     $strLink = $arrFeed['feedBase'] ?: \Environment::get('base');
     $strFile = $arrFeed['feedName'];
     $objFeed = new \Feed($strFile);
     $objFeed->link = $strLink;
     $objFeed->title = $arrFeed['title'];
     $objFeed->description = $arrFeed['description'];
     $objFeed->language = $arrFeed['language'];
     $objFeed->published = $arrFeed['tstamp'];
     $arrUrls = array();
     $this->arrEvents = array();
     $time = time();
     // Get the upcoming events
     $objArticle = \CalendarEventsModel::findUpcomingByPids($arrCalendars, $arrFeed['maxItems']);
     // Parse the items
     if ($objArticle !== null) {
         while ($objArticle->next()) {
             $jumpTo = $objArticle->getRelated('pid')->jumpTo;
             // No jumpTo page set (see #4784)
             if (!$jumpTo) {
                 continue;
             }
             // Get the jumpTo URL
             if (!isset($arrUrls[$jumpTo])) {
                 $objParent = \PageModel::findWithDetails($jumpTo);
                 // A jumpTo page is set but does no longer exist (see #5781)
                 if ($objParent === null) {
                     $arrUrls[$jumpTo] = false;
                 } else {
                     $arrUrls[$jumpTo] = $this->generateFrontendUrl($objParent->row(), \Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/%s' : '/events/%s', $objParent->language);
                 }
             }
             // Skip the event if it requires a jumpTo URL but there is none
             if ($arrUrls[$jumpTo] === false && $objArticle->source == 'default') {
                 continue;
             }
             $strUrl = $arrUrls[$jumpTo];
             $this->addEvent($objArticle, $objArticle->startTime, $objArticle->endTime, $strUrl, $strLink);
             // Recurring events
             if ($objArticle->recurring) {
                 $arrRepeat = deserialize($objArticle->repeatEach);
                 if ($arrRepeat['value'] < 1) {
                     continue;
                 }
                 $count = 0;
                 $intStartTime = $objArticle->startTime;
                 $intEndTime = $objArticle->endTime;
                 $strtotime = '+ ' . $arrRepeat['value'] . ' ' . $arrRepeat['unit'];
                 // Do not include more than 20 recurrences
                 while ($count++ < 20) {
                     if ($objArticle->recurrences > 0 && $count >= $objArticle->recurrences) {
                         break;
                     }
                     $intStartTime = strtotime($strtotime, $intStartTime);
                     $intEndTime = strtotime($strtotime, $intEndTime);
                     if ($intStartTime >= $time) {
                         $this->addEvent($objArticle, $intStartTime, $intEndTime, $strUrl, $strLink);
                     }
                 }
             }
         }
     }
     $count = 0;
     ksort($this->arrEvents);
     // Add the feed items
     foreach ($this->arrEvents as $days) {
         foreach ($days as $events) {
             foreach ($events as $event) {
                 if ($arrFeed['maxItems'] > 0 && $count++ >= $arrFeed['maxItems']) {
                     break 3;
                 }
                 $objItem = new \FeedItem();
                 $objItem->title = $event['title'];
                 $objItem->link = $event['link'];
                 $objItem->published = $event['tstamp'];
                 $objItem->begin = $event['begin'];
                 $objItem->end = $event['end'];
                 $objItem->author = $event['authorName'];
                 // Prepare the description
                 if ($arrFeed['source'] == 'source_text') {
                     $strDescription = '';
                     $objElement = \ContentModel::findPublishedByPidAndTable($event['id'], 'tl_calendar_events');
                     if ($objElement !== null) {
                         // Overwrite the request (see #7756)
                         $strRequest = \Environment::get('request');
                         \Environment::set('request', $objItem->link);
                         while ($objElement->next()) {
                             $strDescription .= $this->getContentElement($objElement->current());
                         }
                         \Environment::set('request', $strRequest);
                     }
                 } else {
                     $strDescription = $event['teaser'];
                 }
                 $strDescription = $this->replaceInsertTags($strDescription, false);
                 $objItem->description = $this->convertRelativeUrls($strDescription, $strLink);
                 if (is_array($event['enclosure'])) {
                     foreach ($event['enclosure'] as $enclosure) {
                         $objItem->addEnclosure($enclosure);
                     }
                 }
                 $objFeed->addItem($objItem);
             }
         }
     }
     // Create the file
     \File::putContent('share/' . $strFile . '.xml', $this->replaceInsertTags($objFeed->{$strType}(), false));
 }
Example #20
0
 /**
  * Store the relative path
  */
 protected function storeRelativePath()
 {
     if (TL_PATH === null) {
         return;
     }
     if (file_exists(TL_ROOT . '/system/config/pathconfig.php')) {
         $strPath = (include TL_ROOT . '/system/config/pathconfig.php');
         if (TL_PATH == $strPath) {
             return;
         }
     }
     try {
         \File::putContent('system/config/pathconfig.php', '<?php' . "\n\n// Relative path to the installation\nreturn " . var_export(TL_PATH, true) . ";\n");
     } catch (\Exception $e) {
         log_message($e->getMessage());
     }
 }
 /**
  * Resets the login count.
  */
 public function resetLoginCount()
 {
     \File::putContent('system/tmp/login-count.txt', 0);
 }