/**
  * Write sitemap-file
  *
  * @global     object
  * @global     array
  * @param   array An array containing the language ID's of which languages should be included in the sitemap.
  * @param   string  The two letter language code of the selected language used as the virtual language path
  */
 protected function writeXML()
 {
     $filename = \FWLanguage::getLanguageCodeById($this->lang) ? sprintf(self::$strFileNameWithLang, \FWLanguage::getLanguageCodeById($this->lang)) : self::$strFileName;
     $xml = $this->render();
     try {
         $filePath = \Env::get('cx')->getWebsiteDocumentRootPath();
         $objFile = new \Cx\Lib\FileSystem\File($filePath . self::$strFilePath . '/' . $filename);
         $objFile->touch();
         $objFile->write($xml);
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::log($e->getMessage());
         return false;
     }
     return true;
 }
 /**
  * Handle the calendar image upload
  * 
  * @param string $id unique form id
  * 
  * @return string image path
  */
 function _handleUpload($fieldName, $id)
 {
     $tup = self::getTemporaryUploadPath($fieldName, $id);
     $tmpUploadDir = \Env::get('cx')->getWebsitePath() . $tup[1] . '/' . $tup[2] . '/';
     //all the files uploaded are in here
     $depositionTarget = $this->uploadImgPath;
     //target folder
     $pic = '';
     //move all files
     if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpUploadDir)) {
         throw new \Exception("could not find temporary upload directory '{$tmpUploadDir}'");
     }
     $h = opendir($tmpUploadDir);
     if ($h) {
         while (false !== ($f = readdir($h))) {
             // skip folders and thumbnails
             if ($f == '..' || $f == '.' || preg_match("/(?:\\.(?:thumb_thumbnail|thumb_medium|thumb_large)\\.[^.]+\$)|(?:\\.thumb)\$/i", $f)) {
                 continue;
             }
             //do not overwrite existing files.
             $prefix = '';
             while (file_exists($depositionTarget . $prefix . $f)) {
                 if (empty($prefix)) {
                     $prefix = 0;
                 }
                 $prefix++;
             }
             // move file
             try {
                 $objFile = new \Cx\Lib\FileSystem\File($tmpUploadDir . $f);
                 $fileInfo = pathinfo($tmpUploadDir . $f);
                 $objFile->move($depositionTarget . $prefix . $f, false);
                 $imageName = $prefix . $f;
                 if (in_array($fileInfo['extension'], array('gif', 'jpg', 'jpeg', 'png'))) {
                     $objImage = new \ImageManager();
                     $objImage->_createThumb($this->uploadImgPath, $this->uploadImgWebPath, $imageName, 180);
                 }
                 $pic = contrexx_input2raw($this->uploadImgWebPath . $imageName);
                 // abort after one file has been fetched, as all event upload
                 // fields do allow a single file only anyway
                 break;
             } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
                 \DBG::msg($e->getMessage());
             }
         }
     }
     return $pic;
 }
function activateDebugging()
{
    $File = new \Cx\Lib\FileSystem\File(ASCMS_DOCUMENT_ROOT . '/update/dbg.log');
    if ($File->getAccessMode() == \Cx\Lib\FileSystem\File::FTP_ACCESS) {
        throw new \Exception('Cannot write log via FTP (file needs to be loaded into memory which leads to memory overflow)');
    }
    // temporariy disable FTP support to prevent the FileSystem
    // from creating the dbg.log file through FTP
    $ftpConfig = \Env::get('ftpConfig');
    if ($ftpConfig['is_activated']) {
        \DBG::msg('Update: Intentionally deactivate FTP support as we do not support to write the update log (dbg.log) through FTP due to potential memory overflows.');
        $hackedFtpConfig = $ftpConfig;
        $hackedFtpConfig['is_activated'] = false;
        \Env::set('ftpConfig', $hackedFtpConfig);
    }
    $File->touch();
    // reset FTP
    if ($ftpConfig['is_activated']) {
        \Env::set('ftpConfig', $ftpConfig);
    }
    if ($File->makeWritable()) {
        \DBG::activate(DBG_LOG_FILE | DBG_PHP | DBG_DB);
        return true;
    }
    return false;
}
示例#4
0
 /**
  * Upload Finished callback
  *
  * This is called as soon as uploads have finished.
  * takes care of moving them to the right folder
  *
  * @param string $tempPath    Path to the temporary directory containing the files at this moment
  * @param string $tempWebPath Points to the same folder as tempPath, but relative to the webroot
  * @param array  $data        Data given to setData() when creating the uploader
  * @param string $uploadId    unique session id for the current upload
  * @param array  $fileInfos   uploaded file informations
  * @param array  $response    uploaded status
  *
  * @return array path and webpath
  */
 public static function uploadFinished($tempPath, $tempWebPath, $data, $uploadId, $fileInfos, $response)
 {
     $path = $data['path'];
     $webPath = $data['webPath'];
     $objCategory = Category::getCategory($data['category_id']);
     // check for sufficient permissions
     if ($objCategory->getAddFilesAccessId() && !\Permission::checkAccess($objCategory->getAddFilesAccessId(), 'dynamic', true) && $objCategory->getOwnerId() != \FWUser::getFWUserObject()->objUser->getId()) {
         return;
     }
     //we remember the names of the uploaded files here. they are stored in the session afterwards,
     //so we can later display them highlighted.
     $arrFiles = array();
     $uploadFiles = array();
     //rename files, delete unwanted
     $arrFilesToRename = array();
     //used to remember the files we need to rename
     $h = opendir($tempPath);
     if (!$h) {
         return array($path, $webPath);
     }
     while (false !== ($file = readdir($h))) {
         //skip . and ..
         if ($file == '.' || $file == '..') {
             continue;
         }
         try {
             //delete potentially malicious files
             $objTempFile = new \Cx\Lib\FileSystem\File($tempPath . '/' . $file);
             if (!\FWValidator::is_file_ending_harmless($file)) {
                 $objTempFile->delete();
                 continue;
             }
             $cleanFile = \Cx\Lib\FileSystem\FileSystem::replaceCharacters($file);
             if ($cleanFile != $file) {
                 $objTempFile->rename($tempPath . '/' . $cleanFile, false);
                 $file = $cleanFile;
             }
             $info = pathinfo($file);
             //check if file needs to be renamed
             $newName = '';
             $suffix = '';
             if (file_exists($path . '/' . $file)) {
                 $suffix = '_' . time();
                 $newName = $info['filename'] . $suffix . '.' . $info['extension'];
                 $arrFilesToRename[$file] = $newName;
                 array_push($arrFiles, $newName);
             }
             if (!isset($arrFilesToRename[$file])) {
                 array_push($uploadFiles, $file);
             }
             //rename files where needed
             foreach ($arrFilesToRename as $oldName => $newName) {
                 $objTempFile = new \Cx\Lib\FileSystem\File($tempPath . '/' . $oldName);
                 $objTempFile->rename($tempPath . '/' . $newName, false);
                 array_push($uploadFiles, $newName);
             }
             //move file from temp path into target folder
             $objImage = new \ImageManager();
             foreach ($uploadFiles as $fileName) {
                 $objFile = new \Cx\Lib\FileSystem\File($tempPath . '/' . $fileName);
                 $objFile->move($path . '/' . $fileName, false);
                 \Cx\Core\Core\Controller\Cx::instanciate()->getMediaSourceManager()->getThumbnailGenerator()->createThumbnailFromPath($path . '/' . $fileName);
             }
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             \DBG::msg($e->getMessage());
         }
         $objDownloads = new downloads('');
         $objDownloads->addDownloadFromUpload($info['filename'], $info['extension'], $suffix, $objCategory, $objDownloads, $fileInfos['name']);
     }
     return array($path, $webPath);
 }
示例#5
0
 /**
  *
  * @param Cx\Core_Modules\Listing\Model\ExportInterface $exportInterface
  * @param type $filename 
  * @throws \Cx\Lib\FileSystem\FileSystemException
  */
 public function exportToFile(\Cx\Core_Modules\Listing\Model\Entity\Exportable $exportInterface, $filename)
 {
     try {
         $objFile = new \Cx\Lib\FileSystem\File($filename);
         $objFile->touch();
         $objFile->write($this->export($exportInterface));
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::msg($e->getMessage());
         throw new DataSetException("Failed to export data to file {$filename}!");
     }
 }
