Exemplo n.º 1
0
function LoadZipOrDir($dbi, $zip_or_dir)
{
    global $LANG, $genericpages;
    $type = filetype($zip_or_dir);
    if ($type == 'file') {
        $zip = new ZipReader($zip_or_dir);
        while (list($fn, $data, $attrib) = $zip->readFile()) {
            LoadFile($dbi, $fn, $data, $attrib['mtime']);
        }
    } else {
        if ($type == 'dir') {
            $handle = opendir($dir = $zip_or_dir);
            // load default pages
            while ($fn = readdir($handle)) {
                if ($fn[0] == '.' || filetype("{$dir}/{$fn}") != 'file') {
                    continue;
                }
                $stat = stat("{$dir}/{$fn}");
                $mtime = $stat[9];
                LoadFile($dbi, $fn, implode("", file("{$dir}/{$fn}")), $mtime);
            }
            closedir($handle);
            if ($LANG != "C") {
                // if language is not default, then insert
                // generic pages from the English ./pgsrc
                reset($genericpages);
                $dir = DEFAULT_WIKI_PGSRC;
                while (list(, $fn) = each($genericpages)) {
                    LoadFile($dbi, $fn, implode("", file("{$dir}/{$fn}")), $mtime);
                }
            }
        }
    }
}
Exemplo n.º 2
0
 function unpack($packed)
 {
     if (!$packed) {
         return false;
     }
     // ZLIB format has a five bit checksum in it's header.
     // Lets check for sanity.
     if ((ord($packed[0]) * 256 + ord($packed[1])) % 31 == 0 and substr($packed, 0, 2) == "‹" or substr($packed, 0, 2) == "xÚ") {
         if (function_exists('gzuncompress')) {
             // Looks like ZLIB.
             $data = gzuncompress($packed);
             return unserialize($data);
         } else {
             // user our php lib. TESTME
             include_once "ziplib.php";
             $zip = new ZipReader($packed);
             list(, $data, $attrib) = $zip->readFile();
             return unserialize($data);
         }
     }
     if (substr($packed, 0, 2) == "O:") {
         // Looks like a serialized object
         return unserialize($packed);
     }
     if (preg_match("/^\\w+\$/", $packed)) {
         return $packed;
     }
     // happened with _BackendInfo problem also.
     trigger_error("Can't unpack bad cached markup. Probably php_zlib extension not loaded.", E_USER_WARNING);
     return false;
 }
Exemplo n.º 3
0
 /**
  * Implement the commands to run by this batch program
  */
 public function run()
 {
     $this->import("Files");
     $zipname = 'system/tmp/tmp.zip';
     $csvFile = 'system/tmp/geoData.csv';
     //get the new zip-file
     copy('http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip', TL_ROOT . '/' . $zipname);
     // open zip archive
     $zip = new ZipReader($zipname);
     // process files in TL_ROOT and TL_FILES
     while ($zip->next()) {
         if ($zip->file_name == 'GeoIPCountryWhois.csv') {
             // save file
             $f = new File($csvFile);
             if (!$f->write($zip->unzip())) {
                 throw new Exception(sprintf($text['fileerrwrite'], $csvFile));
             }
             $f->close();
             //prepare SQL from CSV
             $f = new File($csvFile);
             $set = array();
             $query = "INSERT INTO `tl_geodata` (ip_start, ip_end, ipnum_start, ipnum_end, country_short, country) VALUES ";
             while (($arrRow = @fgetcsv($f->handle, 1024, ',')) !== false) {
                 $query .= '("' . $arrRow[0] . '","' . $arrRow[1] . '","' . $arrRow[2] . '","' . $arrRow[3] . '","' . $arrRow[4] . '","' . $arrRow[5] . '"),';
             }
             //cut off last ","
             $query = substr($query, 0, -1);
             //Empty table
             $this->Database->prepare('TRUNCATE TABLE `tl_geodata`')->execute();
             //insert new Data
             $test = $this->Database->prepare($query)->set($set)->execute();
             //delete file
             $f->close();
             $f->delete();
         }
     }
     $this->Files->delete($zipname);
     $this->log('Geodata updated successfully.', 'UpdateGeoData run()', TL_GENERAL);
 }
Exemplo n.º 4
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();
 }
