/** * Load your component. * * @param \Cx\Core\ContentManager\Model\Entity\Page $page The resolved page */ public function load(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $objTemplate, $sessionObj; switch ($this->cx->getMode()) { case \Cx\Core\Core\Controller\Cx::MODE_FRONTEND: if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $objLogin = new \Cx\Core_Modules\Login\Controller\Login(\Env::get('cx')->getPage()->getContent()); $pageTitle = \Env::get('cx')->getPage()->getTitle(); $pageMetaTitle = \Env::get('cx')->getPage()->getMetatitle(); \Env::get('cx')->getPage()->setContent($objLogin->getContent($pageMetaTitle, $pageTitle)); break; case \Cx\Core\Core\Controller\Cx::MODE_BACKEND: if (\FWUser::getFWUserObject()->objUser->login(true)) { \Cx\Core\Csrf\Controller\Csrf::header('location: index.php'); } $this->cx->getTemplate()->addBlockfile('CONTENT_OUTPUT', 'content_master', 'LegacyContentMaster.html'); $objTemplate = $this->cx->getTemplate(); $objLoginManager = new \Cx\Core_Modules\Login\Controller\LoginManager(); $objLoginManager->getPage(); break; default: break; } }
/** * Do something before resolving is done * * @param \Cx\Core\Routing\Url $request The URL object for this request */ public function preResolve(\Cx\Core\Routing\Url $request) { global $sessionObj; if (\Cx\Core\Core\Controller\Cx::instanciate()->getMode() == \Cx\Core\Core\Controller\Cx::MODE_BACKEND) { if (empty($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $_SESSION->cmsSessionStatusUpdate('backend'); } }
/** * @param boolean $backend whether this is a backend request or not */ public function __construct($backend) { $this->isBackendRequest = $backend; //start session if it's not ready yet global $sessionObj; if (empty($sessionObj)) { //session hasn't been initialized so far $sessionObj = \cmsSession::getInstance(); } }
protected function initSession() { global $sessionObj; if (empty($sessionObj)) { //session hasn't been initialized so far $sessionObj = \cmsSession::getInstance(); } if (!isset($_SESSION['upload'])) { $_SESSION['upload'] = array(); $_SESSION['upload']['handlers'] = array(); } }
/** * Do something after resolving is done * * @param \Cx\Core\ContentManager\Model\Entity\Page $page The resolved page */ public function postResolve(\Cx\Core\ContentManager\Model\Entity\Page $page) { global $sessionObj; switch ($this->cx->getMode()) { case \Cx\Core\Core\Controller\Cx::MODE_FRONTEND: if (isset($_REQUEST['section']) && $_REQUEST['section'] == 'Upload') { if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } // initialize session object $objUploadModule = new Upload(); $objUploadModule->getPage(); //execution never reaches this point } break; default: break; } }
private function __construct($config) { global $sessionObj; if (!isset($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } // TODO: move to basic configuration screen (/cadmin/index.php?cmd=settings) $captchaConfig = array('ReCaptcha' => array('domains' => array('localhost' => array('public_key' => '6LeiusgSAAAAACPI2stz_Qh2fVC1reRUxJuqzf7h', 'private_key' => '6LeiusgSAAAAAABv3CW65svwgRMqFfTiC5NTOzOh')))); $config['coreCaptchaLib'] = ''; $config['coreCaptchaLibConfig'] = json_encode($captchaConfig); switch ($config['coreCaptchaLib']) { case 'ReCaptcha': $this->objCaptcha = new ReCaptcha($config); break; case 'contrexx': default: $this->objCaptcha = new ContrexxCaptcha($config); break; } }
private static function __setkey($key, $value) { if (!isset($_SESSION[self::$sesskey])) { \cmsSession::getInstance(); $_SESSION[self::$sesskey] = array(); } $_SESSION[self::$sesskey][$key] = $value; }
function _showTermination() { global $objTpl, $_ARRLANG, $_CONFIG, $_DBCONFIG, $objCommon, $basePath, $sessionObj, $documentRoot; // load template file $objTpl->addBlockfile('CONTENT', 'CONTENT_BLOCK', "termination.html"); $result = $this->_createConfigFile(); if ($result !== true) { $objTpl->setVariable(array('ERROR_MSG' => $result)); $objTpl->parse('errorMsg'); $objTpl->hideBlock('termination'); } else { $objCommon->updateCheck(); $objTpl->hideBlock('errorMsg'); $port = intval($_SERVER['SERVER_PORT']); if ($port != 80) { $port = ':' . $port; } else { $port = ''; } if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off') { $protocol = "http://"; } else { $protocol = "https://"; } $webUrl = $protocol . $_SESSION['installer']['sysConfig']['domainURL'] . $port . $_SESSION['installer']['config']['offsetPath'] . '/'; $adminUrl = $protocol . $_SESSION['installer']['sysConfig']['domainURL'] . $port . $_SESSION['installer']['config']['offsetPath'] . '/cadmin/'; $congratulationsMsg = $_ARRLANG['TXT_CONGRATULATIONS_MESSAGE']; $congratulationsMsg = str_replace("[VERSION]", $_CONFIG['coreCmsVersion'], $congratulationsMsg); $congratulationsMsg = str_replace("[EDITION]", $_CONFIG['coreCmsEdition'], $congratulationsMsg); $internetSiteMsg = $_ARRLANG['TXT_INTERNET_SITE_MESSAGE']; $internetSiteMsg = str_replace("[WEB_URL]", "<a href=\"" . $webUrl . "\" target=\"_blank\" title=\"" . $_ARRLANG['TXT_INTERNET_SITE_FOR_VISITORS'] . "\">" . $webUrl . "</a>", $internetSiteMsg); $adminSiteMsg = $_ARRLANG['TXT_ADMIN_SITE_MESSAGE']; $adminSiteMsg = str_replace("[ADMIN_URL]", "<a href=\"" . $adminUrl . "\" target=\"_blank\" title=\"" . $_ARRLANG['TXT_ADMIN_SITE'] . "\">" . $adminUrl . "</a>", $adminSiteMsg); $objTpl->setVariable(array('TXT_LOGIN_CREDENTIAL' => $_ARRLANG['TXT_LOGIN_EMAIL'], 'CONGRATULATIONS_MESSAGE' => $congratulationsMsg, 'INTERNET_SITE_MESSAGE' => $internetSiteMsg, 'ADMIN_SITE_MESSAGE' => $adminSiteMsg, 'USERNAME' => $_SESSION['installer']['account']['username'], 'PASSWORD' => $_SESSION['installer']['account']['password'], 'HTML_IMAGE_CODE' => $_SESSION['installer']['updateCheckImage'])); $objTpl->parse('termination'); // overwrite current DBCONFIG with the new data, so the database can be loaded correct in this request $_DBCONFIG['host'] = $_SESSION['installer']['config']['dbHostname']; $_DBCONFIG['database'] = $_SESSION['installer']['config']['dbDatabaseName']; $_DBCONFIG['user'] = $_SESSION['installer']['config']['dbUsername']; $_DBCONFIG['password'] = $_SESSION['installer']['config']['dbPassword']; $_DBCONFIG['tablePrefix'] = $_SESSION['installer']['config']['dbTablePrefix']; @session_destroy(); // clear cx in env, because from now on we use the core Cx and not longer the InstallerCx \Env::clear('cx'); // we will now initialize a new session and will login the administrator (userID = 1). // this is required to allow the License system (versioncheck.php) to update // the license section template // We might have some overhead, since versioncheck.php does more or less the same again $documentRoot = realpath(dirname($basePath)); require_once $documentRoot . '/core/Core/init.php'; init('minimal', false); if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = cmsSession::getInstance(); } $userId = 1; $_SESSION->cmsSessionUserUpdate($userId); $_GET['force'] = 'true'; $_GET['silent'] = 'true'; require_once $documentRoot . '/core_modules/License/versioncheck.php'; } }
/** * Get the thumbnail generation progress from the temp file */ function getThumbProgress() { // release the locks, session not needed $session = \cmsSession::getInstance(); $session->releaseLocks(); session_write_close(); $key = isset($_GET['key']) ? $_GET['key'] : ''; $processFile = $session->getTempPath() . '/progress' . $key . '.txt'; $process = 0; if (file_exists($processFile)) { $process = file_get_contents($processFile); if ($process == 100) { \Cx\Lib\FileSystem\FileSystem::delete_file($processFile); } } echo $process; die; }
/** * Gets the temporary upload location for files. * @param integer $submissionId * @return array('path','webpath', 'dirname') * @throws ContactException */ protected static function getTemporaryUploadPath($submissionId, $fieldId) { global $sessionObj; if (!isset($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $tempPath = $_SESSION->getTempPath(); $tempWebPath = $_SESSION->getWebTempPath(); if ($tempPath === false || $tempWebPath === false) { throw new \Cx\Core_Modules\Contact\Controller\ContactException('could not get temporary session folder'); } $dirname = 'contact_files_' . $submissionId . '_' . $fieldId; $result = array($tempPath, $tempWebPath, $dirname); return $result; }
/** * 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; }
/** * Remove the file from folder widget * * @param array $params array from json request */ public function removeFileFromFolderWidget($params) { \cmsSession::getInstance(); $folderWidgetId = isset($params['get']['widget']) ? contrexx_input2int($params['get']['widget']) : 0; if (empty($folderWidgetId) || empty($_SESSION['MediaBrowser']['FolderWidget'][$folderWidgetId]) || $_SESSION['MediaBrowser']['FolderWidget'][$folderWidgetId]['mode'] == \Cx\Core_Modules\MediaBrowser\Model\Entity\FolderWidget::MODE_VIEW_ONLY) { return false; } $path = !empty($params['get']['file']) ? contrexx_input2raw($params['get']['file']) : null; if (empty($path)) { return false; } $folder = $_SESSION['MediaBrowser']['FolderWidget'][$folderWidgetId]['folder']; $localFileSystem = new \Cx\Core\MediaSource\Model\Entity\LocalFileSystem($folder); $file = '/' . $path; $objFile = new \Cx\Core\MediaSource\Model\Entity\LocalFile($file); $this->setMessage($localFileSystem->removeFile($objFile)); return array(); }
/** * Handle the calendar image upload * * @param string $id uploaderId * * @return string image path */ function _handleUpload($id) { global $sessionObj; if (!isset($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $tmpUploadDir = $_SESSION->getTempPath() . '/' . $id . '/'; //all the files uploaded are in here $depositionTarget = $this->uploadImgPath; //target folder $pic = ''; //move all files if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpUploadDir)) { return $pic; } $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; }
/** * 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; }
/** * Logs the user off and destroys the session. */ public function logoutAndDestroySession() { if (isset($_SESSION['auth'])) { unset($_SESSION['auth']); } \cmsSession::getInstance()->destroy(); }
/** * Gets the temporary upload location for files. * * @param string $fieldName Uploader field name and id * @param integer $submissionId * * @throws Exeception * * @return array('path','webpath', 'dirname') */ public static function getTemporaryUploadPath($fieldName, $submissionId) { global $sessionObj; if (!isset($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $tempPath = $_SESSION->getTempPath(); $tempWebPath = $_SESSION->getWebTempPath(); if ($tempPath === false || $tempWebPath === false) { throw new \Exception('could not get temporary session folder'); } $dirname = "event_files_{$fieldName}_{$submissionId}"; $result = array($tempPath, $tempWebPath, $dirname); return $result; }
/** * Checks if this page can be displayed in frontend, redirects to login of not * @param \Cx\Core\ContentManager\Model\Entity\Page $page Page to check * @param int $history (optional) Revision of page to use, 0 means current, default 0 */ public function checkPageFrontendProtection($page, $history = 0) { global $sessionObj; $page_protected = $page->isFrontendProtected(); $pageAccessId = $page->getFrontendAccessId(); if ($history) { $pageAccessId = $page->getBackendAccessId(); } // login pages are unprotected by design $checkLogin = array($page); while (count($checkLogin)) { $currentPage = array_pop($checkLogin); if ($currentPage->getType() == \Cx\Core\ContentManager\Model\Entity\Page::TYPE_FALLBACK) { try { array_push($checkLogin, $this->getFallbackPage($currentPage)); } catch (ResolverException $e) { } } if ($currentPage->getModule() == 'Login') { return; } } // Authentification for protected pages if (($page_protected || $history || !empty($_COOKIE['PHPSESSID'])) && (!isset($_REQUEST['section']) || $_REQUEST['section'] != 'Login')) { if (empty($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $_SESSION->cmsSessionStatusUpdate('frontend'); if (\FWUser::getFWUserObject()->objUser->login()) { if ($page_protected) { if (!\Permission::checkAccess($pageAccessId, 'dynamic', true)) { $link = base64_encode(\Env::get('cx')->getRequest()->getUrl()->toString()); \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . \Cx\Core\Routing\Url::fromModuleAndCmd('Login', 'noaccess', '', array('redirect' => $link))); exit; } } if ($history && !\Permission::checkAccess(78, 'static', true)) { $link = base64_encode(\Env::get('cx')->getRequest()->getUrl()->toString()); \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . \Cx\Core\Routing\Url::fromModuleAndCmd('Login', 'noaccess', '', array('redirect' => $link))); exit; } } elseif (!empty($_COOKIE['PHPSESSID']) && !$page_protected) { unset($_COOKIE['PHPSESSID']); } else { if (isset($_GET['redirect'])) { $link = $_GET['redirect']; } else { $link = base64_encode(\Env::get('cx')->getRequest()->getUrl()->toString()); } \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . \Cx\Core\Routing\Url::fromModuleAndCmd('Login', '', '', array('redirect' => $link))); exit; } } }
/** * Get uploaded csv file by using uploader id * * @param string $uploaderId Uploader id * * @return boolean|string File path when file exists, false otherwise */ public function getUploadedFileFromUploader($uploaderId) { if (empty($uploaderId)) { return false; } $objSession = \cmsSession::getInstance(); $uploaderFolder = $objSession->getTempPath() . '/' . $uploaderId; if (!\Cx\Lib\FileSystem\FileSystem::exists($uploaderFolder)) { return false; } foreach (glob($uploaderFolder . '/*.csv') as $file) { return $file; } return false; }
/** * Checks if the user has been successfully authenticated * * If a user has been successfully authenticated then he will be * redirected to the requested page, otherwise the login page will be displayed * * @access private * @global array * @see cmsSession::cmsSessionStatusUpdate(), contrexx_strip_tags, \Cx\Core\Html\Sigma::get() * @return string \Cx\Core\Html\Sigma::get() */ function _login() { global $_CORELANG, $sessionObj; $objFWUser = \FWUser::getFWUserObject(); if (isset($_REQUEST['redirect'])) { $redirect = contrexx_strip_tags($_REQUEST['redirect']); } elseif (isset($_SESSION['redirect'])) { $redirect = $_SESSION['redirect']; } else { $redirect = ""; } \Cx\Lib\SocialLogin::parseSociallogin($this->_objTpl); $arrSettings = \User_Setting::getSettings(); if (function_exists('curl_init') && $arrSettings['sociallogin']['status'] && !empty($_GET['provider'])) { $providerLogin = $this->loginWithProvider($_GET['provider']); if ($providerLogin) { return $providerLogin; } } if ($objFWUser->objUser->login()) { if (isset($_POST['login']) && $objFWUser->checkLogin() || isset($_GET['auth-token']) && isset($_GET['user-id'])) { $objFWUser->objUser->reset(); $objFWUser->logoutAndDestroySession(); $sessionObj = \cmsSession::getInstance(); } elseif (isset($_POST['login'])) { $_GET['relogin'] = '******'; } } if ((!isset($_GET['relogin']) || $_GET['relogin'] != 'true') && $objFWUser->objUser->login() || $objFWUser->checkAuth()) { $groupRedirect = ($objGroup = $objFWUser->objGroup->getGroup($objFWUser->objUser->getPrimaryGroupId())) && $objGroup->getHomepage() ? preg_replace('/\\[\\[([A-Z0-9_-]+)\\]\\]/', '{\\1}', $objGroup->getHomepage()) : CONTREXX_SCRIPT_PATH; \LinkGenerator::parseTemplate($groupRedirect); if (isset($_SESSION['redirect'])) { unset($_SESSION['redirect']); } if (!empty($redirect)) { $redirect = \FWUser::getRedirectUrl(urlencode(base64_decode($redirect))); } \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . (empty($redirect) ? $groupRedirect : $redirect)); exit; } else { if (isset($_POST['login'])) { $this->_statusMessage = $_CORELANG['TXT_PASSWORD_OR_USERNAME_IS_INCORRECT']; } } if (isset($_SESSION['auth']['loginLastAuthFailed'])) { $this->_objTpl->setVariable(array('TXT_CORE_CAPTCHA' => $_CORELANG['TXT_CORE_CAPTCHA'], 'CAPTCHA_CODE' => \Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->getCode())); $this->_objTpl->parse('captcha'); } else { $this->_objTpl->hideBlock('captcha'); } // TODO: loading the language data of component Access at this // point is a workaround as the integration of the Access // component's functionality itself is hard-coded too and // has not been implemented through the system component // framework. $accessLang = \Env::get('init')->getComponentSpecificLanguageData('Access'); $this->_objTpl->setVariable(array('TXT_ACCESS_SIGNUP_BY_FACEBOOK' => $accessLang['TXT_ACCESS_SIGNUP_BY_FACEBOOK'], 'TXT_ACCESS_SIGNUP_BY_GOOGLE' => $accessLang['TXT_ACCESS_SIGNUP_BY_GOOGLE'], 'TXT_ACCESS_SIGNUP_BY_TWITTER' => $accessLang['TXT_ACCESS_SIGNUP_BY_TWITTER'], 'TXT_CORE_SIGN_UP' => $_CORELANG['TXT_CORE_SIGN_UP'], 'TXT_LOGIN' => $_CORELANG['TXT_LOGIN'], 'TXT_USER_NAME' => $_CORELANG['TXT_USER_NAME'], 'TXT_EMAIL' => $_CORELANG['TXT_EMAIL'], 'TXT_PASSWORD' => $_CORELANG['TXT_PASSWORD'], 'TXT_LOGIN_REMEMBER_ME' => $_CORELANG['TXT_CORE_REMEMBER_ME'], 'TXT_PASSWORD_LOST' => $_CORELANG['TXT_PASSWORD_LOST'], 'LOGIN_REDIRECT' => $redirect, 'LOGIN_STATUS_MESSAGE' => $this->_statusMessage)); return $this->_objTpl->get(); }
/** * Get uploaded file path by using uploader id and file name * * @param string $uploaderId Uploader id * @param string $fileName File name * * @return boolean|string File path when File exists, false otherwise */ public function getUploadedFilePath($uploaderId, $fileName) { global $sessionObj; if (empty($uploaderId) || empty($fileName)) { return false; } if (empty($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $uploaderFolder = $sessionObj->getTempPath() . '/' . $uploaderId; if (!\Cx\Lib\FileSystem\FileSystem::exists($uploaderFolder)) { return false; } $filePath = $uploaderFolder . '/' . $fileName; if (!\Cx\Lib\FileSystem\FileSystem::exists($filePath)) { return false; } return $filePath; }
/** * handles the upload of a file * * @param string $inputName name of the HTML input element used to upload the file * * @return array $uploadedFileInfo array containing the properties for the uploaded file, * false when upload has failed */ function _handleUpload($inputName) { global $_ARRAYLANG, $sessionObj; $fileName = isset($_POST[$inputName]) ? contrexx_input2raw($_POST[$inputName]) : ''; if (empty($fileName)) { return array('name' => '', 'path' => '', 'size' => 0); } $uploaderId = isset($_POST['forumUploaderId']) ? contrexx_input2raw($_POST['forumUploaderId']) : ''; if (empty($uploaderId)) { \DBG::log('Uploader id is empty'); return false; } //Re-initialize the $sessionObj if it is empty if (empty($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $tempPath = $sessionObj->getTempPath() . '/' . $uploaderId . '/' . $fileName; if (!\Cx\Lib\FileSystem\FileSystem::exists($tempPath)) { return false; } $cx = \Cx\Core\Core\Controller\Cx::instanciate(); $filePath = $cx->getWebsiteMediaForumUploadPath() . '/'; $pathinfo = pathinfo($fileName); $i = 1; while (\Cx\Lib\FileSystem\FileSystem::exists($filePath . $fileName)) { $fileName = $pathinfo['filename'] . '_' . $i++ . '.' . $pathinfo['extension']; } if (\Cx\Lib\FileSystem\FileSystem::move($tempPath, $filePath . $fileName, true) === false) { $this->_objTpl->setVariable('TXT_FORUM_ERROR', $filePath . $fileName . ': ' . $_ARRAYLANG['TXT_FORUM_UPLOAD_NOT_MOVABLE']); return false; } return array('name' => contrexx_addslashes($fileName), 'path' => $filePath, 'size' => filesize($filePath . $fileName)); }
/** * Import and Export data from/to csv * @author Reto Kohli <*****@*****.**> (parts) */ function _import() { global $_ARRAYLANG, $objDatabase; self::$pageTitle = $_ARRAYLANG['TXT_SHOP_IMPORT_TITLE']; self::$objTemplate->loadTemplateFile('module_shop_import.html'); self::$objTemplate->setGlobalVariable(array('TXT_SHOP_IMPORT_CATEGORIES_TIPS' => contrexx_raw2xhtml($_ARRAYLANG['TXT_SHOP_IMPORT_CATEGORIES_TIPS']), 'TXT_SHOP_IMPORT_CHOOSE_TEMPLATE_TIPS' => contrexx_raw2xhtml($_ARRAYLANG['TXT_SHOP_IMPORT_CHOOSE_TEMPLATE_TIPS']))); $objCSVimport = new CsvImport(); // Delete template if (isset($_REQUEST['deleteImg'])) { $query = "\n DELETE FROM " . DBPREFIX . "module_shop" . MODULE_INDEX . "_importimg\n WHERE img_id=" . $_REQUEST['img']; if ($objDatabase->Execute($query)) { \Message::ok($_ARRAYLANG['TXT_SHOP_IMPORT_SUCCESSFULLY_DELETED']); } else { \Message::error($_ARRAYLANG['TXT_SHOP_IMPORT_ERROR_DELETE']); } } // Save template if (isset($_REQUEST['SaveImg'])) { $query = "\n INSERT INTO " . DBPREFIX . "module_shop" . MODULE_INDEX . "_importimg (\n img_name, img_cats, img_fields_file, img_fields_db\n ) VALUES (\n '" . $_REQUEST['ImgName'] . "',\n '" . $_REQUEST['category'] . "',\n '" . $_REQUEST['pairs_left_keys'] . "',\n '" . $_REQUEST['pairs_right_keys'] . "'\n )"; if ($objDatabase->Execute($query)) { \Message::ok($_ARRAYLANG['TXT_SHOP_IMPORT_SUCCESSFULLY_SAVED']); } else { \Message::error($_ARRAYLANG['TXT_SHOP_IMPORT_ERROR_SAVE']); } } $objCSVimport->initTemplateArray(); $fileExists = false; $fileName = isset($_POST['csvFile']) ? contrexx_input2raw($_POST['csvFile']) : ''; $uploaderId = isset($_POST['importCsvUploaderId']) ? contrexx_input2raw($_POST['importCsvUploaderId']) : ''; if (!empty($fileName) && !empty($uploaderId)) { $objSession = \cmsSession::getInstance(); $tmpFile = $objSession->getTempPath() . '/' . $uploaderId . '/' . $fileName; $fileExists = \Cx\Lib\FileSystem\FileSystem::exists($tmpFile); } // Import Categories // This is not subject to change, so it's hardcoded if (isset($_REQUEST['ImportCategories']) && $fileExists) { // delete existing categories on request only! // mind that this necessarily also clears all products and // their associated attributes! if (!empty($_POST['clearCategories'])) { Products::deleteByShopCategory(0, false, true); ShopCategories::deleteAll(); // NOTE: Removing Attributes is now disabled. Optionally enable this. // Attributes::deleteAll(); } $objCsv = new CsvBv($tmpFile); $importedLines = 0; $arrCategoryLevel = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); $line = $objCsv->NextLine(); while ($line) { $level = 0; foreach ($line as $catName) { ++$level; if (!empty($catName)) { $parentCatId = $objCSVimport->getCategoryId($catName, $arrCategoryLevel[$level - 1]); $arrCategoryLevel[$level] = $parentCatId; } } ++$importedLines; $line = $objCsv->NextLine(); } \Message::ok($_ARRAYLANG['TXT_SHOP_IMPORT_SUCCESSFULLY_IMPORTED_CATEGORIES'] . ': ' . $importedLines); } // Import if (isset($_REQUEST['importFileProducts']) && $fileExists) { if (isset($_POST['clearProducts']) && $_POST['clearProducts']) { Products::deleteByShopCategory(0, false, true); // The categories need not be removed, but it is done by design! ShopCategories::deleteAll(); // NOTE: Removing Attributes is now disabled. Optionally enable this. // Attributes::deleteAll(); } $arrFileContent = $objCSVimport->GetFileContent($tmpFile); $query = ' SELECT img_id, img_name, img_cats, img_fields_file, img_fields_db FROM ' . DBPREFIX . 'module_shop' . MODULE_INDEX . '_importimg WHERE img_id=' . $_REQUEST['ImportImage']; $objResult = $objDatabase->Execute($query); $arrCategoryName = preg_split('/;/', $objResult->fields['img_cats'], null, PREG_SPLIT_NO_EMPTY); $arrFirstLine = $arrFileContent[0]; $arrCategoryColumnIndex = array(); for ($x = 0; $x < count($arrCategoryName); ++$x) { foreach ($arrFirstLine as $index => $strColumnName) { if ($strColumnName == $arrCategoryName[$x]) { $arrCategoryColumnIndex[] = $index; } } } $arrTemplateFieldName = preg_split('/;/', $objResult->fields['img_fields_file'], null, PREG_SPLIT_NO_EMPTY); $arrDatabaseFieldIndex = array(); for ($x = 0; $x < count($arrTemplateFieldName); ++$x) { foreach ($arrFirstLine as $index => $strColumnName) { if ($strColumnName == $arrTemplateFieldName[$x]) { $arrDatabaseFieldIndex[] = $index; } } } $arrProductFieldName = preg_split('/;/', $objResult->fields['img_fields_db'], null, PREG_SPLIT_NO_EMPTY); $arrProductDatabaseFieldName = array(); for ($x = 0; $x < count($arrProductFieldName); ++$x) { $dbname = $objCSVimport->DBfieldsName($arrProductFieldName[$x]); $arrProductDatabaseFieldName[$dbname] = (isset($arrProductDatabaseFieldName[$dbname]) ? $arrProductDatabaseFieldName[$dbname] . ';' : '') . $x; } $importedLines = 0; $errorLines = 0; // Array of IDs of newly inserted records $arrId = array(); for ($x = 1; $x < count($arrFileContent); ++$x) { $category_id = false; for ($cat = 0; $cat < count($arrCategoryColumnIndex); ++$cat) { $catName = $arrFileContent[$x][$arrCategoryColumnIndex[$cat]]; if (empty($catName) && !empty($category_id)) { break; } if (empty($catName)) { $category_id = $objCSVimport->GetFirstCat(); } else { $category_id = $objCSVimport->getCategoryId($catName, $category_id); } } if ($category_id == 0) { $category_id = $objCSVimport->GetFirstCat(); } $objProduct = new Product('', $category_id, '', Distribution::TYPE_DELIVERY, 0, 1, 0, 0, 0); foreach ($arrProductDatabaseFieldName as $index => $strFieldIndex) { $value = ''; if (strpos($strFieldIndex, ';')) { $prod2line = explode(';', $strFieldIndex); for ($z = 0; $z < count($prod2line); ++$z) { $value .= $arrFileContent[$x][$arrDatabaseFieldIndex[$prod2line[$z]]] . '<br />'; } } else { $value = $arrFileContent[$x][$arrDatabaseFieldIndex[$strFieldIndex]]; } $objProduct->{$index}($value); } if ($objProduct->store()) { $arrId[] = $objProduct->id(); ++$importedLines; } else { ++$errorLines; } } // Fix picture field and create thumbnails Products::makeThumbnailsById($arrId); if ($importedLines) { \Message::ok($_ARRAYLANG['TXT_SHOP_IMPORT_SUCCESSFULLY_IMPORTED_PRODUCTS'] . ': ' . $importedLines); } if ($errorLines) { \Message::error($_ARRAYLANG['TXT_SHOP_IMPORT_NOT_SUCCESSFULLY_IMPORTED_PRODUCTS'] . ': ' . $errorLines); } } // end import $jsnofiles = ''; $fileFields = $dblist = null; $arrTemplateArray = $objCSVimport->getTemplateArray(); if (isset($_REQUEST['mode']) && $_REQUEST['mode'] != 'ImportImg') { if (count($arrTemplateArray) == 0) { self::$objTemplate->hideBlock('import_products'); self::$objTemplate->touchBlock('import_products_no_template'); } else { $imageChoice = $objCSVimport->GetImageChoice(); self::$objTemplate->setVariable(array('IMAGE_CHOICE' => $imageChoice)); } } else { if (!isset($_REQUEST['SelectFields'])) { $jsnofiles = "selectTab('import1');"; } else { if (isset($_POST['mode']) && $_POST['csvFile'] == '') { $jsnofiles = "selectTab('import4');"; } else { $jsnofiles = "selectTab('import2');"; if ($fileExists) { $fileFields = ' <select name="FileFields" id="file_field" style="width: 200px;" size="10"> ' . $objCSVimport->getFilefieldMenuOptions($tmpFile) . ' </select>' . "\n"; } $dblist = ' <select name="DbFields" id="given_field" style="width: 200px;" size="10"> ' . $objCSVimport->getAvailableNamesMenuOptions() . ' </select>' . "\n"; } } } $jsSelectLayer = 'selectTab("import1");'; if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'ImportImg') { $jsSelectLayer = 'selectTab("import2");'; } $arrTemplateArray = $objCSVimport->getTemplateArray(); if ($arrTemplateArray) { $arrName = $objCSVimport->getNameArray(); self::$objTemplate->setVariable('SHOP_IMPORT_TEMPLATE_MENU', \Html::getSelect('ImportImage', $arrName)); } else { self::$objTemplate->touchBlock('import_products_no_template'); } for ($x = 0; $x < count($arrTemplateArray); ++$x) { self::$objTemplate->setVariable(array('IMG_NAME' => $arrTemplateArray[$x]['name'], 'IMG_ID' => $arrTemplateArray[$x]['id'], 'CLASS_NAME' => 'row' . ($x % 2 + 1), 'SHOP_CMS_OFFSET' => \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteOffsetPath())); self::$objTemplate->parse('imgRow'); } //initialize the uploader $uploader = new \Cx\Core_Modules\Uploader\Model\Entity\Uploader(); //create an uploader $uploader->setCallback('importUploaderCallback'); $uploader->setOptions(array('id' => 'importCsvUploader', 'allowed-extensions' => array('csv', 'xls'), 'data-upload-limit' => 1, 'style' => 'display:none')); self::$objTemplate->setVariable(array('SELECT_LAYER_ONLOAD' => $jsSelectLayer, 'NO_FILES' => isset($jsnofiles) ? $jsnofiles : '', 'FILE_FIELDS_LIST' => isset($fileFields) ? $fileFields : '', 'DB_FIELDS_LIST' => isset($dblist) ? $dblist : '', 'SHOP_IMPORT_CSV_UPLOADER_CODE' => $uploader->getXHtml(), 'SHOP_IMPORT_CSV_UPLOADER_ID' => $uploader->getId())); // TODO: !!! CSV EXPORT IS OBSOLETE AND DYSFUNCT !!! /* // Export groups -- hardcoded $content_location = ''; if (isset($_REQUEST['group'])) { $query = $fieldNames = $content_location = ''; $arrPictures = null; switch ($_REQUEST['group']) { // products - plain fields: case 'tproduct': $content_location = "ProdukteTabelle.csv"; $fieldNames = array( 'id', 'product_id', 'picture', 'title', 'catid', 'distribution', 'normalprice', 'resellerprice', 'short', 'long', 'stock', 'stock_visible', 'discountprice', 'discount_active', 'active', 'b2b', 'b2c', 'date_start', 'date_end', 'manufacturer', 'manufacturer_url', 'external_link', 'ord', 'vat_id', 'weight', 'flags', 'group_id', 'article_id', 'keywords', ); $query = " SELECT id, product_id, picture, title, catid, distribution, normalprice, resellerprice, short, long, stock, stock_visible, discountprice, discount_active, active, b2b, b2c, date_start, date_end, manufacturer, manufacturer_url, external_link, sort_order, vat_id, weight, flags, group_id, article_id, keywords FROM ".DBPREFIX."module_shop_products ORDER BY id ASC"; break; // products - custom: case 'rproduct': $content_location = "ProdukteRelationen.csv"; $fieldNames = array( 'id', 'product_id', 'picture', 'title', 'catid', 'category', 'parentcategory', 'distribution', 'normalprice', 'resellerprice', 'discountprice', 'discount_active', 'short', 'long', 'stock', 'stock_visible', 'active', 'b2b', 'b2c', 'date_start', 'date_end', 'manufacturer_name', 'manufacturer_website', 'manufacturer_url', 'external_link', 'ord', 'vat_percent', 'weight', 'discount_group', 'article_group', 'keywords', ); // c1.catid *MUST NOT* be NULL // c2.catid *MAY* be NULL (if c1.catid is root) // vat_id *MAY* be NULL $query = " SELECT p.id, p.product_id, p.picture, p.title, p.catid, c1.catname as category, c2.catname as parentcategory, p.distribution, p.normalprice, p.resellerprice, p.discountprice, p.discount_active, p.short, p.long, p.stock, p.stock_visible, p.active, p.b2b, p.b2c, p.date_start, p.date_end, m.name as manufacturer_name, m.url as manufacturer_website, p.manufacturer_url, p.external_link, p.ord, v.percent as vat_percent, p.weight, d.name AS discount_group, a.name AS article_group, p.keywords FROM ".DBPREFIX."module_shop_products p INNER JOIN ".DBPREFIX."module_shop_categories c1 ON p.catid=c1.catid LEFT JOIN ".DBPREFIX."module_shop_categories c2 ON c1.parentid=c2.catid LEFT JOIN ".DBPREFIX."module_shop_vat v ON vat_id=v.id LEFT JOIN ".DBPREFIX."module_shop_manufacturer as m ON m.id = p.manufacturer LEFT JOIN ".DBPREFIX."module_shop_discountgroup_count_name as d ON d.id = p.group_id LEFT JOIN ".DBPREFIX."module_shop_article_group as a ON a.id = p.article_id ORDER BY catid ASC, product_id ASC"; break; // customer - plain fields: // TODO: Use Customer class! case 'tcustomer': $content_location = "KundenTabelle.csv"; $fieldNames = array( 'customerid', 'username', 'password', 'prefix', 'company', 'firstname', 'lastname', 'address', 'city', 'zip', 'country_id', 'phone', 'fax', 'email', 'ccnumber', 'ccdate', 'ccname', 'cvc_code', 'company_note', 'is_reseller', 'register_date', 'customer_status', 'group_id', ); $query = " SELECT customerid, username, password, prefix, company, firstname, lastname, address, city, zip, country_id, phone, fax, email, ccnumber, ccdate, ccname, cvc_code, company_note, is_reseller, register_date, customer_status, group_id FROM ".DBPREFIX."module_shop_customers ORDER BY lastname ASC, firstname ASC"; break; // customer - custom: // TODO: Use Customer class! case 'rcustomer': $content_location = "KundenRelationen.csv"; $fieldNames = array( 'customerid', 'username', 'firstname', 'lastname', 'prefix', 'company', 'address', 'zip', 'city', 'countries_name', 'phone', 'fax', 'email', 'is_reseller', 'register_date', 'group_name', ); $query = " SELECT c.customerid, c.username, c.firstname, c.lastname, c.prefix, c.company, c.address, c.zip, c.city, n.countries_name, c.phone, c.fax, c.email, c.is_reseller, c.register_date, d.name AS group_name FROM ".DBPREFIX."module_shop_customers c INNER JOIN ".DBPREFIX."module_shop_countries n ON c.country_id=n.countries_id LEFT JOIN ".DBPREFIX."module_shop_customer_group d ON c.group_id=d.id ORDER BY c.lastname ASC, c.firstname ASC"; break; // orders - plain fields: case 'torder': $content_location = "BestellungenTabelle.csv"; $fieldNames = array( 'id', 'customer_id', 'currency_id', 'order_sum', 'sum', 'date_time', 'status', 'ship_prefix', 'ship_company', 'ship_firstname', 'ship_lastname', 'ship_address', 'ship_city', 'ship_zip', 'ship_country_id', 'ship_phone', 'vat_amount', 'currency_ship_price', 'shipment_id', 'payment_id', 'currency_payment_price', 'ip', 'host', 'lang_id', 'browser', 'note', 'last_modified', 'modified_by'); $query = " SELECT id, customer_id, currency_id, order_sum, sum, date_time, status, ship_prefix, ship_company, ship_firstname, ship_lastname, ship_address, ship_city, ship_zip, ship_country_id, ship_phone, vat_amount, currency_ship_price, shipment_id, payment_id, currency_payment_price, ip, host, lang_id, browser, note, last_modified, modified_by FROM ".DBPREFIX."module_shop".MODULE_INDEX."_orders ORDER BY id ASC"; break; // orders - custom: case 'rorder': // TODO: Use Customer class! $content_location = "BestellungenRelationen.csv"; $fieldNames = array( 'id', 'order_sum', 'vat_amount', 'currency_ship_price', 'currency_payment_price', 'sum', 'date_time', 'status', 'ship_prefix', 'ship_company', 'ship_firstname', 'ship_lastname', 'ship_address', 'ship_city', 'ship_zip', 'ship_phone', 'note', 'customer_id', 'username', 'firstname', 'lastname', 'prefix', 'company', 'address', 'zip', 'city', 'countries_name', 'phone', 'fax', 'email', 'is_reseller', 'register_date', 'currency_code', 'shipper_name', 'payment_name', 'account_number', 'bank_name', 'bank_code'); $query = " SELECT o.id, o.order_sum, o.vat_amount, o.currency_ship_price, o.currency_payment_price, o.sum, o.date_time, o.status, o.ship_prefix, o.ship_company, o.ship_firstname, o.ship_lastname, o.ship_address, o.ship_city, o.ship_zip, o.ship_phone, o.note, o.customer_id, c.username, c.firstname, c.lastname, c.prefix, c.company, c.address, c.zip, c.city, n.countries_name, c.phone, c.fax, c.email, c.is_reseller, c.register_date, u.code AS currency_code, s.name AS shipper_name, p.name AS payment_name, l.holder, l.bank, l.blz FROM ".DBPREFIX."module_shop_orders o INNER JOIN ".DBPREFIX."module_shop_customers c ON o.customer_id=c.customerid INNER JOIN ".DBPREFIX."module_shop_countries n ON c.country_id=n.countries_id INNER JOIN ".DBPREFIX."module_shop_currencies u ON o.currency_id=u.id LEFT JOIN ".DBPREFIX."module_shop_shipper s ON o.shipment_id=s.id LEFT JOIN ".DBPREFIX."module_shop_payment p ON o.payment_id=p.id LEFT JOIN ".DBPREFIX."module_shop_lsv l ON o.id=l.order_id ORDER BY o.id ASC"; break; } // switch if ($query && $objResult = $objDatabase->Execute($query)) { // field names $fileContent = '"'.join('";"', $fieldNames)."\"\n"; while (!$objResult->EOF) { $arrRow = $objResult->FetchRow(); $arrReplaced = array(); // Decode the pictures foreach ($arrRow as $index => $field) { if ($index == 'picture') { $arrPictures = Products::get_image_array_from_base64($field); $field = 'http://'. $_SERVER['HTTP_HOST'].'/'. ASCMS_SHOP_IMAGES_WEB_PATH.'/'. $arrPictures[1]['img']; } $arrReplaced[] = str_replace('"', '""', $field); } $fileContent .= '"'.join('";"', $arrReplaced)."\"\n"; } // Test the output for UTF8! if (strtoupper(CONTREXX_CHARSET) == 'UTF-8') { $fileContent = utf8_decode($fileContent); } // TODO: Add success message? // set content to filename and -type for download header("Content-Disposition: inline; filename=$content_location"); header("Content-Type: text/comma-separated-values"); echo($fileContent); exit(); } \Message::error($_ARRAYLANG['TXT_SHOP_EXPORT_ERROR']); } else { // can't submit without a group selection } // if/else group // end export // make sure that language entries exist for all of // TXT_SHOP_EXPORT_GROUP_*, TXT_SHOP_EXPORT_GROUP_*_TIP !! $arrGroups = array('tproduct', 'rproduct', 'tcustomer', 'rcustomer', 'torder', 'rorder'); $tipText = ''; for ($i = 0; $i < count($arrGroups); ++$i) { self::$objTemplate->setCurrentBlock('groupRow'); self::$objTemplate->setVariable(array( 'SHOP_EXPORT_GROUP' => $_ARRAYLANG['TXT_SHOP_EXPORT_GROUP_'.strtoupper($arrGroups[$i])], 'SHOP_EXPORT_GROUP_CODE' => $arrGroups[$i], 'SHOP_EXPORT_INDEX' => $i, 'CLASS_NAME' => 'row'.($i % 2 + 1), )); self::$objTemplate->parse('groupRow'); $tipText .= 'Text['.$i.']=["","'.$_ARRAYLANG['TXT_SHOP_EXPORT_GROUP_'.strtoupper($arrGroups[$i]).'_TIP'].'"];'; } */ }
/** * Get uploader code * * @param string $fieldKey uploadFieldKey * @param string $fieldName uploadFieldName * @param string $uploadCallBack upload callback function * @param boolean $allowImageOnly allow only images files * * @return string uploaderCode * @throws \Exception */ protected function getUploaderCode($fieldKey, $fieldName, $uploadCallBack = "uploadFinished", $allowImageOnly = true) { \cmsSession::getInstance(); $cx = \Cx\Core\Core\Controller\Cx::instanciate(); try { $uploader = new \Cx\Core_Modules\Uploader\Model\Entity\Uploader(); $uploaderId = $uploader->getId(); $uploadOptions = array('id' => 'calendarUploader_' . $uploaderId, 'style' => 'display: none'); if ($allowImageOnly) { $uploadOptions['allowed-extensions'] = array('gif', 'jpg', 'png', 'jpeg'); } $uploader->setCallback($fieldName . 'JsCallback'); $uploader->setUploadLimit(1); $uploader->setOptions($uploadOptions); $uploader->setFinishedCallback(array($cx->getCodeBaseModulePath() . '/Calendar/Controller/Calendar.class.php', '\\Cx\\Modules\\Calendar\\Controller\\Calendar', $uploadCallBack)); $folderWidget = new \Cx\Core_Modules\MediaBrowser\Model\Entity\FolderWidget($_SESSION->getTempPath() . '/' . $uploaderId); $this->_objTpl->setVariable(array(strtoupper($fieldName) . '_WIDGET_CODE' => $folderWidget->getXHtml(), "{$this->moduleLangVar}_" . strtoupper($fieldKey) => $uploaderId)); $strJs = <<<JAVASCRIPT {$uploader->getXHtml()} <script type="text/javascript"> cx.ready(function() { //called if user clicks on the field jQuery('#{$fieldName}').bind('click', function() { jQuery('#calendarUploader_{$uploaderId}').trigger('click'); return false; }); }); //uploader javascript callback function function {$fieldName}JsCallback(callback) { angular.element('#mediaBrowserfolderWidget_{$folderWidget->getId()}').scope().refreshBrowser(); } </script> JAVASCRIPT; return $strJs; } catch (\Exception $e) { \DBG::msg('<!-- failed initializing uploader -->'); throw new \Exception("failed initializing uploader"); } }
/** * Searchs for an user with the given user id of the social media platform. * If there is no user, create one and directly log in. * * @param string $oauth_id the user id of the social media platform * @return bool * @throws OAuth_Exception */ protected function getContrexxUser($oauth_id) { global $sessionObj; //\DBG::activate(); $arrSettings = \User_Setting::getSettings(); $provider = $this::OAUTH_PROVIDER; $FWUser = \FWUser::getFWUserObject(); $objUser = $FWUser->objUser->getByNetwork($provider, $oauth_id); if (!$objUser) { // check whether the user is already logged in // if the user is logged in just add a new network to the user object if ($FWUser->objUser->login()) { $objUser = $FWUser->objUser; $this->addProviderToUserObject($provider, $oauth_id, $objUser); $objUser->getNetworks()->save(); return true; } // create a new user with the default profile attributes $objUser = new \User(); $objUser->setEmail($this->getEmail()); $objUser->setAdminStatus(0); $objUser->setProfile(array('firstname' => array($this->getFirstname()), 'lastname' => array($this->getLastname()))); $registrationRedirectNeeded = $arrSettings['sociallogin_show_signup']['status']; // if user_account_verification is true (1), then we need to do checkMandatoryCompliance(), because // the required fields must be set. if ($registrationRedirectNeeded == false && $arrSettings['user_account_verification']['value'] === 1) { $registrationRedirectNeeded = !$objUser->checkMandatoryCompliance(); } $objUser->setActiveStatus(!$registrationRedirectNeeded); if ($registrationRedirectNeeded) { $objUser->setRestoreKey(); $objUser->setRestoreKeyTime(intval($arrSettings['sociallogin_activation_timeout']['value']) * 60); } if (!empty($arrSettings['sociallogin_assign_to_groups']['value'])) { $groups = $arrSettings['sociallogin_assign_to_groups']['value']; } else { $groups = $arrSettings['assigne_to_groups']['value']; } $objUser->setGroups(explode(',', $groups)); // if we can create the user without sign up page if (!$objUser->store()) { // if the email address already exists but not with the given oauth-provider throw new OAuth_Exception(); } // add the social network to user $this->addProviderToUserObject($provider, $oauth_id, $objUser); $objUser->getNetworks()->save(); // check whether there are empty mandatory fields or the setting to show sign up everytime if ($registrationRedirectNeeded) { // start session if no session is open if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } // write the user id to session so we can pre-fill the sign up form $_SESSION['user_id'] = $objUser->getId(); // generate url for sign up page and redirect $signUpPageUri = \Cx\Core\Routing\Url::fromModuleAndCmd('Access', 'signup'); \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $signUpPageUri->__toString()); exit; } } $FWUser->loginUser($objUser); }
* "Cloudrexx" is a registered trademark of Cloudrexx AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ header("content-type: application/javascript"); if (strpos(dirname(__FILE__), 'customizing') === false) { $contrexx_path = dirname(dirname(dirname(__FILE__))); } else { // this files resides within the customizing directory, therefore we'll have to strip // out one directory more than usually $contrexx_path = dirname(dirname(dirname(dirname(__FILE__)))); } require_once $contrexx_path . '/core/Core/init.php'; $cx = init('minimal'); $sessionObj = \cmsSession::getInstance(); $_SESSION->cmsSessionStatusUpdate('backend'); $pageId = !empty($_GET['pageId']) ? $_GET['pageId'] : null; //get the main domain $domainRepository = new \Cx\Core\Net\Model\Repository\DomainRepository(); $mainDomain = $domainRepository->getMainDomain()->getName(); //find the right css files and put it into the wysiwyg $em = $cx->getDb()->getEntityManager(); $componentRepo = $em->getRepository('Cx\\Core\\Core\\Model\\Entity\\SystemComponent'); $wysiwyg = $componentRepo->findOneBy(array('name' => 'Wysiwyg')); $pageRepo = $em->getRepository('Cx\\Core\\ContentManager\\Model\\Entity\\Page'); \Cx\Core\Setting\Controller\Setting::init('Wysiwyg', 'config', 'Yaml'); $skinId = 0; if (!empty($pageId) && $pageId != 'new') { $skinId = $pageRepo->find($pageId)->getSkin(); }
/** * Get uploaded zip file by using uploader id * * @param string $uploaderId Uploader id * * @return boolean|string File path when file exists, false otherwise */ public function getUploadedFileFromUploader($uploaderId) { global $sessionObj; if (empty($uploaderId)) { \DBG::log('Uploader id is empty'); return false; } if (empty($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } $uploaderFolder = $sessionObj->getTempPath() . '/' . $uploaderId; if (!\Cx\Lib\FileSystem\FileSystem::exists($uploaderFolder)) { \DBG::log('The Uploader Folder path is invalid/not exists'); return false; } foreach (glob($uploaderFolder . '/*.zip') as $file) { return $file; } return false; }
/** * @param integer $uploadId the upload id of the active upload * @return array */ public static function getTemporaryFilePaths($uploadId) { global $sessionObj; if (!isset($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } return array($_SESSION->getTempPath() . '/', $_SESSION->getWebTempPath() . '/', $uploadId); }
/** * Returns the Shop page for the present parameters * @param string $template The page template * @return string The page content */ static function getPage($template) { //\DBG::activate(DBG_ERROR_FIREPHP); //\DBG::activate(DBG_LOG_FILE); self::init(); self::registerJavascriptCode(); // PEAR Sigma template self::$objTemplate = new \Cx\Core\Html\Sigma('.'); self::$objTemplate->setErrorHandling(PEAR_ERROR_DIE); self::$objTemplate->setTemplate($template); // Global module index for clones self::$objTemplate->setGlobalVariable('MODULE_INDEX', MODULE_INDEX); // Do this *before* calling our friends, especially Customer methods! // Pick the default Country for delivery if (empty($_SESSION['shop']['countryId2'])) { $_SESSION['shop']['countryId2'] = isset($_POST['countryId2']) ? intval($_POST['countryId2']) : \Cx\Core\Setting\Controller\Setting::getValue('country_id', 'Shop'); } // TODO: This should be set up in a more elegant way Vat::is_reseller(self::$objCustomer && self::$objCustomer->is_reseller()); // The coupon code may be set when entering the Shop already if (isset($_REQUEST['coupon_code'])) { global $sessionObj; if (!$sessionObj) { $sessionObj = \cmsSession::getInstance(); } $_SESSION['shop']['coupon_code'] = trim(strip_tags(contrexx_input2raw($_REQUEST['coupon_code']))); //\DBG::log("Coupon Code: Set to ".$_SESSION['shop']['coupon_code']); } //\DBG::log("Shop::getPage(): Entered"); // Global placeholders that are used on (almost) all pages. // Add more as desired. self::$objTemplate->setGlobalVariable(array('SHOP_CURRENCY_CODE' => Currency::getActiveCurrencyCode(), 'SHOP_CURRENCY_SYMBOL' => Currency::getActiveCurrencySymbol())); if (!isset($_GET['cmd'])) { $_GET['cmd'] = ''; } if (!isset($_GET['act'])) { $_GET['act'] = $_GET['cmd']; } switch ($_GET['act']) { case 'shipment': self::showShipmentTerms(); break; case 'success': self::success(); break; case 'confirm': self::confirm(); break; case 'lsv': case 'lsv_form': self::view_lsv_form(); break; case 'payment': self::payment(); break; case 'account': self::view_account(); break; case 'cart': self::cart(); break; case 'discounts': self::discounts(); break; case 'login': self::login(); break; case 'paypalIpnCheck': // OBSOLETE -- Handled by PaymentProcessing::checkIn() now $objPaypal = new \PayPal(); $objPaypal->ipnCheck(); exit; case 'sendpass': self::view_sendpass(); break; case 'changepass': self::_changepass(); break; // Test for PayPal IPN. // *DO NOT* remove this! Needed for site testing. // Test for PayPal IPN. // *DO NOT* remove this! Needed for site testing. case 'testIpn': \PayPal::testIpn(); // die()s! // Test for PayPal IPN validation // *DO NOT* remove this! Needed for site testing. // die()s! // Test for PayPal IPN validation // *DO NOT* remove this! Needed for site testing. case 'testIpnValidate': \PayPal::testIpnValidate(); // die()s! // Test mail body generation // *DO NOT* remove this! Needed for site testing. // die()s! // Test mail body generation // *DO NOT* remove this! Needed for site testing. case 'testMail': // Test with // http://localhost/contrexx_300/de/index.php?section=Shop&act=testMail&key=&order_id=5 //MailTemplate::errorHandler();die(); $order_id = !empty($_GET['order_id']) ? $_GET['order_id'] : 10; $key = !empty($_GET['key']) ? $_GET['key'] : 'order_confirmation'; $arrSubstitution = Orders::getSubstitutionArray($order_id); $customer_id = $arrSubstitution['CUSTOMER_ID']; $objCustomer = Customer::getById($customer_id); if (!$objCustomer) { die("Failed to get Customer for ID {$customer_id}"); return false; } $arrSubstitution += $objCustomer->getSubstitutionArray($customer_id) + self::getSubstitutionArray(); $arrMailTemplate = array('section' => 'Shop', 'key' => $key, 'lang_id' => $arrSubstitution['LANG_ID'], 'substitution' => &$arrSubstitution, 'to' => '*****@*****.**'); \DBG::activate(DBG_LOG_FIREPHP); // DBG::activate(DBG_LOG_FILE); die(nl2br(contrexx_raw2xhtml(var_export($arrMailTemplate, true)))); // DBG::log(MailTemplate::send($arrMailTemplate) ? "Sent successfully" : "Sending FAILED!"); // DBG::deactivate(DBG_LOG_FILE); break; case 'testAttachment': \Cx\Core\MailTemplate\Controller\MailTemplate::send(array('from' => '*****@*****.**', 'to' => '*****@*****.**', 'subject' => 'Test Attachment', 'message' => 'Test', 'attachments' => array(0 => 'images/content/banner/qualidator.gif', 'images/content/banner/itnews.gif' => 'Sch�nes Bild'))); die("Done!"); case 'pricelist': self::send_pricelist(); break; case 'terms': // Static content only (fttb) break; // TODO: Add Order history view (see History.class.php) // case 'history': // self::view_history(); // break; // TODO: Add Order history view (see History.class.php) // case 'history': // self::view_history(); // break; case 'destroy': self::destroyCart(); // TODO: Experimental // self::destroyCart(true); // No break on purpose // TODO: Experimental // self::destroyCart(true); // No break on purpose case 'lastFive': case 'products': default: self::view_product_overview(); } // Note that the Shop Navbar *MUST* be set up *after* the request // has been processed, otherwise the cart info won't be up to date! self::setNavbar(); // TODO: Set the Messages in the global template instead when that's ready \Message::show(self::$objTemplate); //\DBG::deactivate(); return self::$objTemplate->get(); }
/** * @covers \Cx\Core\Json\Adapter\Block\JsonBlock::saveBlockContent */ public function testSaveBlockContent() { global $sessionObj; $sessionObj = !$sessionObj ? \cmsSession::getInstance() : $sessionObj; $user = \FWUser::getFWUserObject()->objUser->getUser(1); \FWUser::loginUser($user); $jsonBlock = new JsonBlock(); $jsonBlock->saveBlockContent(array('get' => array('block' => 32, 'lang' => 'de'), 'post' => array('content' => 'bla'))); $result = $jsonBlock->getBlockContent(array('get' => array('block' => 32, 'lang' => 'de'))); $this->assertEquals('bla', $result['content']); }
/** * Move the uploaded images into place and link to the user * * @param \User $objUser \User object * @param array $arrProfile Array profile data * @param array $arrImages Uploaded images array * @param string $uploaderId Uploader id * * @return boolean TRUE on success false otherwise */ protected function addUploadedImagesToProfile($objUser, &$arrProfile, $arrImages, $uploaderId) { global $_CORELANG; $objSession = \cmsSession::getInstance(); $arrErrorMsg = array(); foreach ($arrImages as $attribute => $arrHistories) { foreach ($arrHistories as $historyId => $data) { $arrUploadedImages = array(); if ($historyId === 'new') { foreach ($data as $historyIndex => $filePath) { $arrUploadedImages[] = array('path' => contrexx_input2raw($filePath), 'history_index' => $historyIndex); } } else { $arrUploadedImages[] = array('path' => contrexx_input2raw($data)); } foreach ($arrUploadedImages as $arrImage) { $fileName = basename($arrImage['path']); $path = $objSession->getTempPath() . '/' . contrexx_input2raw($uploaderId) . '/' . $fileName; if (!\Cx\Lib\FileSystem\FileSystem::exists($path) || !\FWValidator::is_file_ending_harmless($path)) { continue; } $fileSize = filesize($path); if (!$this->isImageWithinAllowedSize($fileSize, $attribute == 'picture')) { $objAttribute = $objUser->objAttribute->getById($attribute); $arrErrorMsg[] = sprintf($_CORELANG['TXT_ACCESS_PIC_TOO_BIG'], htmlentities($objAttribute->getName(), ENT_QUOTES, CONTREXX_CHARSET)); continue; } // resize image and put it into place (ASCMS_ACCESS_PHOTO_IMG_PATH / ASCMS_ACCESS_PROFILE_IMG_PATH) if (($imageName = $this->moveUploadedImageInToPlace($objUser, $path, $fileName, $attribute == 'picture')) === false) { continue; } // create thumbnail if ($this->createThumbnailOfImage($imageName, $attribute == 'picture') !== false) { if ($historyId === 'new') { $arrProfile[$attribute][$historyId][$arrImage['history_index']] = $imageName; } else { $arrProfile[$attribute][$historyId] = $imageName; } } } } } if (count($arrErrorMsg)) { return $arrErrorMsg; } else { return true; } }