示例#6
0
 /**
  * Write all settings into the config-file
  *
  */
 function _createSettingsFile()
 {
     global $_ARRLANG;
     $objDb = $this->_getDbObject($statusMsg);
     if ($objDb === false) {
         return $statusMsg;
     } else {
         $strSettingsFile = $_SESSION['installer']['config']['documentRoot'] . $_SESSION['installer']['config']['offsetPath'] . '/config/settings.php';
         if (!\Cx\Lib\FileSystem\FileSystem::touch($strSettingsFile) || !\Cx\Lib\FileSystem\FileSystem::makeWritable($strSettingsFile)) {
             return sprintf($_ARRLANG['TXT_SETTINGS_ERROR_WRITABLE'], $strSettingsFile);
         }
         //Header & Footer
         $strHeader = "<?php\n";
         $strHeader .= "/**\n";
         $strHeader .= "* This file is generated by the \"settings\"-menu in your CMS.\n";
         $strHeader .= "* Do not try to edit it manually!\n";
         $strHeader .= "*/\n\n";
         $strFooter = "\n";
         //Get module-names
         $objResult = $objDb->Execute("SELECT id, name FROM `" . $_SESSION['installer']['config']['dbTablePrefix'] . "modules`");
         if ($objResult->RecordCount() > 0) {
             while (!$objResult->EOF) {
                 $arrModules[$objResult->fields['id']] = $objResult->fields['name'];
                 $objResult->MoveNext();
             }
         }
         //Get values
         $objResult = $objDb->Execute("SELECT setname, setmodule, setvalue FROM `" . $_SESSION['installer']['config']['dbTablePrefix'] . "settings` ORDER BY    setmodule ASC, setname ASC");
         $intMaxLen = 0;
         if ($objResult->RecordCount() > 0) {
             while (!$objResult->EOF) {
                 $intMaxLen = strlen($objResult->fields['setname']) > $intMaxLen ? strlen($objResult->fields['setname']) : $intMaxLen;
                 $arrValues[$objResult->fields['setmodule']][$objResult->fields['setname']] = $objResult->fields['setvalue'];
                 $objResult->MoveNext();
             }
         }
         $intMaxLen += strlen('$_CONFIG[\'\']') + 1;
         //needed for formatted output
         //Write values
         $data = $strHeader;
         $strBody = '';
         foreach ($arrValues as $intModule => $arrInner) {
             $strBody .= "/**\n";
             $strBody .= "* -------------------------------------------------------------------------\n";
             $strBody .= "* " . ucfirst(isset($arrModules[$intModule]) ? $arrModules[$intModule] : '') . "\n";
             $strBody .= "* -------------------------------------------------------------------------\n";
             $strBody .= "*/\n";
             foreach ($arrInner as $strName => $strValue) {
                 $strBody .= sprintf("%-" . $intMaxLen . "s", '$_CONFIG[\'' . $strName . '\']');
                 $strBody .= "= ";
                 $strBody .= (is_numeric($strValue) ? $strValue : '"' . str_replace('"', '\\"', $strValue) . '"') . ";\n";
             }
             $strBody .= "\n";
         }
         $data .= $strBody;
         $data .= $strFooter;
         try {
             $objFile = new \Cx\Lib\FileSystem\File($strSettingsFile);
             $objFile->write($data);
             return true;
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             DBG::msg($e->getMessage());
         }
         return false;
     }
 }
示例#7
0
function _writeNewConfigurationFile()
{
    global $_CORELANG, $_ARRAYLANG, $_DBCONFIG, $_PATHCONFIG, $_FTPCONFIG, $_CONFIGURATION, $_CONFIG;
    $ftpStatus = $_FTPCONFIG['is_activated'] ? 'true' : 'false';
    $charset = 'UTF-8';
    $dbCharset = 'utf8';
    $_FTPCONFIG['port'] = intval($_FTPCONFIG['port']);
    $configurationTpl = <<<CONFIG_TPL
<?php
global \$_DBCONFIG, \$_PATHCONFIG, \$_FTPCONFIG, \$_CONFIG;
/**
* @exclude
*
* Cloudrexx CMS Web Installer
* Please use the Cloudrexx CMS installer to configure this file
* or edit this file and configure the parameters for your site and
* database manually.
*/

/**
* -------------------------------------------------------------------------
* Set installation status
* -------------------------------------------------------------------------
*/
define('CONTREXX_INSTALLED', true);

/**
* -------------------------------------------------------------------------
* Database configuration section
* -------------------------------------------------------------------------
*/
\$_DBCONFIG['host'] = '{$_DBCONFIG['host']}'; // This is normally set to localhost
\$_DBCONFIG['database'] = '{$_DBCONFIG['database']}'; // Database name
\$_DBCONFIG['tablePrefix'] = '{$_DBCONFIG['tablePrefix']}'; // Database table prefix
\$_DBCONFIG['user'] = '******'user']}'; // Database username
\$_DBCONFIG['password'] = '******'password']}'; // Database password
\$_DBCONFIG['dbType'] = '{$_DBCONFIG['dbType']}';    // Database type (e.g. mysql,postgres ..)
\$_DBCONFIG['charset'] = '{$dbCharset}'; // Charset (default, latin1, utf8, ..)
\$_DBCONFIG['timezone'] = '{$_CONFIG['timezone']}'; // Controller's timezone for model
\$_DBCONFIG['collation'] = '{$_DBCONFIG['collation']}';

/**
* -------------------------------------------------------------------------
* Site path specific configuration
* -------------------------------------------------------------------------
*/
\$_PATHCONFIG['ascms_root'] = '';
\$_PATHCONFIG['ascms_root_offset'] = ''; // example: '/cms';
\$_PATHCONFIG['ascms_installation_root'] = \$_PATHCONFIG['ascms_root'];
\$_PATHCONFIG['ascms_installation_offset'] = \$_PATHCONFIG['ascms_root_offset']; // example: '/cms';

/**
* -------------------------------------------------------------------------
* Ftp specific configuration
* -------------------------------------------------------------------------
*/
\$_FTPCONFIG['is_activated'] = {$ftpStatus}; // Ftp support true or false
\$_FTPCONFIG['host']    = '{$_FTPCONFIG['host']}';// This is normally set to localhost
\$_FTPCONFIG['port'] = {$_FTPCONFIG['port']}; // Ftp remote port
\$_FTPCONFIG['username'] = '******'username']}'; // Ftp login username
\$_FTPCONFIG['password']    = '******'password']}'; // Ftp login password
\$_FTPCONFIG['path']    = '{$_FTPCONFIG['path']}'; // Ftp path to cms (must not include ascms_root_offset)

/**
* -------------------------------------------------------------------------
* Base setup (altering might break the system!)
* -------------------------------------------------------------------------
*/
// Set character encoding
\$_CONFIG['coreCharacterEncoding'] = 'UTF-8'; // example 'UTF-8'

CONFIG_TPL;
    // write settings
    try {
        $objFile = new \Cx\Lib\FileSystem\File(ASCMS_DOCUMENT_ROOT . '/config/configuration.php');
        $objFile->makeWritable();
        $objFile->write($configurationTpl);
    } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
        \DBG::msg($e->getMessage());
        setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_WRITE_SETTINGS_FILE'], ASCMS_DOCUMENT_ROOT . '/config/configuration.php'));
        setUpdateMsg(sprintf($_ARRAYLANG['TXT_SET_WRITE_PERMISSON_TO_FILE'], ASCMS_DOCUMENT_ROOT . '/config/configuration.php', $_CORELANG['TXT_UPDATE_TRY_AGAIN']), 'msg');
        return false;
    }
    return true;
}
示例#8
0
 /**
  * Exports a DataSet to a file using an export interface
  *
  * @param Cx\Core_Modules\Listing\Model\Entity\Exportable $exportInterface
  * @param string $filename
  * @param boolean $useCache
  * @throws \Cx\Lib\FileSystem\FileSystemException
  */
 public function exportToFile(\Cx\Core_Modules\Listing\Model\Entity\Exportable $exportInterface, $filename, $useCache = true)
 {
     try {
         $objFile = new \Cx\Lib\FileSystem\File($filename);
         $objFile->touch();
         $export = $this->export($exportInterface);
         $objFile->write($export);
         // delete old key from cache, to reload it on the next import
         if ($useCache) {
             $cache = \Cx\Core\Core\Controller\Cx::instanciate()->getComponent('Cache');
             if (!$cache) {
                 throw new DataSetException('Cache component not available at this stage!');
             }
             $cache->delete($filename);
         }
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::msg($e->getMessage());
         throw new DataSetException("Failed to export data to file {$filename}!");
     }
 }
示例#9
0
 /**
  * Move the uploaded image to destination path from the temp path
  *
  * @return mixed $status | false
  */
 public function uploadPicture()
 {
     $status = "";
     $path = "pictures/";
     //check file array
     $uploaderId = isset($_POST['marketUploaderId']) ? contrexx_input2raw($_POST['marketUploaderId']) : 0;
     $fileName = isset($_POST['uploadImage']) ? contrexx_input2raw($_POST['uploadImage']) : 0;
     if (empty($uploaderId) || empty($fileName)) {
         return false;
     }
     //get file info
     $objSession = \cmsSession::getInstance();
     $tmpFile = $objSession->getTempPath() . '/' . $uploaderId . '/' . $fileName;
     if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpFile)) {
         return false;
     }
     if ($fileName != '' && \FWValidator::is_file_ending_harmless($fileName)) {
         //check extension
         $info = pathinfo($fileName);
         $exte = $info['extension'];
         $exte = !empty($exte) ? '.' . $exte : '';
         $part1 = substr($fileName, 0, strlen($fileName) - strlen($exte));
         $rand = rand(10, 99);
         $fileName = md5($rand . $fileName) . $exte;
         //check file
         // TODO: $x is not defined
         $x = 0;
         if (file_exists($this->mediaPath . $path . $fileName)) {
             $fileName = $rand . $part1 . '_' . (time() + $x) . $exte;
             $fileName = md5($fileName) . $exte;
         }
         //Move the uploaded file to the path specified in the variable $this->mediaPath
         try {
             $objFile = new \Cx\Lib\FileSystem\File($tmpFile);
             if ($objFile->move($this->mediaPath . $path . $fileName, false)) {
                 $objFile = new \File();
                 $objFile->setChmod($this->mediaPath, $this->mediaWebPath, $path . $fileName);
                 $status = $fileName;
             } else {
                 $status = "error";
             }
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             \DBG::msg($e->getMessage());
         }
     } else {
         $status = "error";
     }
     return $status;
 }
 /**
  * Set the component's name in frontend and backend language files
  * @param string $baseDir Directory in which the recursive replace should be done
  */
 public function setComponentName($baseDir)
 {
     $componentNamePlaceholder = '{COMPONENT_NAME}';
     $directoryIterator = new \RecursiveDirectoryIterator($baseDir);
     $iterator = new \RecursiveIteratorIterator($directoryIterator);
     $files = new \RegexIterator($iterator, '/^.+(frontend|backend)\\.php$/i', \RegexIterator::GET_MATCH);
     // recursive foreach frontend.php and backend.php file
     foreach ($files as $file) {
         // prepare data
         $file = current($file);
         // file_get_contents()
         $objFile = new \Cx\Lib\FileSystem\File($file);
         $content = $objFile->getData();
         $content = preg_replace('/' . preg_quote($componentNamePlaceholder) . '/', preg_quote($this->componentName), $content);
         echo 'Replace ' . $componentNamePlaceholder . ' by ' . $this->componentName . ' in ' . $file . "\n";
         $objFile->write($content);
     }
 }