Exemplo n.º 5
0
function LoadZip(&$request, $zipfile, $files = false, $exclude = false)
{
    $zip = new ZipReader($zipfile);
    $timeout = !$request->getArg('start_debug') ? 20 : 120;
    while (list($fn, $data, $attrib) = $zip->readFile()) {
        // FIXME: basename("filewithnoslashes") seems to return
        // garbage sometimes.
        $fn = basename("/dummy/" . $fn);
        if ($files && !in_array($fn, $files) || $exclude && in_array($fn, $exclude)) {
            PrintXML(HTML::dt(WikiLink($fn)), HTML::dd(_("Skipping")));
            flush();
            continue;
        }
        longer_timeout($timeout);
        // longer timeout per page
        LoadFile($request, $fn, $data, $attrib['mtime']);
    }
}
Exemplo n.º 6
0
	/**
	 * Run the live update
	 * @param BackendTemplate
	 */
	protected function runLiveUpdate(BackendTemplate $objTemplate)
	{
		$archive = 'system/tmp/' . $this->Input->get('token');

		// Download the archive
		if (!file_exists(TL_ROOT . '/' . $archive))
		{
			$objRequest = new Request();
			$objRequest->send($GLOBALS['TL_CONFIG']['liveUpdateBase'] . 'request.php?token=' . $this->Input->get('token'));

			if ($objRequest->hasError())
			{
				$objTemplate->updateClass = 'tl_error';
				$objTemplate->updateMessage = $objRequest->response;
				return;
			}

			$objFile = new File($archive);
			$objFile->write($objRequest->response);
			$objFile->close();
		}

		// Create a minimalistic HTML5 document
		echo '<!DOCTYPE html>'
			.'<head>'
			  .'<meta charset="utf-8">'
			  .'<title>Contao Live Update</title>'
			  .'<style>'
			    .'body { background:#f5f5f5 url("../system/themes/default/images/hbg.jpg") left top repeat-x; font-family:Verdana,sans-serif; font-size:11px; color:#444; padding:1em; }'
			    .'div { max-width:680px; margin:0 auto; border:1px solid #bbb; background:#fff; }'
			    .'h1 { font-size:12px; color:#fff; margin:1px; padding:2px 6px 4px; background:#b3b6b3 url("../system/themes/default/images/headline.gif") left top repeat-x; }'
			    .'h2 { font-size:14px; color:#8ab858; margin:18px 15px; padding:6px 42px 8px; background:url("../system/themes/default/images/current.gif") left center no-repeat; }'
			    .'ol { border:1px solid #ccc; max-height:430px; margin:0 15px 18px; overflow:auto; padding:3px 18px 3px 48px; background:#fcfcfc; }'
			    .'li { margin-bottom:3px; }'
			    .'p { margin:0 12px; padding:0; overflow:hidden; }'
			    .'.button { font-family:"Trebuchet MS",Verdana,sans-serif; font-size:12px; display:block; float:right; margin:0 3px 18px; border-radius:3px; background:#808080; text-decoration:none; color:#fff; padding:4px 18px; box-shadow:0 1px 3px #bbb; text-shadow:1px 1px 0 #666; }'
			    .'.button:hover,.button:focus { box-shadow:0 0 6px #8ab858; }'
			    .'.button:active { background:#8ab858; }'
			  .'</style>'
			.'<body>'
			.'<div>';

		$objArchive = new ZipReader($archive);

		// Table of contents
		if ($this->Input->get('toc'))
		{
			$arrFiles = $objArchive->getFileList();
			array_shift($arrFiles);

			echo '<hgroup>'
				  .'<h1>Contao Live Update</h1>'
				  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['toc'] . '</h2>'
				.'</hgroup>'
				.'<ol>'
				  .'<li>' . implode('</li><li>', $arrFiles) . '</li>'
				.'</ol>'
				.'<p>'
				  .'<a href="' . ampersand(str_replace('toc=1', 'toc=', $this->Environment->base . $this->Environment->request)) . '" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
				  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance" class="button">' . $GLOBALS['TL_LANG']['MSC']['cancelBT'] . '</a>'
				  .'</p>'
				.'</div>';

			exit;
		}

		// Backup
		if ($this->Input->get('bup'))
		{
			echo '<hgroup>'
				  .'<h1>Contao Live Update</h1>'
				  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['backup'] . '</h2>'
				.'</hgroup>'
				.'<ol>';

			$arrFiles = $objArchive->getFileList();
			$objBackup = new ZipWriter('LU' . date('YmdHi') . '.zip');

			foreach ($arrFiles as $strFile)
			{
				if ($strFile == 'TOC.txt' || $strFile == 'system/runonce.php')
				{
					continue;
				}

				try
				{
					$objBackup->addFile($strFile);
					echo '<li>Backed up ' . $strFile . '</li>';
				}
				catch (Exception $e)
				{
					echo '<li>' . $e->getMessage() . ' (skipped)</li>';
				}
			}

			$objBackup->close();

			echo '</ol>'
				.'<p>'
				  .'<a href="' . ampersand(str_replace('bup=1', 'bup=', $this->Environment->base . $this->Environment->request)) . '" id="continue" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
				  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance" id="back" class="button">' . $GLOBALS['TL_LANG']['MSC']['cancelBT'] . '</a>'
				  .'</p>'
				.'</div>';

			exit;
 		}

 		echo '<hgroup>'
			  .'<h1>Contao Live Update</h1>'
			  .'<h2>' . $GLOBALS['TL_LANG']['tl_maintenance']['update'] . '</h2>'
			.'</hgroup>'
			.'<ol>';

		// Update
		while ($objArchive->next())
		{
			if ($objArchive->file_name == 'TOC.txt')
			{
				continue;
			}

			try
			{
				$objFile = new File($objArchive->file_name);
				$objFile->write($objArchive->unzip());
				$objFile->close();

				echo '<li>Updated ' . $objArchive->file_name . '</li>';
			}
			catch (Exception $e)
			{
				echo '<li><span style="color:#c55">Error updating ' . $objArchive->file_name . ': ' . $e->getMessage() . '</span></li>';
			}
		}

		// Delete the archive
		$this->import('Files');
		$this->Files->delete($archive);

		// Add a log entry
		$this->log('Live update from version ' . VERSION . '.' . BUILD . ' to version ' . $GLOBALS['TL_CONFIG']['latestVersion'] . ' completed', 'LiveUpdate run()', TL_GENERAL);

		echo '</ol>'
			.'<p>'
			  .'<a href="' . $this->Environment->base . 'contao/main.php?do=maintenance&amp;act=runonce" id="continue" class="button">' . $GLOBALS['TL_LANG']['MSC']['continue'] . '</a>'
			.'</p>'
			.'</div>';

		exit;
	}
Exemplo n.º 7
0
 /**
  * Install the files of an extension.
  * @param string $aName Name of the extension to install/update.
  * @param int $aVersion The extension version to install/update to.
  * @param string $aKey License key for commercial or private extensions.
  */
 private function installExtension($aName, $aVersion, $aKey)
 {
     $text =& $GLOBALS['TL_LANG']['tl_repository'];
     $rep =& $this->Template->rep;
     $db =& $this->Database;
     $this->import('Files');
     $err = false;
     try {
         // get package info from repository
         $options = array('name' => $aName, 'version' => $aVersion, 'mode' => 'install');
         if ($aKey != '') {
             $options['key'] = $aKey;
         }
         $pkg = $this->getPackage($options);
         // create tmp name and copy package
         $zipname = 'system/tmp/' . $pkg->path;
         $this->Files->delete($zipname);
         // fetch package - using Request class
         // HOOK: proxy module
         if ($GLOBALS['TL_CONFIG']['useProxy']) {
             $req = new ProxyRequest();
         } else {
             $req = new Request();
         }
         $req->send($pkg->url);
         if ($req->hasError()) {
             throw new Exception($req->error);
         }
         $dstfile = new File($zipname);
         if (!$dstfile->write($req->response)) {
             throw new Exception(sprintf($text['fileerrwrite'], $zipname));
         }
         $dstfile->close();
         $req = null;
         // release mem
         try {
             // initialize counters
             $sum_inst = $sum_updt = 0;
             // open zip archive
             $zip = new ZipReader($zipname);
             try {
                 // get pid of installation record
                 $q = $db->prepare("select `id` from `tl_repository_installs` where `extension`=?")->execute($aName);
                 if (!$q->next()) {
                     throw new Exception($text['extinstrecntf']);
                 }
                 $instId = $q->id;
                 // process files in TL_ROOT and TL_FILES
                 while ($zip->next()) {
                     $filerel = '';
                     if (mb_substr($zip->file_name, 0, 8) == 'TL_ROOT/') {
                         $filerel = mb_substr($zip->file_name, 8);
                     } else {
                         if (mb_substr($zip->file_name, 0, 9) == 'TL_FILES/') {
                             $filerel = $this->tl_files . mb_substr($zip->file_name, 9);
                         }
                     }
                     // if
                     if ($filerel != '') {
                         $fileabs = $this->tl_root . $filerel;
                         if (file_exists($fileabs)) {
                             $sum_updt++;
                         } else {
                             $sum_inst++;
                         }
                         // save new directories by this file
                         $dir = dirname($filerel);
                         $enddirs = array('', '.', '/');
                         while (!in_array($dir, $enddirs) && !file_exists($this->tl_root . $dir)) {
                             $q = $db->prepare("update `tl_repository_instfiles` set `tstamp`=?" . " where `pid`=? and `filetype`='D' and `filename`=?")->executeUncached(array(time(), $instId, $dir));
                             if ($q->affectedRows == 0) {
                                 $db->prepare("insert into `tl_repository_instfiles` %s")->set(array('pid' => $instId, 'tstamp' => time(), 'filename' => $dir, 'filetype' => 'D'))->executeUncached();
                             }
                             $dir = dirname($dir);
                         }
                         // while
                         // save new or changed file
                         $f = new File($filerel);
                         if (!$f->write($zip->unzip())) {
                             throw new Exception(sprintf($text['fileerrwrite'], $filerel));
                         }
                         $f->close();
                         // add new file record
                         $db->prepare("insert into `tl_repository_instfiles` %s")->set(array('pid' => $instId, 'tstamp' => time(), 'filename' => $filerel, 'filetype' => 'F'))->executeUncached();
                     }
                     // if
                 }
                 // for
                 $zip = null;
                 // destruct = close
             } catch (Exception $exc) {
                 $zip = null;
                 throw $exc;
             }
             // catch
             // log counter and success message
             if ($sum_inst > 0) {
                 $rep->log .= '<div>' . sprintf($text['filesinstalled'], $sum_inst) . "</div>\n";
             }
             if ($sum_updt > 0) {
                 $rep->log .= '<div>' . sprintf($text['filesupdated'], $sum_updt) . "</div>\n";
             }
             $rep->log .= '<div class="color_green">' . $text['actionsuccess'] . "</div>\n";
             // cleanup
             $this->Files->delete($zipname);
         } catch (Exception $exc) {
             $this->Files->delete($zipname);
             throw $exc;
         }
         // catch
         $this->log('Extension "' . $aName . '" version "' . Repository::formatVersion($aVersion) . '" has been installed', 'RepositoryManager::installExtension()', TL_REPOSITORY);
     } catch (Exception $exc) {
         $rep->log .= "<div class=\"color_red\">\n" . str_replace("\n", "<br/>\n", $exc->getMessage()) . "<br/>\n" . $exc->getFile() . '[' . $exc->getLine() . ']' . "</div>\n";
         error_log(sprintf('Extension Manager: %s in %s on line %s', $exc->getMessage(), $exc->getFile(), $exc->getLine()));
         $err = true;
     }
     // catch
     return $err;
 }
Exemplo n.º 8
0
Arquivo: Theme.php Projeto: 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')));
 }