示例#11
0
 /**
  * Upload a file to be associated with a product in the cart
  * @param   string    $fileName             upload file name
  *
  * @return  string                          The file name on success,
  *                                          the empty string otherwise
  * @author    Reto Kohli <*****@*****.**>
  * @static
  */
 static function uploadFile($fileName)
 {
     global $_ARRAYLANG;
     $uploaderId = isset($_REQUEST['productOptionsUploaderId']) ? contrexx_input2raw($_REQUEST['productOptionsUploaderId']) : '';
     if (empty($uploaderId) || empty($fileName)) {
         return '';
     }
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $objSession = $cx->getComponent('Session')->getSession();
     $tmpFile = $objSession->getTempPath() . '/' . $uploaderId . '/' . $fileName;
     if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpFile)) {
         return '';
     }
     $originalFileName = $fileName;
     $arrMatch = array();
     $filename = '';
     $fileext = '';
     if (preg_match('/(.+)(\\.[^.]+)/', $originalFileName, $arrMatch)) {
         $filename = $arrMatch[1];
         $fileext = $arrMatch[2];
     } else {
         $filename = $originalFileName;
     }
     if ($fileext == '.jpg' || $fileext == '.gif' || $fileext == '.png') {
         $newFileName = $filename . '[' . uniqid() . ']' . $fileext;
         $newFilePath = Order::UPLOAD_FOLDER . $newFileName;
         //Move the uploaded file to the path specified in the variable $newFilePath
         try {
             $objFile = new \Cx\Lib\FileSystem\File($tmpFile);
             if ($objFile->move(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteDocumentRootPath() . '/' . $newFilePath, false)) {
                 return $newFileName;
             } else {
                 \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_UPLOADING_FILE']);
             }
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             \DBG::msg($e->getMessage());
         }
     } else {
         \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_ERROR_WRONG_FILETYPE'], $fileext));
     }
     return '';
 }
示例#12
0
function renameCustomizingFile($file)
{
    global $_CONFIG;
    $cxFilePath = dirname(substr($file, strlen(ASCMS_DOCUMENT_ROOT)));
    if ($cxFilePath == '/') {
        $cxFilePath = '';
    }
    $customizingPath = ASCMS_DOCUMENT_ROOT . '/customizing' . $cxFilePath;
    $customizingFile = $customizingPath . '/' . basename($file);
    if (file_exists($customizingFile)) {
        $customizingFile .= "_" . $_CONFIG['coreCmsVersion'];
        $suffix = '';
        $idx = 0;
        while (file_exists($customizingFile . $suffix)) {
            $idx++;
            $suffix = '_' . $idx;
        }
        $customizingFile .= $suffix;
    } else {
        return true;
    }
    try {
        $objFile = new \Cx\Lib\FileSystem\File($file);
        $objFile->move($customizingFile);
    } catch (\Exception $e) {
        setUpdateMsg('Error on renaming customizing file:<br />' . $file);
        setUpdateMsg('Error: ' . $e->getMessage());
        setUpdateMsg('<br />Häufigste Ursache dieses Problems ist, dass zur Ausführung dieses Vorgangs die benötigten Schreibrechte nicht vorhanden sind. Prüfen Sie daher, ob die FTP-Konfiguration in der Datei <strong>config/configuration.php</strong> korrekt eingerichtet ist.');
        return false;
    }
    return true;
}
 /**
  * Upload the media files
  *
  * @param string $fileName   name of the media file
  * @param string $path       folder path
  * @param string $uploaderId uploader id
  *
  * @return string $status name of the uploaded file / error
  */
 function uploadMedia($fileName, $path, $uploaderId)
 {
     if (empty($uploaderId) || empty($fileName)) {
         return 'error';
     }
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $objSession = $cx->getComponent('Session')->getSession();
     $tempPath = $objSession->getTempPath() . '/' . $uploaderId . '/' . $fileName;
     //Check the uploaded file exists in /tmp folder
     if (!\Cx\Lib\FileSystem\FileSystem::exists($tempPath)) {
         //If the file still exists in the mediaPath then return the filename
         if (\Cx\Lib\FileSystem\FileSystem::exists($this->mediaPath . $path . $fileName)) {
             return $fileName;
         }
         return 'error';
     }
     $info = pathinfo($fileName);
     $exte = $info['extension'];
     $extension = !empty($exte) ? '.' . $exte : '';
     $file = substr($fileName, 0, strlen($fileName) - strlen($extension));
     $rand = rand(10, 99);
     $arrSettings = $this->getSettings();
     if ($arrSettings['encodeFilename']['value'] == 1) {
         $fileName = md5($rand . $file) . $extension;
     }
     //Rename the file if the filename already exists
     while (\Cx\Lib\FileSystem\FileSystem::exists($this->mediaPath . $path . $fileName)) {
         $fileName = $file . '_' . time() . $extension;
     }
     $filePath = $this->mediaPath . $path . $fileName;
     if (!\FWValidator::is_file_ending_harmless($filePath)) {
         return 'error';
     }
     //Move the file from /tmp folder into mediaPath and set the permission
     try {
         $objFile = new \Cx\Lib\FileSystem\File($tempPath);
         if ($objFile->move($filePath, false)) {
             $fileObj = new \File();
             $fileObj->setChmod($this->mediaPath, $this->mediaWebPath, $path . $fileName);
             $status = $fileName;
         }
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::msg($e->getMessage());
         $status = 'error';
     }
     //make the thumb
     if (($exte == "gif" || $exte == "jpeg" || $exte == "jpg" || $exte == "png") && $path != "uploads/") {
         $this->createThumb($fileName, $path);
     }
     return $status;
 }
示例#14
0
        return false;
    }
    if (!verifyMd5SumOfFile(ASCMS_DOCUMENT_ROOT . ASCMS_BACKEND_PATH . '/index.php', '', false)) {
        \DBG::msg('...and it\'s customized, so let\'s move it to customizing directory');
        // changes, backup modified file
        if (!backupModifiedFile(ASCMS_DOCUMENT_ROOT . ASCMS_BACKEND_PATH . '/index.php')) {
            setUpdateMsg('Die Datei \'' . ASCMS_DOCUMENT_ROOT . ASCMS_BACKEND_PATH . '/index.php\' konnte nicht kopiert werden.');
            return false;
        }
    } else {
        \DBG::msg('...but it\'s not customized');
    }
    // no non-backupped changes, can delete
    try {
        \DBG::msg('So let\'s remove it...');
        $cadminIndex = new \Cx\Lib\FileSystem\File(ASCMS_DOCUMENT_ROOT . ASCMS_BACKEND_PATH . '/index.php');
        $cadminIndex->delete();
    } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
        setUpdateMsg('Die Datei \'' . ASCMS_DOCUMENT_ROOT . ASCMS_BACKEND_PATH . '/index.php\' konnte nicht gelöscht werden.');
        return false;
    }
}
/***************************************
 *
 * CALENDAR: FIX TABLE
 * only for 3.1.0
 *
 **************************************/
// fixing news container text setting which cannot be activated
if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.1.1')) {
    try {
示例#15
0
 public static function makeWritable($path)
 {
     try {
         $objFile = new \Cx\Lib\FileSystem\File($path);
         $objFile->makeWritable();
         return true;
     } catch (FileSystemException $e) {
         \DBG::msg($e->getMessage());
     }
     return false;
 }
示例#16
0
function _updateSettings()
{
    global $objUpdate, $objDatabase, $_ARRAYLANG, $_CORELANG, $_CONFIG, $arrSettings, $arrSettingsByName;
    // TODO: Unused
    //    $setVars = false;
    $arrSettings = array(3 => array('setname' => 'dnsServer', 'setvalue' => 'ns1.contrexxdns.net', 'setmodule' => 1), 4 => array('setname' => 'bannerStatus', 'setvalue' => '0', 'setmodule' => 28), 5 => array('setname' => 'spamKeywords', 'setvalue' => 'sex, viagra', 'setmodule' => 1), 11 => array('setname' => 'coreAdminName', 'setvalue' => 'Webmaster', 'setmodule' => 1), 18 => array('setname' => 'corePagingLimit', 'setvalue' => '30', 'setmodule' => 1), 19 => array('setname' => 'searchDescriptionLength', 'setvalue' => '150', 'setmodule' => 5), 23 => array('setname' => 'coreIdsStatus', 'setvalue' => 'off', 'setmodule' => 1), 24 => array('setname' => 'coreAdminEmail', 'setvalue' => '*****@*****.**', 'setmodule' => 1), 29 => array('setname' => 'contactFormEmail', 'setvalue' => '*****@*****.**', 'setmodule' => 6), 34 => array('setname' => 'sessionLifeTime', 'setvalue' => '3600', 'setmodule' => 1), 35 => array('setname' => 'lastAccessId', 'setvalue' => '1', 'setmodule' => 1), 37 => array('setname' => 'newsTeasersStatus', 'setvalue' => '0', 'setmodule' => 8), 39 => array('setname' => 'feedNewsMLStatus', 'setvalue' => '0', 'setmodule' => 22), 40 => array('setname' => 'calendarheadlines', 'setvalue' => '1', 'setmodule' => 21), 41 => array('setname' => 'calendarheadlinescount', 'setvalue' => '5', 'setmodule' => 21), 42 => array('setname' => 'blockStatus', 'setvalue' => '1', 'setmodule' => 7), 44 => array('setname' => 'calendarheadlinescat', 'setvalue' => '0', 'setmodule' => 21), 45 => array('setname' => 'calendardefaultcount', 'setvalue' => '16', 'setmodule' => 21), 48 => array('setname' => 'blockRandom', 'setvalue' => '1', 'setmodule' => 7), 49 => array('setname' => 'directoryHomeContent', 'setvalue' => '0', 'setmodule' => 12), 50 => array('setname' => 'cacheEnabled', 'setvalue' => 'off', 'setmodule' => 1), 51 => array('setname' => 'coreGlobalPageTitle', 'setvalue' => 'Contrexx Example Page', 'setmodule' => 1), 52 => array('setname' => 'cacheExpiration', 'setvalue' => '86400', 'setmodule' => 1), 53 => array('setname' => 'domainUrl', 'setvalue' => 'localhost', 'setmodule' => 1), 54 => array('setname' => 'xmlSitemapStatus', 'setvalue' => 'off', 'setmodule' => 1), 55 => array('setname' => 'systemStatus', 'setvalue' => 'on', 'setmodule' => 1), 56 => array('setname' => 'searchVisibleContentOnly', 'setvalue' => 'on', 'setmodule' => 1), 57 => array('setname' => 'protocolHttpsFrontend', 'setvalue' => 'off', 'setmodule' => 1), 58 => array('setname' => 'protocolHttpsBackend', 'setvalue' => 'off', 'setmodule' => 1), 59 => array('setname' => 'forceDomainUrl', 'setvalue' => 'off', 'setmodule' => 1), 60 => array('setname' => 'forumHomeContent', 'setvalue' => '0', 'setmodule' => 20), 62 => array('setname' => 'coreSmtpServer', 'setvalue' => '0', 'setmodule' => 1), 63 => array('setname' => 'languageDetection', 'setvalue' => 'on', 'setmodule' => 1), 64 => array('setname' => 'podcastHomeContent', 'setvalue' => '0', 'setmodule' => 35), 65 => array('setname' => 'googleMapsAPIKey', 'setvalue' => '', 'setmodule' => 1), 66 => array('setname' => 'forumTagContent', 'setvalue' => '0', 'setmodule' => 20), 68 => array('setname' => 'dataUseModule', 'setvalue' => '0', 'setmodule' => 48), 69 => array('setname' => 'frontendEditingStatus', 'setvalue' => 'off', 'setmodule' => 1), 71 => array('setname' => 'coreListProtectedPages', 'setvalue' => 'on', 'setmodule' => 1), 72 => array('setname' => 'useKnowledgePlaceholders', 'setvalue' => '0', 'setmodule' => 56), 73 => array('setname' => 'advancedUploadFrontend', 'setvalue' => 'off', 'setmodule' => 52), 74 => array('setname' => 'advancedUploadBackend', 'setvalue' => 'on', 'setmodule' => 52), 75 => array('setname' => 'installationId', 'setvalue' => '', 'setmodule' => 1), 76 => array('setname' => 'licenseKey', 'setvalue' => '', 'setmodule' => 1), 77 => array('setname' => 'contactCompany', 'setvalue' => 'Ihr Firmenname', 'setmodule' => 1), 78 => array('setname' => 'contactAddress', 'setvalue' => 'Musterstrasse 12', 'setmodule' => 1), 79 => array('setname' => 'contactZip', 'setvalue' => '3600', 'setmodule' => 1), 80 => array('setname' => 'contactPlace', 'setvalue' => 'Musterhausen', 'setmodule' => 1), 81 => array('setname' => 'contactCountry', 'setvalue' => 'Musterland', 'setmodule' => 1), 82 => array('setname' => 'contactPhone', 'setvalue' => '033 123 45 67', 'setmodule' => 1), 83 => array('setname' => 'contactFax', 'setvalue' => '033 123 45 68', 'setmodule' => 1), 84 => array('setname' => 'sessionLifeTimeRememberMe', 'setvalue' => '1209600', 'setmodule' => 1), 85 => array('setname' => 'dashboardNews', 'setvalue' => 'on', 'setmodule' => 1), 86 => array('setname' => 'dashboardStatistics', 'setvalue' => 'on', 'setmodule' => 1), 87 => array('setname' => 'timezone', 'setvalue' => 'Europe/Zurich', 'setmodule' => 1), 88 => array('setname' => 'googleAnalyticsTrackingId', 'setvalue' => '', 'setmodule' => 1), 89 => array('setname' => 'passwordComplexity', 'setvalue' => 'off', 'setmodule' => 1), 90 => array('setname' => 'licenseState', 'setvalue' => 'OK', 'setmodule' => 66), 91 => array('setname' => 'licenseValidTo', 'setvalue' => '', 'setmodule' => 66), 92 => array('setname' => 'coreCmsEdition', 'setvalue' => 'Trial', 'setmodule' => 66), 93 => array('setname' => 'licenseMessage', 'setvalue' => '', 'setmodule' => 66), 94 => array('setname' => 'licenseCreatedAt', 'setvalue' => '', 'setmodule' => 66), 95 => array('setname' => 'licenseDomains', 'setvalue' => '', 'setmodule' => 66), 96 => array('setname' => 'licenseGrayzoneMessages', 'setvalue' => '', 'setmodule' => 66), 97 => array('setname' => 'coreCmsVersion', 'setvalue' => '3.0.4', 'setmodule' => 66), 98 => array('setname' => 'coreCmsCodeName', 'setvalue' => 'Nikola Tesla', 'setmodule' => 66), 99 => array('setname' => 'coreCmsStatus', 'setvalue' => 'Stable', 'setmodule' => 66), 100 => array('setname' => 'coreCmsReleaseDate', 'setvalue' => '12.04.2013', 'setmodule' => 66), 101 => array('setname' => 'licensePartner', 'setvalue' => '', 'setmodule' => 66), 102 => array('setname' => 'licenseCustomer', 'setvalue' => '', 'setmodule' => 66), 103 => array('setname' => 'availableComponents', 'setvalue' => '', 'setmodule' => 66), 104 => array('setname' => 'upgradeUrl', 'setvalue' => 'http://license.contrexx.com/', 'setmodule' => 66), 105 => array('setname' => 'isUpgradable', 'setvalue' => 'off', 'setmodule' => 66), 106 => array('setname' => 'dashboardMessages', 'setvalue' => 'YToxOntzOjI6ImRlIjtPOjMxOiJDeFxDb3JlX01vZHVsZXNcTGljZW5zZVxNZXNzYWdlIjo2OntzOjQxOiIAQ3hcQ29yZV9Nb2R1bGVzXExpY2Vuc2VcTWVzc2FnZQBsYW5nQ29kZSI7czoyOiJkZSI7czozNzoiAEN4XENvcmVfTW9kdWxlc1xMaWNlbnNlXE1lc3NhZ2UAdGV4dCI7czo5MjoiU2llIGJlbnV0emVuIGRlbiBSZWxlYXNlIENhbmRpZGF0ZSB2b24gQ29udHJleHggMy4gS2xpY2tlbiBTaWUgaGllciB1bSBOZXVpZ2tlaXRlbiB6dSBzZWhlbiEiO3M6Mzc6IgBDeFxDb3JlX01vZHVsZXNcTGljZW5zZVxNZXNzYWdlAHR5cGUiO3M6MTA6Indhcm5pbmdib3giO3M6Mzc6IgBDeFxDb3JlX01vZHVsZXNcTGljZW5zZVxNZXNzYWdlAGxpbmsiO3M6MjE6ImluZGV4LnBocD9jbWQ9bGljZW5zZSI7czo0MzoiAEN4XENvcmVfTW9kdWxlc1xMaWNlbnNlXE1lc3NhZ2UAbGlua1RhcmdldCI7czo1OiJfc2VsZiI7czo0ODoiAEN4XENvcmVfTW9kdWxlc1xMaWNlbnNlXE1lc3NhZ2UAc2hvd0luRGFzaGJvYXJkIjtiOjE7fX0=', 'setmodule' => 66), 112 => array('setname' => 'coreCmsName', 'setvalue' => 'Contrexx', 'setmodule' => 66), 113 => array('setname' => 'useCustomizings', 'setvalue' => 'off', 'setmodule' => 1), 114 => array('setname' => 'licenseGrayzoneTime', 'setvalue' => '14', 'setmodule' => 66), 115 => array('setname' => 'licenseLockTime', 'setvalue' => '10', 'setmodule' => 66), 116 => array('setname' => 'licenseUpdateInterval', 'setvalue' => '24', 'setmodule' => 66), 117 => array('setname' => 'licenseFailedUpdate', 'setvalue' => '0', 'setmodule' => 66), 118 => array('setname' => 'licenseSuccessfulUpdate', 'setvalue' => '0', 'setmodule' => 66), 119 => array('setname' => 'cacheUserCache', 'setvalue' => 'off', 'setmodule' => 1), 120 => array('setname' => 'cacheOPCache', 'setvalue' => 'off', 'setmodule' => 1), 121 => array('setname' => 'cacheUserCacheMemcacheConfig', 'setvalue' => '{\\"ip":\\"127.0.0.1\\",\\"port\\":11211}', 'setmodule' => 1), 122 => array('setname' => 'cacheProxyCacheVarnishConfig', 'setvalue' => '{\\"ip":\\"127.0.0.1\\",\\"port\\":8080}', 'setmodule' => 1));
    $arrSettingsByName = array();
    foreach ($arrSettings as $setid => $data) {
        $arrSettingsByName[$data['setname']] = $setid;
    }
    // change googleSitemapStatus to xmlSitemapStatus
    $query = "SELECT 1 FROM `" . DBPREFIX . "settings` WHERE `setname`='googleSitemapStatus'";
    $objResult = $objDatabase->SelectLimit($query, 1);
    if ($objResult) {
        if ($objResult->RecordCount() == 1) {
            $query = "UPDATE `" . DBPREFIX . "settings` SET `setname` = 'xmlSitemapStatus' WHERE `setname` = 'googleSitemapStatus'";
            if ($objDatabase->Execute($query) === false) {
                return _databaseError($query, $objDatabase->ErrorMsg());
            }
        }
    } else {
        return _databaseError($query, $objDatabase->ErrorMsg());
    }
    try {
        //remove fileuploader setting
        \Cx\Lib\UpdateUtil::sql('DELETE FROM ' . DBPREFIX . 'settings WHERE setid=70 AND setname="fileUploaderStatus"');
    } catch (\Cx\Lib\UpdateException $e) {
        DBG::trace();
        return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
    }
    foreach ($arrSettings as $setId => $arrSetting) {
        if (!_updateSettingsTable($setId, $arrSetting)) {
            return false;
        }
    }
    $query = "UPDATE `" . DBPREFIX . "settings` SET `setmodule`=1 WHERE `setmodule`=0";
    if ($objDatabase->Execute($query) === false) {
        return _databaseError($query, $objDatabase->ErrorMsg());
    }
    //timezone (Contrexx 3.0.1)
    $arrTimezoneIdentifiers = timezone_identifiers_list();
    if (isset($_POST['timezone']) && array_key_exists($_POST['timezone'], $arrTimezoneIdentifiers)) {
        $_SESSION['contrexx_update']['update']['timezone'] = $_POST['timezone'];
    }
    if (isset($_SESSION['contrexx_update']['update']['timezone']) && array_key_exists(ContrexxUpdate::_getSessionArray($_SESSION['contrexx_update']['update']['timezone']), $arrTimezoneIdentifiers)) {
        try {
            \Cx\Lib\UpdateUtil::sql('UPDATE `' . DBPREFIX . 'settings` SET `setvalue` = "' . $arrTimezoneIdentifiers[$_SESSION['contrexx_update']['update']['timezone']] . '" WHERE `setname` = "timezone"');
            // add timezone to $_CONFIG array so it will be written in configuration.php in components/core/core.php
            $_CONFIG['timezone'] = $arrTimezoneIdentifiers[$_SESSION['contrexx_update']['update']['timezone']];
        } catch (\Cx\Lib\UpdateException $e) {
            return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
        }
    } else {
        $selected = -1;
        if (($defaultTimezoneId = array_search(@date_default_timezone_get(), $arrTimezoneIdentifiers)) && !empty($defaultTimezoneId)) {
            $selected = $defaultTimezoneId;
        }
        $options = '<option value="-1"' . ($selected == -1 ? ' selected="selected"' : '') . '>' . $_CORELANG['TXT_PLEASE_SELECT'] . '</option>';
        foreach ($arrTimezoneIdentifiers as $id => $name) {
            $dateTimeZone = new DateTimeZone($name);
            $dateTime = new DateTime('now', $dateTimeZone);
            $timeOffset = $dateTimeZone->getOffset($dateTime);
            $sign = $timeOffset < 0 ? '-' : '+';
            $gmt = 'GMT ' . $sign . gmdate('g:i', $timeOffset);
            $options .= '<option value="' . $id . '"' . ($selected == $id ? ' selected="selected"' : '') . '>' . $name . ' (' . $gmt . ')' . '</option>';
        }
        setUpdateMsg($_CORELANG['TXT_TIMEZONE'], 'title');
        setUpdateMsg($_CORELANG['TXT_TIMEZONE_INTRODUCTION'] . ' <select name="timezone">' . $options . '</select>', 'msg');
        setUpdateMsg('<input type="submit" value="' . $_CORELANG['TXT_UPDATE_NEXT'] . '" name="updateNext" /><input type="hidden" name="processUpdate" id="processUpdate" />', 'button');
        return false;
    }
    // write settings
    $strFooter = '';
    $arrModules = '';
    \Cx\Lib\FileSystem\FileSystem::makeWritable(ASCMS_DOCUMENT_ROOT . '/config/');
    if (!file_exists(ASCMS_DOCUMENT_ROOT . '/config/settings.php')) {
        if (!touch(ASCMS_DOCUMENT_ROOT . '/config/settings.php')) {
            setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_CREATE_SETTINGS_FILE'], ASCMS_DOCUMENT_ROOT . '/config/settings.php'));
            setUpdateMsg(sprintf($_ARRAYLANG['TXT_SET_WRITE_PERMISSON_TO_DIR'], ASCMS_DOCUMENT_ROOT . '/config/', $_CORELANG['TXT_UPDATE_TRY_AGAIN']), 'msg');
            return false;
        }
    }
    \Cx\Lib\FileSystem\FileSystem::makeWritable(ASCMS_DOCUMENT_ROOT . '/config/settings.php');
    if (is_writable(ASCMS_DOCUMENT_ROOT . '/config/settings.php')) {
        try {
            $objFile = new \Cx\Lib\FileSystem\File(ASCMS_DOCUMENT_ROOT . '/config/settings.php');
            //Header & Footer
            $strHeader = "<?php\n";
            $strHeader .= "/**\n";
            $strHeader .= "* This file is generated by the \"settings\"-menu in your CMS.\n";
            $strHeader .= "* Do not try to edit it manually!\n";
            $strHeader .= "*/\n\n";
            $strFooter .= "?>";
            //Get module-names
            $objResult = $objDatabase->Execute('SELECT    id, name FROM ' . DBPREFIX . 'modules');
            if ($objResult->RecordCount() > 0) {
                while (!$objResult->EOF) {
                    $arrModules[$objResult->fields['id']] = $objResult->fields['name'];
                    $objResult->MoveNext();
                }
            }
            //Get values
            $objResult = $objDatabase->Execute('SELECT        setname,
                                                            setmodule,
                                                            setvalue
                                                FROM        ' . DBPREFIX . 'settings
                                                ORDER BY    setmodule ASC,
                                                            setname ASC
                                            ');
            $intMaxLen = 0;
            $arrValues = array();
            while ($objResult && !$objResult->EOF) {
                $intMaxLen = strlen($objResult->fields['setname']) > $intMaxLen ? strlen($objResult->fields['setname']) : $intMaxLen;
                $arrValues[$objResult->fields['setmodule']][$objResult->fields['setname']] = $objResult->fields['setvalue'];
                $objResult->MoveNext();
            }
            $intMaxLen += strlen('$_CONFIG[\'\']') + 1;
            //needed for formatted output
            $fileContent = $strHeader;
            foreach ($arrValues as $intModule => $arrInner) {
                $fileContent .= "/**\n";
                $fileContent .= "* -------------------------------------------------------------------------\n";
                if (isset($arrModules[$intModule])) {
                    $fileContent .= "* " . ucfirst($arrModules[$intModule]) . "\n";
                } else {
                    $fileContent .= "* " . $intModule . "\n";
                }
                $fileContent .= "* -------------------------------------------------------------------------\n";
                $fileContent .= "*/\n";
                foreach ($arrInner as $strName => $strValue) {
                    $fileContent .= sprintf("%-" . $intMaxLen . "s", '$_CONFIG[\'' . $strName . '\']');
                    $fileContent .= "= ";
                    $fileContent .= (is_numeric($strValue) ? $strValue : '"' . $strValue . '"') . ";\n";
                }
                $fileContent .= "\n";
            }
            $fileContent .= $strFooter;
            $objFile->write($fileContent);
        } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
        }
    } else {
        setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_WRITE_SETTINGS_FILE'], ASCMS_DOCUMENT_ROOT . '/config/settings.php'));
        setUpdateMsg(sprintf($_ARRAYLANG['TXT_SET_WRITE_PERMISSON_TO_FILE'], ASCMS_DOCUMENT_ROOT . '/config/settings.php', $_CORELANG['TXT_UPDATE_TRY_AGAIN']), 'msg');
        return false;
    }
    $query = "\n    ALTER TABLE " . DBPREFIX . "settings\n    CHANGE COLUMN setid setid integer(6) UNSIGNED NOT NULL auto_increment;\n    ";
    if (!$objDatabase->Execute($query)) {
        return _databaseError($query, $objDatabase->ErrorMsg());
    }
    try {
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'settings_image', array('id' => array('type' => 'INT(10)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'name' => array('type' => 'VARCHAR(50)', 'after' => 'id'), 'value' => array('type' => 'text', 'after' => 'name')));
    } catch (\Cx\Lib\UpdateException $e) {
        return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
    }
    if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.0.3')) {
        try {
            \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "settings_image` (`name`, `value`) VALUES (?, ?)", array('image_cut_width', '500'));
            \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "settings_image` (`name`, `value`) VALUES (?, ?)", array('image_cut_height', '500'));
            \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "settings_image` (`name`, `value`) VALUES (?, ?)", array('image_scale_width', '800'));
            \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "settings_image` (`name`, `value`) VALUES (?, ?)", array('image_scale_height', '800'));
            \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "settings_image` (`name`, `value`) VALUES (?, ?)", array('image_compression', '100'));
        } catch (\Cx\Lib\UpdateException $e) {
            return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
        }
    }
    return true;
}
 /**
  * Clears a cache page
  * @param string $urlPattern Drop all pages that match the pattern, for exact format, make educated guesses
  * @param string $domain Domain name to drop cache page of
  * @param int $port Port to drop cache page of
  */
 protected function clearCachePageForDomainAndPort($urlPattern, $domain, $port)
 {
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $strCachePath = $cx->getWebsiteCachePath() . '/';
     $glob = null;
     if ($urlPattern == '*') {
         $glob = $strCachePath . '*';
     }
     if (!$glob) {
         $searchParts = $cx->getComponent('Cache')->getCacheFileNameSearchPartsFromUrl($urlPattern);
         $glob = $strCachePath . $cx->getComponent('Cache')->getCacheFileNameFromUrl($urlPattern, false) . '*' . implode('', $searchParts) . '*';
     }
     if ($glob !== null) {
         $fileNames = glob($glob);
         foreach ($fileNames as $fileName) {
             if (!preg_match('#/[0-9a-f]{32}((_[plutgc][a-z0-9]+)+)?$#', $fileName)) {
                 continue;
             }
             try {
                 $file = new \Cx\Lib\FileSystem\File($fileName);
                 $file->delete();
             } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             }
         }
         return;
     }
     $cacheFile = $cx->getComponent('Cache')->getCacheFileNameFromUrl($urlPattern);
     try {
         $file = new \Cx\Lib\FileSystem\File($strCachePath . $cacheFile);
         $file->delete();
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
     }
     // make sure HTTP and HTTPS files are dropped
     if (substr($urlPattern, 0, 5) == 'https') {
         $urlPattern = 'http' . substr($urlPattern, 5);
     } else {
         if (substr($urlPattern, 0, 4) == 'http') {
             $urlPattern = 'https' . substr($urlPattern, 4);
         }
     }
     $cacheFile = md5($urlPattern);
     try {
         $file = new \Cx\Lib\FileSystem\File($strCachePath . $cacheFile);
         $file->delete();
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
     }
 }