Exemplo n.º 9
0
	/**
	 * Extract the theme files and write the data to the database
	 * @param array
	 * @param array
	 */
	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 tl_files and the templates directory
				if (strncmp($objArchive->file_name, 'tl_files/', 9) !== 0 && strncmp($objArchive->file_name, 'templates/', 10) !== 0)
				{
					$this->addErrorMessage(sprintf($GLOBALS['TL_LANG']['ERR']['invalidFile'], $objArchive->file_name));
					continue;
				}

				// Extract the files
				try
				{
					$strFileName = $objArchive->file_name;

					// Override the files directory
					if ($GLOBALS['TL_CONFIG']['uploadPath'] != 'tl_files' && strncmp($objArchive->file_name, 'tl_files/', 9) === 0)
					{
						$strFileName = str_replace('tl_files/', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $objArchive->file_name);
					}

					$objFile = new File($strFileName);
					$objFile->write($objArchive->unzip());
					$objFile->close();
				}
				catch (Exception $e)
				{
					$this->addErrorMessage($e->getMessage());
				}
			}

			// Continue if there is no XML file
			if (!$xml instanceof DOMDocument)
			{
				$this->addErrorMessage(sprintf($GLOBALS['TL_LANG']['tl_theme']['missing_xml'], basename($strZipFile)));
				continue;
			}

			$arrMapper = array();
			$tables = $xml->getElementsByTagName('table');

			// Lock the tables
			$arrLocks = array
			(
				'tl_theme'       => 'WRITE',
				'tl_style_sheet' => 'WRITE',
				'tl_style'       => 'WRITE',
				'tl_module'      => 'WRITE',
				'tl_layout'      => 'WRITE'
			);

			$this->Database->lockTables($arrLocks);

			// Get the current auto_increment values
			$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');

			// 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 ($table != 'tl_theme' && $table != 'tl_style_sheet' && $table != 'tl_style' && $table != 'tl_module' && $table != 'tl_layout')
				{
					continue;
				}

				// 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');

						// Increment the ID
						if ($name == 'id')
						{
							$id = ${$table}++;
							$arrMapper[$table][$value] = $id;
							$value = $id;
						}

						// Increment the parent IDs
						elseif ($name == 'pid')
						{
							if ($table == 'tl_style')
							{
								$value = $arrMapper['tl_style_sheet'][$value];
							}
							else
							{
								$value = $arrMapper['tl_theme'][$value];
							}
						}

						// Adjust the style sheet IDs of the page layout
						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);
							}
						}

						// Adjust the module IDs of the page layout
						elseif ($table == 'tl_layout' && $name == 'modules')
						{
							$modules = deserialize($value);

							if (is_array($modules))
							{
								foreach (array_keys($modules) as $key)
								{
									if ($modules[$key]['mod'] > 0)
									{
										$modules[$key]['mod'] = $arrMapper['tl_module'][$modules[$key]['mod']];
									}
								}

								$value = serialize($modules);
							}
						}

						// Adjust the names
						elseif (($table == 'tl_theme' || $table == 'tl_style_sheet') && $name == 'name')
						{
							$objCount = $this->Database->prepare("SELECT COUNT(*) AS total FROM ". $table ." WHERE name=?")
													   ->execute($value);

							if ($objCount->total > 0)
							{
								$value = preg_replace('/( |\-)[0-9]+$/', '', $value);
								$value .= (($table == 'tl_style_sheet') ? '-' : ' ') . ${$table};
							}
						}

						// Handle fallback fields
						elseif ($name == 'fallback')
						{
							$value = '';
						}

						// Skip NULL values
						elseif ($value == 'NULL')
						{
							continue;
						}

						// Adjust the file paths in style sheets and modules
						elseif ($GLOBALS['TL_CONFIG']['uploadPath'] != 'tl_files' && strpos($value, 'tl_files') !== false)
						{
							$tmp = deserialize($value);

							if (is_array($tmp))
							{
								foreach ($tmp as $kk=>$vv)
								{
									$tmp[$kk] = str_replace('tl_files/', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $vv);
								}

								$value = serialize($tmp);
							}
							else
							{
								$value = str_replace('tl_files/', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $value);
							}
						}

						$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]);
						}
					}

					// Update the datatbase
					$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
			$this->addConfirmationMessage(sprintf($GLOBALS['TL_LANG']['tl_theme']['theme_imported'], basename($strZipFile)));
		}

		// Redirect
		setcookie('BE_PAGE_OFFSET', 0, 0, '/');
		$this->redirect(str_replace('&key=importTheme', '', $this->Environment->request));
	}
Exemplo n.º 10
0
 /**
  * Unzip the file by using the ZipReader class from contao
  * 
  * @param sring $strZipPath Path to the zip
  * @return array A list with current path and taget path.
  * @throws Exception 
  */
 protected function unzipByContao($strZipPath)
 {
     $arrMoveList = array();
     $objZipReader = new ZipReader($strZipPath);
     // Create tmp folder
     new Folder(self::TEMP_PATH . '/syncCtoAutoUpdate');
     foreach ($objZipReader->getFileList() as $value) {
         // Check if the file part of the folder "FILES"
         if (!preg_match("/^" . self::ZIP_FILE_PATH . "\\//i", $value)) {
             continue;
         }
         $movePath = preg_replace("/^" . self::ZIP_FILE_PATH . "\\//i", "", $value);
         $targetPath = self::TEMP_PATH . 'syncCtoAutoUpdate/' . $movePath;
         $arrMoveList[$targetPath] = $movePath;
         // Write file
         $objZipReader->getFile($value);
         $objFile = new File($targetPath);
         $objFile->write($objZipReader->unzip());
         $objFile->close();
         unset($objFile);
     }
     return $arrMoveList;
 }