示例#18
0
function contentManagerUpdates()
{
    //Database migration
    try {
        //update module name
        \Cx\Lib\UpdateUtil::sql("INSERT INTO `" . DBPREFIX . "modules` (`id`, `name`, `distributor`, `description_variable`, `status`, `is_required`, `is_core`, `is_active`, `is_licensed`) VALUES ('72', 'ContentManager', 'DEV', 'TXT_CONTENTMANAGER_MODULE_DESCRIPTION', 'n', '0', '1', '1', '1')");
        //update navigation url
        \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "backend_areas` SET `uri` = 'index.php?cmd=ContentManager&act=new' WHERE `area_id` = 5");
        \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "backend_areas` SET `uri` = 'index.php?cmd=ContentManager' WHERE `area_id` = 6");
        \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "backend_areas` SET `uri` = 'index.php?cmd=ContentManager' WHERE `area_id` = 161");
        //Alter the content_page table structure
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'content_page', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'node_id' => array('type' => 'INT(11)', 'notnull' => false, 'after' => 'id'), 'nodeIdShadowed' => array('type' => 'INT(11)', 'notnull' => false, 'after' => 'node_id'), 'lang' => array('type' => 'INT(11)', 'after' => 'nodeIdShadowed'), 'type' => array('type' => 'VARCHAR(16)', 'after' => 'lang'), 'caching' => array('type' => 'TINYINT(1)', 'after' => 'type'), 'updatedAt' => array('type' => 'timestamp', 'after' => 'caching'), 'updatedBy' => array('type' => 'CHAR(40)', 'after' => 'updatedAt'), 'title' => array('type' => 'VARCHAR(255)', 'after' => 'updatedBy'), 'linkTarget' => array('type' => 'VARCHAR(16)', 'notnull' => false, 'after' => 'title'), 'contentTitle' => array('type' => 'VARCHAR(255)', 'after' => 'linkTarget'), 'slug' => array('type' => 'VARCHAR(255)', 'after' => 'contentTitle'), 'content' => array('type' => 'longtext', 'after' => 'slug'), 'sourceMode' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'content'), 'customContent' => array('type' => 'VARCHAR(64)', 'notnull' => false, 'after' => 'sourceMode'), 'useCustomContentForAllChannels' => array('type' => 'INT(2)', 'notnull' => false, 'after' => 'customContent'), 'applicationTemplate' => array('type' => 'VARCHAR(100)', 'notnull' => false, 'after' => 'useCustomContentForAllChannels'), 'useCustomApplicationTemplateForAllChannels' => array('type' => 'TINYINT(2)', 'after' => 'applicationTemplate'), 'cssName' => array('type' => 'VARCHAR(255)', 'notnull' => false, 'after' => 'useCustomApplicationTemplateForAllChannels'), 'cssNavName' => array('type' => 'VARCHAR(255)', 'notnull' => false, 'after' => 'cssName'), 'skin' => array('type' => 'INT(11)', 'notnull' => false, 'after' => 'cssNavName'), 'useSkinForAllChannels' => array('type' => 'INT(2)', 'notnull' => false, 'after' => 'skin'), 'metatitle' => array('type' => 'VARCHAR(255)', 'notnull' => false, 'after' => 'useSkinForAllChannels'), 'metadesc' => array('type' => 'text', 'after' => 'metatitle'), 'metakeys' => array('type' => 'text', 'after' => 'metadesc'), 'metarobots' => array('type' => 'VARCHAR(7)', 'notnull' => false, 'after' => 'metakeys'), 'start' => array('type' => 'timestamp', 'after' => 'metarobots'), 'end' => array('type' => 'timestamp', 'after' => 'start'), 'editingStatus' => array('type' => 'VARCHAR(16)', 'after' => 'end'), 'protection' => array('type' => 'INT(11)', 'after' => 'editingStatus'), 'frontendAccessId' => array('type' => 'INT(11)', 'after' => 'protection'), 'backendAccessId' => array('type' => 'INT(11)', 'after' => 'frontendAccessId'), 'display' => array('type' => 'TINYINT(1)', 'after' => 'backendAccessId'), 'active' => array('type' => 'TINYINT(1)', 'after' => 'display'), 'target' => array('type' => 'VARCHAR(255)', 'notnull' => false, 'after' => 'active'), 'module' => array('type' => 'VARCHAR(255)', 'notnull' => false, 'after' => 'target'), 'cmd' => array('type' => 'VARCHAR(50)', 'notnull' => true, 'default' => '', 'after' => 'module')), array('node_id' => array('fields' => array('node_id', 'lang'), 'type' => 'UNIQUE'), 'IDX_D8E86F54460D9FD7' => array('fields' => array('node_id'))), 'InnoDB', '', array('node_id' => array('table' => DBPREFIX . 'content_node', 'column' => 'id', 'onDelete' => 'SET NULL', 'onUpdate' => 'NO ACTION')));
    } catch (\Cx\Lib\UpdateException $e) {
        return "Error: {$e->sql}";
    }
    $virtualComponents = array('Agb', 'Ids', 'Imprint', 'Privacy');
    //migrating custom application template
    $pageRepo = \Env::get('em')->getRepository('Cx\\Core\\ContentManager\\Model\\Entity\\Page');
    $themeRepo = new \Cx\Core\View\Model\Repository\ThemeRepository();
    $pages = $pageRepo->findBy(array('type' => \Cx\Core\ContentManager\Model\Entity\Page::TYPE_APPLICATION));
    foreach ($pages as $page) {
        try {
            //virtual components do not migrating custom application template
            if (in_array(ucfirst($page->getModule()), $virtualComponents)) {
                continue;
            }
            $designTemplateName = $page->getSkin() ? $themeRepo->findById($page->getSkin())->getFoldername() : $themeRepo->getDefaultTheme()->getFoldername();
            $cmd = !$page->getCmd() ? 'Default' : ucfirst($page->getCmd());
            $moduleFolderName = contrexx_isCoreModule($page->getModule()) ? 'core_modules' : 'modules';
            $themesPath = ASCMS_THEMES_PATH . '/' . $designTemplateName;
            //check common module or core_module folder exists
            if (!file_exists($themesPath . '/' . $moduleFolderName)) {
                \Cx\Lib\FileSystem\FileSystem::make_folder($themesPath . '/' . $moduleFolderName);
            }
            //check module's folder exists
            if (!file_exists($themesPath . '/' . $moduleFolderName . '/' . $page->getModule())) {
                \Cx\Lib\FileSystem\FileSystem::make_folder($themesPath . '/' . $moduleFolderName . '/' . $page->getModule());
            }
            //check module's template folder exists
            if (!file_exists($themesPath . '/' . $moduleFolderName . '/' . $page->getModule() . '/Template')) {
                \Cx\Lib\FileSystem\FileSystem::make_folder($themesPath . '/' . $moduleFolderName . '/' . $page->getModule() . '/Template');
            }
            //check module's Frontend folder exists
            if (!file_exists($themesPath . '/' . $moduleFolderName . '/' . $page->getModule() . '/Template/Frontend')) {
                \Cx\Lib\FileSystem\FileSystem::make_folder($themesPath . '/' . $moduleFolderName . '/' . $page->getModule() . '/Template/Frontend');
            }
            $targetPath = $themesPath . '/' . $moduleFolderName . '/' . $page->getModule() . '/Template/Frontend';
            $applicationTemplateName = getFilename($targetPath, $cmd . '_custom_' . FWLanguage::getLanguageCodeById($page->getLang()));
            if (file_exists($targetPath)) {
                //create a application template file
                $file = new \Cx\Lib\FileSystem\File($targetPath . '/' . $applicationTemplateName);
                $file->write($page->getContent());
            }
            //update application template
            $page->setContent('{APPLICATION_DATA}');
            $page->setApplicationTemplate($applicationTemplateName);
            $page->setUseCustomApplicationTemplateForAllChannels(1);
            \Env::get('em')->persist($page);
            \Env::get('em')->flush();
        } catch (\Exception $e) {
            throw new \Exception('Error :' . $e);
        }
    }
    return 'Application template migrated successfully.';
}
 protected function fetchResponse($license, $_CONFIG, $forceTemplate, $_CORELANG)
 {
     $v = preg_split('#\\.#', $_CONFIG['coreCmsVersion']);
     $e = $_CONFIG['coreCmsEdition'];
     $version = current($v);
     unset($v[key($v)]);
     foreach ($v as $part) {
         $version *= 100;
         $version += $part;
     }
     $srvUri = 'updatesrv1.contrexx.com';
     $srvPath = '/';
     $data = array('installationId' => $license->getInstallationId(), 'licenseKey' => $license->getLicenseKey(), 'edition' => $license->getEditionName(), 'version' => $this->coreCmsVersion, 'versionstate' => $this->coreCmsStatus, 'domainName' => $this->domainUrl, 'sendTemplate' => $forceTemplate);
     if (true) {
         try {
             $objFile = new \Cx\Lib\FileSystem\File(ASCMS_INSTANCE_PATH . ASCMS_INSTANCE_OFFSET . '/config/License.lic');
             $rawData = $objFile->getData();
             $response = json_decode(base64_decode($rawData));
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             $license->setState(License::LICENSE_ERROR);
             $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
             $license->check();
             throw $e;
         }
         return $response;
     }
     $a = $_SERVER['REMOTE_ADDR'];
     $r = 'http://';
     if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
         $r = 'https://';
     }
     $r .= $_SERVER['SERVER_NAME'] . ASCMS_INSTANCE_OFFSET;
     $request = new \HTTP_Request2('http://' . $srvUri . $srvPath . '?v=' . $version, \HTTP_Request2::METHOD_POST);
     $request->setHeader('X-Edition', $e);
     $request->setHeader('X-Remote-Addr', $a);
     $request->setHeader('Referer', $r);
     $jd = new \Cx\Core\Json\JsonData();
     $request->addPostParameter('data', $jd->json($data));
     try {
         $objResponse = $request->send();
         if ($objResponse->getStatus() !== 200) {
             $license->setState(License::LICENSE_ERROR);
             $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
             $license->check();
             return null;
         } else {
             \DBG::dump($objResponse->getBody());
             $response = json_decode($objResponse->getBody());
         }
     } catch (\HTTP_Request2_Exception $objException) {
         $license->setState(License::LICENSE_ERROR);
         $license->setGrayzoneMessages(array(\FWLanguage::getLanguageCodeById(LANG_ID) => new Message(\FWLanguage::getLanguageCodeById(LANG_ID), $_CORELANG['TXT_LICENSE_COMMUNICATION_ERROR'])));
         $license->check();
         throw $objException;
     }
     return $response;
 }