Exemplo n.º 11
0
 /**
  * Run the live update
  * @param \BackendTemplate
  */
 protected function runLiveUpdate(\BackendTemplate $objTemplate)
 {
     $archive = 'system/tmp/' . \Input::get('token');
     // Download the archive
     if (!file_exists(TL_ROOT . '/' . $archive)) {
         $objRequest = new \Request();
         $objRequest->send($GLOBALS['TL_CONFIG']['liveUpdateBase'] . 'request.php?token=' . \Input::get('token'));
         if ($objRequest->hasError()) {
             $objTemplate->updateClass = 'tl_error';
             $objTemplate->updateMessage = $objRequest->response;
             return;
         }
         $objFile = new \File($archive);
         $objFile->write($objRequest->response);
         $objFile->close();
     }
     $objArchive = new \ZipReader($archive);
     // Extract
     while ($objArchive->next()) {
         if ($objArchive->file_name != 'TOC.txt') {
             try {
                 $objFile = new \File($objArchive->file_name);
                 $objFile->write($objArchive->unzip());
                 $objFile->close();
             } catch (\Exception $e) {
                 $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();
 }
Exemplo n.º 12
0
 public function restoreBackup($restoreFile, $boolDB = false, $boolFiles = false)
 {
     $arrOutput = array();
     if ($restoreFile) {
         $c2gFile = new File("backups/" . $restoreFile);
         if ($c2gFile->extension == 'c2g') {
             $c2gZipFile = new ZipReader("backups/" . $restoreFile);
             $descFile = $c2gZipFile->getFile("description.php");
             if ($descFile) {
                 unset($GLOBALS["package"]);
                 eval($c2gZipFile->unzip());
                 $arrOutput[] = sprintf($GLOBALS['TL_LANG']['tl_content']['c2g_restorebackup'], $GLOBALS["package"]["Name"]);
                 $dirName = TL_ROOT . '/' . $GLOBALS["package"]["RootDir"] . '/' . $GLOBALS["package"]["Name"];
                 if ($boolFiles) {
                     $strRestoreFolder = new Folder($GLOBALS["package"]["RootDir"] . @'/' . $GLOBALS["package"]["Name"] . @'/');
                     if ($GLOBALS["package"]["RootDir"] != '.' && is_dir($dirName)) {
                         $this->c2g_functions->rrmdir($dirName);
                         $arrOutput[] = sprintf($GLOBALS['TL_LANG']['tl_content']['c2g_restorebackup_cleandir'], $GLOBALS["package"]["Name"]);
                     }
                     $directoryFile = $c2gZipFile->getFile("directories.dat");
                     if ($directoryFile) {
                         $strDirectories = $c2gZipFile->unzip();
                         $arrDirectories = explode("\r\n", $strDirectories);
                         if (is_array($arrDirectories)) {
                             foreach ($arrDirectories as $dir) {
                                 $objDir = new Folder($dir);
                             }
                         }
                     }
                     $c2gZipFile->first();
                     $arrFileList = $c2gZipFile->getFileList();
                     foreach ($arrFileList as $file) {
                         $c2gZipFile->getFile($file);
                         $objFile = new File('vhosts/' . $file);
                         $strData = $c2gZipFile->unzip();
                         if (basename($file) == 'localconfig.php') {
                             $objFile->write($strData);
                             $objFile->close();
                             $arrConfigReturn = @$this->c2g_functions->loadVHostConfig(TL_ROOT . '/vhosts/' . $GLOBALS["package"]["Name"], false);
                             $objFile = new File('vhosts/' . $file);
                             $strData = $this->c2g_functions->rewriteLocalconfig($strData, $GLOBALS['TL_CONFIG']['dbHost'], $GLOBALS['TL_CONFIG']['dbPort'], $arrConfigReturn['localconfig']['dbDatabase'], $GLOBALS['TL_CONFIG']['dbUser'], $GLOBALS['TL_CONFIG']['dbPass'], $arrConfigReturn['localconfig']['websitePath']);
                         }
                         $objFile->write($strData);
                         $objFile->close();
                         // let the directorystructure create, but remove .empty file
                         if (basename($file) == '.empty') {
                             $objFile->delete();
                         }
                     }
                     $arrOutput[] = $GLOBALS['TL_LANG']['tl_content']['c2g_restorebackup_filesystemrestored'];
                 }
                 $arrConfigReturn = $this->c2g_functions->loadVHostConfig(TL_ROOT . '/vhosts/' . $GLOBALS["package"]["Name"]);
                 if (IS_CONTAO3) {
                     $objFile = new File('vhosts/' . $GLOBALS["package"]["Name"] . '/system/config/pathconfig.php', true);
                     $objFile->write("<?php\n\n// Relative path to the installation\nreturn '/vhosts/" . $GLOBALS["package"]["Name"] . "';\n");
                     $objFile->close();
                     $arrOutput[] = $GLOBALS['TL_LANG']['tl_content']['c2g_createpathconfig'];
                 }
                 if ($boolDB) {
                     $file = $c2gFile->filename . '.sql';
                     $c2gZipFile->getFile($file);
                     $objFile = new File('vhosts/' . $file);
                     $objFile->write($c2gZipFile->unzip());
                     $objFile->close();
                     $sqlDump = new File($GLOBALS["package"]["RootDir"] . '/' . $file);
                     $this->c2g_functions->restoreDump($sqlDump->getContent());
                     $sqlDump->close();
                     $arrOutput[] = $GLOBALS['TL_LANG']['tl_content']['c2g_restorebackup_sqlrestored'];
                 }
                 $objDescFile = new File($GLOBALS["package"]["RootDir"] . '/description.php');
                 $objDescFile->delete();
                 $objDirFile = new File($GLOBALS["package"]["RootDir"] . '/directories.dat');
                 $objDirFile->delete();
                 $objSQLFile = new File($GLOBALS["package"]["RootDir"] . '/' . $c2gFile->filename . '.sql');
                 $objSQLFile->delete();
             }
         }
         $arrOutput[] = sprintf('<a href="%s" title="%s">%s</a>', $this->pathMySelf, $GLOBALS['TL_LANG']['tl_content']['c2g_backupreturntooverview'], $GLOBALS['TL_LANG']['tl_content']['c2g_backupreturntooverview']);
         $pathBackups = $this->replaceInsertTags(sprintf('{{link_url::%s}}', $this->c2g_listvhosts));
         $arrOutput[] = sprintf('<a href="%s" title="%s">%s</a>', $pathBackups, $GLOBALS['TL_LANG']['tl_content']['c2g_backupreturntovhosts'], $GLOBALS['TL_LANG']['tl_content']['c2g_backupreturntovhosts']);
     }
     return implode("<br />", $arrOutput);
 }
Exemplo n.º 13
0
 /**
  * Restore database-backup from zip
  * 
  * @param string $strRestoreFile Path to file like system/backup/backup.zip
  * @param bool $booTruncate 
  * @return type 
  */
 public function runRestore($strRestoreFile, $arrSuffixSQL = null)
 {
     try {
         // Set time out for database. Ticket #2653
         if ($GLOBALS['TL_CONFIG']['syncCto_custom_settings'] == true && intval($GLOBALS['TL_CONFIG']['syncCto_wait_timeout']) > 0 && intval($GLOBALS['TL_CONFIG']['syncCto_interactive_timeout']) > 0) {
             $this->Database->query('SET SESSION wait_timeout = GREATEST(' . intval($GLOBALS['TL_CONFIG']['syncCto_wait_timeout']) . ', @@wait_timeout), SESSION interactive_timeout = GREATEST(' . intval($GLOBALS['TL_CONFIG']['syncCto_interactive_timeout']) . ', @@wait_timeout);');
         } else {
             $this->Database->query('SET SESSION wait_timeout = GREATEST(28000, @@wait_timeout), SESSION interactive_timeout = GREATEST(28000, @@wait_timeout);');
         }
         switch (pathinfo($strRestoreFile, PATHINFO_EXTENSION)) {
             case "zip":
                 $objZipRead = new ZipReader($strRestoreFile);
                 // Get structure
                 if ($objZipRead->getFile($this->strFilenameSyncCto)) {
                     $objGzFile = new File("system/tmp/{$this->strFilenameSyncCto}.gz");
                     $objGzFile->write($objZipRead->unzip());
                     $objGzFile->close();
                     $arrRestoreTables = $this->runRestoreFromXML("system/tmp/{$this->strFilenameSyncCto}.gz");
                 } else {
                     $arrRestoreTables = $this->runRestoreFromSer($strRestoreFile);
                 }
                 break;
             case "synccto":
                 $arrRestoreTables = $this->runRestoreFromXML($strRestoreFile);
                 break;
             default:
                 throw new Exception("Not supportet or Unknown file type.");
                 break;
         }
         // After insert, call some SQL
         if (is_array($arrSuffixSQL)) {
             foreach ($arrSuffixSQL as $key => $value) {
                 $this->Database->query($value['query']);
             }
         }
         // Rename temp tables
         foreach ($arrRestoreTables as $key => $value) {
             $this->Database->query("DROP TABLE IF EXISTS " . $value);
             $this->Database->query("RENAME TABLE " . "synccto_temp_" . $value . " TO " . $value);
         }
     } catch (Exception $exc) {
         // Drop synccto_temp tables
         foreach ($this->Database->listTables() as $key => $value) {
             if (preg_match("/synccto_temp_.*/", $value)) {
                 $this->Database->query("DROP TABLE IF EXISTS {$value}");
             }
         }
         throw $exc;
     }
     // Drop synccto_temp tables
     foreach ($this->Database->listTables() as $key => $value) {
         if (preg_match("/synccto_temp_.*/", $value)) {
             $this->Database->query("DROP TABLE IF EXISTS {$value}");
         }
     }
     return $arrSuffixSQL;
 }
Exemplo n.º 14
0
 /**
  * Import ZAD Send News managers from XML files.
  * @param Array
  */
 protected function importFiles($files)
 {
     foreach ($files as $zipfile) {
         $xml = null;
         // open zip file
         $zip = new \ZipReader($zipfile);
         // extract XML file
         if ($zip->next() && $zip->file_name == 'sendnews.xml') {
             // load the XML file
             $xml = new \DOMDocument();
             $xml->preserveWhiteSpace = false;
             $xml->loadXML($zip->unzip());
         }
         // if there is no XML file, skip to next zip file
         if (!$xml instanceof \DOMDocument) {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['err_import_xml'], basename($zipfile)));
             continue;
         }
         // read XML
         $tab = array();
         $version = $xml->getElementsByTagName('tables')->item($i)->getAttribute('version');
         if (!$version || $version != '2.0') {
             // warning: version is different!
             \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['wrn_import_version'], basename($zipfile)));
         }
         $tables = $xml->getElementsByTagName('table');
         for ($i = 0; $i < $tables->length; $i++) {
             // loop through tables
             $rows = $tables->item($i)->childNodes;
             $table = $tables->item($i)->getAttribute('name');
             for ($j = 0; $j < $rows->length; $j++) {
                 // loop through rows
                 $fields = $rows->item($j)->childNodes;
                 for ($k = 0; $k < $fields->length; $k++) {
                     // loop through fields
                     $value = $fields->item($k)->nodeValue;
                     $name = $fields->item($k)->getAttribute('name');
                     $tab[$table][$j][$name] = $value;
                 }
             }
         }
         // get current news archive id
         $news = $this->Database->prepare("SELECT id FROM tl_news_archive WHERE title=?")->limit(1)->execute($tab['tl_news_archive'][0]['title']);
         if ($news->numRows < 1) {
             // set first news archive
             $news = $this->Database->prepare("SELECT id FROM tl_news_archive ORDER BY id")->limit(1)->execute();
             if ($news->numRows < 1) {
                 // no news archive
                 $news->id = 0;
             }
         }
         // set news archive id
         $tab['tl_zad_sendnews'][0]['news_archive'] = $news->id;
         // get current news author id
         $user = $this->Database->prepare("SELECT id FROM tl_user WHERE username=? OR name=? OR email=?")->limit(1)->execute($tab['tl_user'][0]['username'], $tab['tl_user'][0]['name'], $tab['tl_user'][0]['email']);
         if ($user->numRows < 1) {
             // set first user
             $user = $this->Database->prepare("SELECT id FROM tl_user ORDER BY id")->limit(1)->execute();
             if ($user->numRows < 1) {
                 // no news author
                 $user->id = 0;
             }
         }
         // set news author id
         $tab['tl_zad_sendnews'][0]['news_author'] = $user->id;
         // set send news manager name
         $name = $this->Database->prepare("SELECT count(*) AS cnt FROM tl_zad_sendnews WHERE name LIKE ?")->execute($tab['tl_zad_sendnews'][0]['name'] . '%');
         $tab['tl_zad_sendnews'][0]['name'] .= $name->cnt > 0 ? ' - ' . $name->cnt : '';
         // lock tables
         $locks = array('tl_zad_sendnews' => 'WRITE', 'tl_zad_sendnews_rule' => 'WRITE');
         $this->Database->lockTables($locks);
         // get current values
         $tab['tl_zad_sendnews'][0]['id'] = $this->Database->getNextId('tl_zad_sendnews');
         $tab['tl_zad_sendnews'][0]['tstamp'] = time();
         $tab['tl_zad_sendnews'][0]['active'] = '';
         // insert imported manager
         $this->Database->prepare("INSERT INTO tl_zad_sendnews %s")->set($tab['tl_zad_sendnews'][0])->execute();
         // insert imported rules
         foreach ($tab['tl_zad_sendnews_rule'] as $rule) {
             // get current values
             $rule['id'] = $this->Database->getNextId('tl_zad_sendnews_rule');
             $rule['pid'] = $tab['tl_zad_sendnews'][0]['id'];
             $rule['tstamp'] = time();
             $this->Database->prepare("INSERT INTO tl_zad_sendnews_rule %s")->set($rule)->execute();
         }
         // unlock tables
         $this->Database->unlockTables();
         // notify the user
         \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_zad_sendnews']['ok_imported'], basename($zipfile)));
     }
     // redirect
     \System::setCookie('BE_PAGE_OFFSET', 0, 0);
     $this->redirect(str_replace('&key=import', '', \Environment::get('request')));
 }