示例#20
0
 /**
  * Should be called whenever there's a problem with the settings
  *
  * Tries to fix or recreate the settings.
  * @return  boolean             False, always.
  * 
  */
 function errorHandler()
 {
     try {
         $file = new \Cx\Lib\FileSystem\File(\Env::get('cx')->getWebsiteConfigPath() . '/' . $this->section . '.yml');
         $file->touch();
         return false;
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::msg($e->getMessage());
     }
 }
示例#21
0
 /**
  * End caching functions. Check for a sessionId: if not set, write pagecontent to a file.
  */
 public function endContrexxCaching($page)
 {
     if (!$this->boolIsEnabled) {
         return null;
     }
     if (session_id() != '' && \FWUser::getFWUserObject()->objUser->login()) {
         return null;
     }
     if (!$page->getCaching()) {
         return null;
     }
     $strCacheContents = ob_get_contents();
     ob_end_flush();
     $handleFile = $this->strCachePath . $this->strCacheFilename . "_" . $page->getId();
     $File = new \Cx\Lib\FileSystem\File($handleFile);
     $File->write($strCacheContents);
 }
 private function testLoad($path, $name)
 {
     if (!file_exists($path) || !$this->checkClassExistsInFile($name, $path)) {
         return false;
     }
     $path = substr($path, strlen($this->cx->getCodeBaseDocumentRootPath()));
     if (!$this->loadClass($path, $name)) {
         return false;
     }
     try {
         $objFile = new \Cx\Lib\FileSystem\File($this->userClassCacheFile);
         if (!file_exists($this->userClassCacheFile)) {
             $objFile->touch();
         }
         $cacheArr = unserialize(file_get_contents($this->classLoader->getFilePath($this->userClassCacheFile)));
         $cacheArr[$name] = $path;
         $objFile->write(serialize($cacheArr));
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         \DBG::msg($e->getMessage());
     }
     return true;
 }