Exemplo n.º 15
0
 /**
  * Extract the theme files and write the data to the database
  * @param array
  * @param array
  */
 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 {
                 $strFileName = $objArchive->file_name;
                 // Support the old "tl_files" directory
                 if (strncmp($strFileName, 'tl_files/', 9) === 0) {
                     $strFileName = substr($strFileName, 3);
                 }
                 // Override the files directory
                 if ($GLOBALS['TL_CONFIG']['uploadPath'] != 'files' && strncmp($strFileName, 'files/', 6) === 0) {
                     $strFileName = preg_replace('@^files/@', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $strFileName);
                 }
                 $objFile = new \File($strFileName);
                 $objFile->write($objArchive->unzip());
                 $objFile->close();
             } 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 (is_array($arrNewFolders) && !empty($arrNewFolders)) {
             foreach ($arrNewFolders as $strFolder) {
                 // Support the old "tl_files" folder
                 if (strncmp($strFolder, 'tl_files/', 9) === 0) {
                     $strFolder = substr($strFolder, 3);
                 }
                 // Override the files directory
                 if ($GLOBALS['TL_CONFIG']['uploadPath'] != 'files') {
                     $strFolder = preg_replace('@^files/@', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $strFolder);
                 }
                 // Index the parent folders
                 $strTmp = $strFolder;
                 $intNextPid = null;
                 $arrParents = array();
                 while ($strTmp != '' && $strTmp != '.' && $strTmp != $GLOBALS['TL_CONFIG']['uploadPath']) {
                     $arrParents[] = $strTmp;
                     $strTmp = dirname($strTmp);
                 }
                 foreach (array_reverse($arrParents) as $strParent) {
                     $objParent = \FilesModel::findByPath($strParent);
                     if ($objParent === null) {
                         if ($intNextPid === null) {
                             if (dirname($strParent) == $GLOBALS['TL_CONFIG']['uploadPath']) {
                                 $intNextPid = 0;
                             } else {
                                 $objPid = \FilesModel::findByPath(dirname($strParent));
                                 $intNextPid = $objPid->id;
                             }
                         }
                         $objFolder = new \Folder($strParent);
                         $objModel = new \FilesModel();
                         $objModel->pid = $intNextPid;
                         $objModel->tstamp = time();
                         $objModel->name = basename($strParent);
                         $objModel->type = 'folder';
                         $objModel->path = $strParent;
                         $objModel->hash = $objFolder->hash;
                         $objModel->found = 1;
                         $objModel->save();
                         $intNextPid = $objModel->id;
                     }
                 }
                 $this->syncNewFolder($strFolder, $intNextPid);
             }
         }
         // Lock the tables
         $arrLocks = array('tl_files' => 'WRITE', 'tl_layout' => 'WRITE', 'tl_module' => 'WRITE', 'tl_style_sheet' => 'WRITE', 'tl_style' => 'WRITE', 'tl_theme' => 'WRITE');
         $this->Database->lockTables($arrLocks);
         // Get the current auto_increment values
         $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');
         // 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 ($table != 'tl_theme' && $table != 'tl_style_sheet' && $table != 'tl_style' && $table != 'tl_module' && $table != 'tl_layout') {
                 continue;
             }
             // 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');
                     // Support the old "tl_files" folder
                     if (strncmp($value, 'tl_files/', 9) === 0) {
                         $value = substr($value, 3);
                     }
                     // 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];
                         } 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 (array_keys($modules) as $key) {
                                 if ($modules[$key]['mod'] > 0) {
                                     $modules[$key]['mod'] = $arrMapper['tl_module'][$modules[$key]['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 ($GLOBALS['TL_CONFIG']['uploadPath'] != 'files' && ($table == 'tl_style_sheet' || $table == 'tl_style') && strpos($value, 'files') !== false) {
                         $tmp = deserialize($value);
                         if (is_array($tmp)) {
                             foreach ($tmp as $kk => $vv) {
                                 $tmp[$kk] = preg_replace('@^files/@', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $vv);
                             }
                             $value = serialize($tmp);
                         } else {
                             $value = preg_replace('@^files/@', $GLOBALS['TL_CONFIG']['uploadPath'] . '/', $value);
                         }
                     } elseif ($table == 'tl_theme' && $name == 'screenshot' || $table == 'tl_module' && $name == 'singleSRC' || $table == 'tl_module' && $name == 'reg_homeDir') {
                         if ($value === null) {
                             $value = '';
                             // the field cannot be NULL
                         } elseif ($value != '') {
                             // Do not use the FilesModel here – tables are locked!
                             $objFile = $this->Database->prepare("SELECT id FROM tl_files WHERE path=?")->limit(1)->executeUncached($value);
                             $value = $objFile->id;
                         }
                     } elseif ($table == 'tl_theme' && $name == 'folders' || $table == 'tl_module' && $name == 'multiSRC') {
                         $tmp = deserialize($value);
                         if (is_array($tmp)) {
                             foreach ($tmp as $kk => $vv) {
                                 // Support the old "tl_files" folder
                                 if (strncmp($vv, 'tl_files/', 9) === 0) {
                                     $vv = substr($vv, 3);
                                 }
                                 // Do not use the FilesModel here – tables are locked!
                                 $objFile = $this->Database->prepare("SELECT id FROM tl_files WHERE path=?")->limit(1)->executeUncached($vv);
                                 $tmp[$kk] = $objFile->id;
                             }
                             $value = serialize($tmp);
                         }
                     }
                     $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]);
                     }
                 }
                 // Update the datatbase
                 $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)));
     }
     setcookie('BE_PAGE_OFFSET', 0, 0, '/');
     $this->Session->remove('uploaded_themes');
     // Redirect
     $this->redirect(str_replace('&key=importTheme', '', \Environment::get('request')));
 }