示例#23
0
 /**
  * Saves the new image wherever you want
  * @todo    In case the PHP script has no write access to the location set by $this->newImageFile,
  *          the image shall be sent to the output buffer and then be put into the new file
  *          location using the FileSystemFile object.
  * @access  public
  * @param   string    $file             The path for the image file to be written.
  * @param   booelan   $forceOverwrite   Force overwriting existing files if true.
  * @return  boolean                     True on success, false otherwise.
  */
 public function saveNewImage($file, $forceOverwrite = false)
 {
     // TODO: Add some sort of diagnostics (Message) here and elsewhere in this class
     if (!$this->imageCheck) {
         return false;
     }
     if (empty($this->newImage)) {
         return false;
     }
     if (file_exists($file)) {
         if (!$forceOverwrite) {
             return false;
         }
         \Cx\Lib\FileSystem\FileSystem::makeWritable($file);
     } else {
         try {
             $objFile = new \Cx\Lib\FileSystem\File($file);
             $objFile->touch();
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             \DBG::msg($e->getMessage());
         }
     }
     // TODO: Unfortunately, the functions imagegif(), imagejpeg() and imagepng() can't use the Contrexx FileSystem wrapper,
     //       therefore we need to set the global write access image files.
     //       This issue might be solved by using the output-buffer and write the image manually afterwards.
     //
     //       IMPORTANT: In case something went wrong (see bug #1441) and the path $strPathNew.$strFileNew refers to a directory
     //       we must abort the operation here, otherwise we would remove the execution flag on a directory, which would
     //       cause to remove any browsing access to the directory.
     if (is_dir($file)) {
         return false;
     }
     \Cx\Lib\FileSystem\FileSystem::chmod($file, 0666);
     //\Cx\Lib\FileSystem\FileSystem::CHMOD_FILE);
     $this->newImageFile = $file;
     if ($this->newImageType == self::IMG_TYPE_PNG) {
         $this->setTransparency();
     }
     switch ($this->newImageType) {
         case self::IMG_TYPE_GIF:
             $function = 'imagegif';
             if (!function_exists($function)) {
                 $function = 'imagejpeg';
             }
             break;
         case self::IMG_TYPE_JPEG:
             $function = 'imagejpeg';
             break;
         case self::IMG_TYPE_PNG:
             // make a jpeg thumbnail, too
             $function = 'imagepng';
             break;
         default:
             return false;
     }
     // Only adjust quality, if it is set.
     if ($this->newImageQuality != '') {
         $function($this->newImage, $this->newImageFile, $this->getQuality());
     } else {
         $function($this->newImage, $this->newImageFile);
     }
     return true;
 }
 /**
  * Get update websiteDetailsFromYml
  * 
  * @param string $file yml file name
  * 
  * @return array website details
  */
 public function getUpdateWebsiteDetailsFromYml($file)
 {
     if (!file_exists($file)) {
         return;
     }
     $objFile = new \Cx\Lib\FileSystem\File($file);
     $yaml = new \Symfony\Component\Yaml\Yaml();
     return $yaml->load($objFile->getData());
 }
示例#25
0
 /**
  * Write feed
  *
  * Writes the rss feed.
  *
  * @return boolean
  */
 function write()
 {
     global $_CORELANG;
     if (!$this->_create()) {
         return false;
     }
     try {
         $objFile = new \Cx\Lib\FileSystem\File($this->xmlDocumentPath);
         $objFile->write(preg_replace('/\\f/', '', $this->xmlDocument));
     } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
         if (file_exists($this->xmlDocumentPath)) {
             array_push($this->arrErrorMsg, sprintf($_CORELANG['TXT_UNABLE_TO_WRITE_TO_FILE'], $this->xmlDocumentPath));
         } else {
             array_push($this->arrErrorMsg, sprintf($_CORELANG['TXT_UNABLE_TO_CREATE_FILE'], $this->xmlDocumentPath));
         }
         return false;
     }
     return true;
 }
示例#26
0
 protected function moveModel($sourceFolder, $destinationFolder, $force = false)
 {
     $sourceDirectory = new \RecursiveDirectoryIterator($sourceFolder);
     $sourceDirectoryIterator = new \RecursiveIteratorIterator($sourceDirectory);
     $sourceDirectoryRegexIterator = new \RegexIterator($sourceDirectoryIterator, '/^.+\\.php$/i', \RegexIterator::GET_MATCH);
     $retVal = true;
     // foreach model class
     foreach ($sourceDirectoryRegexIterator as $sourceFile) {
         // move to correct location and add .class ending if necessary
         $sourceFile = current($sourceFile);
         $sourceFile = str_replace('\\', '/', $sourceFile);
         $parts = explode('/Cx/', $sourceFile);
         $destinationFile = $destinationFolder . '/' . end($parts);
         $destinationFile = preg_replace_callback('#(' . $destinationFolder . '/)(Core(?:_Modules)?|Modules)#', function ($matches) {
             return $matches[1] . strtolower($matches[2]);
         }, $destinationFile);
         $destinationFile = preg_replace('/(?!\\.class)\\.php$/', '.class.php', $destinationFile);
         if (!$force && file_exists($destinationFile)) {
             $retVal = false;
             continue;
         }
         try {
             $objFile = new \Cx\Lib\FileSystem\File($sourceFile);
             $objFile->move($destinationFile, $force);
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             throw $e;
         }
         // if the moved file is an entity class
         if (strpos($destinationFile, '/Model/Entity/')) {
             $contents = file_get_contents($destinationFile);
             // and there is no extends statement yet
             $regex = '/(class\\s*(:?[a-zA-Z0-9_]*))\\s*\\{/m';
             if (!preg_match($regex, $contents)) {
                 return $retVal;
             }
             // add extends statement for base entity
             $contents = preg_replace($regex, '$1 extends \\Cx\\Model\\Base\\EntityBase {', $contents);
             file_put_contents($destinationFile, $contents);
         }
     }
     return $retVal;
 }
示例#27
0
 /**
  * Load the component data from component.yml file
  * 
  * @param \Cx\Core\View\Model\Entity\Theme $theme
  */
 public function loadComponentData(\Cx\Core\View\Model\Entity\Theme &$theme)
 {
     $websiteFilePath = \Env::get('cx')->getWebsiteThemesPath() . '/' . $theme->getFoldername() . \Cx\Core\View\Model\Entity\Theme::THEME_COMPONENT_FILE;
     $codeBaseFilePath = \Env::get('cx')->getCodeBaseThemesPath() . '/' . $theme->getFoldername() . \Cx\Core\View\Model\Entity\Theme::THEME_COMPONENT_FILE;
     $filePath = file_exists($websiteFilePath) ? $websiteFilePath : (file_exists($codeBaseFilePath) ? $codeBaseFilePath : '');
     if ($filePath) {
         try {
             $objYaml = new \Symfony\Component\Yaml\Yaml();
             $objFile = new \Cx\Lib\FileSystem\File($filePath);
             $themeInformation = $objYaml->load($objFile->getData());
             $theme->setComponentData($themeInformation['DlcInfo']);
         } catch (\Exception $e) {
             \DBG::log($e->getMessage());
         }
     }
 }
示例#28
0
 /**
  * Process upload form
  *
  * @global     array    $_ARRAYLANG
  * @return     boolean  true if file uplod successfully and false if it failed
  */
 private function processFormUpload()
 {
     global $_ARRAYLANG;
     $objSession = \cmsSession::getInstance();
     $uploaderId = isset($_POST['media_upload_file']) ? contrexx_input2raw($_POST['media_upload_file']) : 0;
     if (empty($uploaderId)) {
         return false;
     }
     $tempPath = $objSession->getTempPath() . '/' . contrexx_input2raw($uploaderId);
     if (!\Cx\Lib\FileSystem\FileSystem::exists($tempPath)) {
         return false;
     }
     $errorMsg = array();
     foreach (glob($tempPath . '/*') as $file) {
         $i = 0;
         $fileName = basename($file);
         $path = $tempPath . '/' . $fileName;
         $file = $this->path . $fileName;
         $arrFile = pathinfo($file);
         while (file_exists($file)) {
             $suffix = '-' . (time() + ++$i);
             $file = $this->path . $arrFile['filename'] . $suffix . '.' . $arrFile['extension'];
         }
         if (!\FWValidator::is_file_ending_harmless($path)) {
             $errorMsg[] = sprintf($_ARRAYLANG['TXT_MEDIA_FILE_EXTENSION_NOT_ALLOWED'], htmlentities($fileName, ENT_QUOTES, CONTREXX_CHARSET));
             continue;
         }
         try {
             $objFile = new \Cx\Lib\FileSystem\File($path);
             $objFile->move($file, false);
             $fileObj = new \File();
             $fileObj->setChmod($this->path, $this->webPath, basename($file));
         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
             \DBG::msg($e->getMessage());
             $errorMsg[] = sprintf($_ARRAYLANG['TXT_MEDIA_FILE_UPLOAD_FAILED'], htmlentities($fileName, ENT_QUOTES, CONTREXX_CHARSET));
         }
     }
     if (!empty($errorMsg)) {
         $this->_strErrorMessage = explode('<br>', $errorMsg);
         return false;
     }
     $this->_strOkMessage = $_ARRAYLANG['TXT_MEDIA_FILE_UPLOADED_SUCESSFULLY'];
     return true;
 }
示例#29
0
 /**
  * Handle uploads
  * @see Contact::_uploadFilesLegacy()
  * @param array $arrFields
  * @param boolean move should the files be moved or
  *                do we just want an array of filenames?
  *                defaults to false. no effect in legacy mode.
  * @return array A list of files that have been stored successfully in the system
  */
 protected function _uploadFiles($arrFields, $move = false)
 {
     /* the field unique_id has been introduced with the new uploader.
      * it helps us to tell whether we're handling an form generated
      * before the new uploader using the classic input fields or
      * if we have to treat the files already uploaded by the uploader.
      */
     if ($this->legacyMode) {
         //legacy function for old uploader
         return $this->_uploadFilesLegacy($arrFields);
     } else {
         //new uploader used
         if (!$this->hasFileField) {
             //nothing to do for us, no files
             return array();
         }
         $arrFiles = array();
         //we'll collect name => path of all files here and return this
         $documentRootPath = \Env::get('cx')->getWebsiteDocumentRootPath();
         foreach ($arrFields as $fieldId => $arrField) {
             // skip non-upload fields
             if (!in_array($arrField['type'], array('file', 'multi_file'))) {
                 continue;
             }
             $tup = self::getTemporaryUploadPath($this->submissionId, $fieldId);
             $tmpUploadDir = $tup[1] . '/' . $tup[2] . '/';
             //all the files uploaded are in here
             $depositionTarget = "";
             //target folder
             //on the first call, _uploadFiles is called with move=false.
             //this is done in order to get an array of the moved files' names, but
             //the files are left in place.
             //the second call is done with move=true - here we finally move the
             //files.
             //
             //the target folder is created in the first call, because if we can't
             //create the folder, the target path is left pointing at the path
             //specified by $arrSettings['fileUploadDepositionPath'].
             //
             //to remember the target folder for the second call, it is stored in
             //$this->depositionTarget.
             if (!$move) {
                 //first call - create folder
                 //determine where form uploads are stored
                 $arrSettings = $this->getSettings();
                 $depositionTarget = $arrSettings['fileUploadDepositionPath'] . '/';
                 //find an unique folder name for the uploaded files
                 $folderName = date("Ymd") . '_' . $fieldId;
                 $suffix = "";
                 if (file_exists($documentRootPath . $depositionTarget . $folderName)) {
                     $suffix = 1;
                     while (file_exists($documentRootPath . $depositionTarget . $folderName . '-' . $suffix)) {
                         $suffix++;
                     }
                     $suffix = '-' . $suffix;
                 }
                 $folderName .= $suffix;
                 //try to make the folder and change target accordingly on success
                 if (\Cx\Lib\FileSystem\FileSystem::make_folder($documentRootPath . $depositionTarget . $folderName)) {
                     \Cx\Lib\FileSystem\FileSystem::makeWritable($documentRootPath . $depositionTarget . $folderName);
                     $depositionTarget .= $folderName . '/';
                 }
                 $this->depositionTarget[$fieldId] = $depositionTarget;
             } else {
                 $depositionTarget = $this->depositionTarget[$fieldId];
             }
             //move all files
             if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpUploadDir)) {
                 throw new \Cx\Core_Modules\Contact\Controller\ContactException("could not find temporary upload directory '{$tmpUploadDir}'");
             }
             $h = opendir(\Env::get('cx')->getWebsitePath() . $tmpUploadDir);
             while (false !== ($f = readdir($h))) {
                 if ($f != '..' && $f != '.') {
                     //do not overwrite existing files.
                     $prefix = '';
                     while (file_exists($documentRootPath . $depositionTarget . $prefix . $f)) {
                         if (empty($prefix)) {
                             $prefix = 0;
                         }
                         $prefix++;
                     }
                     if ($move) {
                         // move file
                         try {
                             $objFile = new \Cx\Lib\FileSystem\File($tmpUploadDir . $f);
                             $objFile->move($documentRootPath . $depositionTarget . $prefix . $f, false);
                         } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
                             \DBG::msg($e->getMessage());
                         }
                     }
                     $arrFiles[$fieldId][] = array('name' => $f, 'path' => $depositionTarget . $prefix . $f);
                 }
             }
         }
         //cleanup
         //TODO: this does not work for certain reloads - add cleanup routine
         //@rmdir($tmpUploadDir);
         return $arrFiles;
     }
 }
示例#30
0
 /**
  * the upload is finished
  * rewrite the names
  * write the uploaded files to the database
  *
  * @param string     $tempPath    the temporary file path
  * @param string     $tempWebPath the temporary file path which is accessable by web browser
  * @param array      $data        the data which are attached by uploader init method
  * @param integer    $uploadId    the upload id
  * @param array      $fileInfos   the file infos 
  * 
  * @return array the target paths
  */
 public static function notesUploadFinished($tempPath, $tempWebPath, $data, $uploadId, $fileInfos, $response)
 {
     global $objDatabase, $objFWUser;
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $depositionTarget = $cx->getWebsiteImagesCrmPath() . '/';
     //target folder
     $h = opendir($tempPath);
     if ($h) {
         while (false != ($file = readdir($h))) {
             $info = pathinfo($file);
             //skip . and ..
             if ($file == '.' || $file == '..') {
                 continue;
             }
             if ($file != '..' && $file != '.') {
                 //do not overwrite existing files.
                 $prefix = '';
                 while (file_exists($depositionTarget . $prefix . $file)) {
                     if (empty($prefix)) {
                         $prefix = 0;
                     }
                     $prefix++;
                 }
                 // move file
                 try {
                     $objFile = new \Cx\Lib\FileSystem\File($tempPath . '/' . $file);
                     $objFile->copy($depositionTarget . $prefix . $file, false);
                     // create thumbnail
                     if (empty($objImage)) {
                         $objImage = new \ImageManager();
                     }
                     $imageName = trim($prefix . $file);
                     $objImage->_createThumbWhq($cx->getWebsiteImagesCrmPath() . '/', $cx->getWebsiteImagesCrmWebPath() . '/', $imageName, 16, 16, 90, '_16X16.thumb');
                     $_SESSION['importFilename'] = $imageName;
                 } catch (\Cx\Lib\FileSystem\FileSystemException $e) {
                     \DBG::msg($e->getMessage());
                 }
             }
             $arrFiles[] = $file;
         }
         closedir($h);
     }
     // return web- and filesystem path. files will be moved there.
     return array($tempPath, $tempWebPath);
 }