Exemplo n.º 16
0
 /**
  * Restore database-backup from zip.
  *
  * @param string $strRestoreFile Path to file like system/backup/backup.zip
  *
  * @param null   $arrSuffixSQL
  *
  * @return type
  *
  * @throws Exception
  *
  * @internal param bool $booTruncate
  */
 public function runRestore($strRestoreFile, $arrSuffixSQL = null)
 {
     // Load the path builder.
     $pathBuilder = new \SyncCto\Helper\PathBuilder();
     try {
         // Set time out for database. Ticket #2653
         $tmpResult = \Database::getInstance()->execute('SELECT @@SESSION.wait_timeout as wTimeout, @@SESSION.interactive_timeout as iTimeout');
         $waitTimeOut = $tmpResult->wTimeout;
         $interactiveTimeout = $tmpResult->iTimeout;
         //overwrite the default values if higher ones are defined in the settings
         if ($GLOBALS['TL_CONFIG']['syncCto_custom_settings'] == true && intval($GLOBALS['TL_CONFIG']['syncCto_wait_timeout']) > 0 && intval($GLOBALS['TL_CONFIG']['syncCto_interactive_timeout']) > 0) {
             $waitTimeOut = max($waitTimeOut, intval($GLOBALS['TL_CONFIG']['syncCto_wait_timeout']));
             $interactiveTimeout = max($interactiveTimeout, intval($GLOBALS['TL_CONFIG']['syncCto_interactive_timeout']));
         }
         \Database::getInstance()->prepare('SET SESSION wait_timeout = ?,SESSION interactive_timeout = ?;')->execute(intval($waitTimeOut), intval($interactiveTimeout));
         switch (pathinfo($strRestoreFile, PATHINFO_EXTENSION)) {
             case "zip":
                 $objZipRead = new ZipReader($strRestoreFile);
                 // Get structure
                 if ($objZipRead->getFile($this->strFilenameSyncCto)) {
                     $zipPath = $pathBuilder->addPath('system/tmp')->addUnknownPath(sprintf('%s.gz', $this->strFilenameSyncCto))->getPath(false);
                     $objGzFile = new File($zipPath);
                     $objGzFile->write($objZipRead->unzip());
                     $objGzFile->close();
                     $arrRestoreTables = $this->runRestoreFromXML("system/tmp/{$this->strFilenameSyncCto}.gz");
                 } else {
                     $strRestoreFile = $pathBuilder->addUnknownPath($strRestoreFile)->getPath(false);
                     $arrRestoreTables = $this->runRestoreFromSer($strRestoreFile);
                 }
                 break;
             case "synccto":
                 $strRestoreFile = $pathBuilder->addUnknownPath($strRestoreFile)->getPath(false);
                 $arrRestoreTables = $this->runRestoreFromXML($strRestoreFile);
                 break;
             default:
                 throw new Exception("Not supportet or Unknown file type.");
                 break;
         }
         // After insert, call some SQL
         if (is_array($arrSuffixSQL)) {
             foreach ($arrSuffixSQL as $key => $value) {
                 $this->Database->query($value['query']);
             }
         }
         // Rename temp tables
         foreach ($arrRestoreTables as $key => $value) {
             $this->Database->query("DROP TABLE IF EXISTS " . $value);
             $this->Database->query("RENAME TABLE " . "synccto_temp_" . $value . " TO " . $value);
         }
     } catch (Exception $exc) {
         // Drop synccto_temp tables
         foreach ($this->Database->listTables() as $key => $value) {
             if (preg_match("/synccto_temp_.*/", $value)) {
                 $this->Database->query("DROP TABLE IF EXISTS {$value}");
             }
         }
         throw $exc;
     }
     // Drop synccto_temp tables
     foreach ($this->Database->listTables() as $key => $value) {
         if (preg_match("/synccto_temp_.*/", $value)) {
             $this->Database->query("DROP TABLE IF EXISTS {$value}");
         }
     }
     return $arrSuffixSQL;
 }