/**
  * Create all the thumbnails for a picture.
  *
  * @param string        $path Path to the file. This can be a virtual path or a absolute path.
  * @param string        $fileNamePlain Plain file name without extension
  * @param string        $fileExtension Extension of the file
  * @param \ImageManager $imageManager
  *
  * <code>
  * <?php
  * \Cx\Core_Modules\MediaBrowser\Model\FileSystem::createThumbnail(
  *      'files/',
  *      'Django,
  *      'jpg',
  *      new ImageManager() // Please recycle the instance and don't create a new anonymous instance for each call.
  *                         // This is just a simple example.
  * );
  * ?>
  * </code>
  *
  * @return array With all thumbnail types and if they were generated successfully.
  */
 public static function createThumbnail($path, $fileNamePlain, $fileExtension, \ImageManager $imageManager, $generateThumbnailByRatio = false)
 {
     $success = array();
     foreach (UploaderConfiguration::getInstance()->getThumbnails() as $thumbnail) {
         if (\Cx\Lib\FileSystem\FileSystem::exists(MediaSourceManager::getAbsolutePath($path) . $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension)) {
             $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_NEUTRAL;
             continue;
         }
         if ($imageManager->_createThumb(MediaSourceManager::getAbsolutePath($path) . '/', '', $fileNamePlain . '.' . $fileExtension, $thumbnail['size'], $thumbnail['quality'], $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension, $generateThumbnailByRatio)) {
             $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_SUCCESS;
             continue;
         }
         $success[$thumbnail['value']] = self::THUMBNAIL_GENERATOR_FAIL;
     }
     return $success;
 }
예제 #2
0
 function handleSignUp($objUser)
 {
     global $_ARRAYLANG, $_CONFIG, $_LANGID;
     $objFWUser = \FWUser::getFWUserObject();
     $objUserMail = $objFWUser->getMail();
     $arrSettings = \User_Setting::getSettings();
     if ($arrSettings['user_activation']['status']) {
         $mail2load = 'reg_confirm';
         $mail2addr = $objUser->getEmail();
     } else {
         $mail2load = 'new_user';
         $mail2addr = $arrSettings['notification_address']['value'];
     }
     if (($objUserMail->load($mail2load, $_LANGID) || $objUserMail->load($mail2load)) && \Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php') && ($objMail = new \PHPMailer()) !== false) {
         if ($_CONFIG['coreSmtpServer'] > 0 && \Env::get('ClassLoader')->loadFile(ASCMS_CORE_PATH . '/SmtpSettings.class.php')) {
             if (($arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) {
                 $objMail->IsSMTP();
                 $objMail->Host = $arrSmtp['hostname'];
                 $objMail->Port = $arrSmtp['port'];
                 $objMail->SMTPAuth = true;
                 $objMail->Username = $arrSmtp['username'];
                 $objMail->Password = $arrSmtp['password'];
             }
         }
         $objMail->CharSet = CONTREXX_CHARSET;
         $objMail->SetFrom($objUserMail->getSenderMail(), $objUserMail->getSenderName());
         $objMail->Subject = $objUserMail->getSubject();
         $isTextMail = in_array($objUserMail->getFormat(), array('multipart', 'text'));
         $isHtmlMail = in_array($objUserMail->getFormat(), array('multipart', 'html'));
         $searchTerms = array('[[HOST]]', '[[USERNAME]]', '[[ACTIVATION_LINK]]', '[[HOST_LINK]]', '[[SENDER]]', '[[LINK]]');
         $replaceTextTerms = array($_CONFIG['domainUrl'], $objUser->getUsername(), 'http://' . $_CONFIG['domainUrl'] . CONTREXX_SCRIPT_PATH . '?section=Access&cmd=signup&u=' . $objUser->getId() . '&k=' . $objUser->getRestoreKey(), 'http://' . $_CONFIG['domainUrl'], $objUserMail->getSenderName(), 'http://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . ASCMS_BACKEND_PATH . '/index.php?cmd=Access&act=user&tpl=modify&id=' . $objUser->getId());
         $replaceHtmlTerms = array($_CONFIG['domainUrl'], contrexx_raw2xhtml($objUser->getUsername()), 'http://' . $_CONFIG['domainUrl'] . CONTREXX_SCRIPT_PATH . '?section=Access&cmd=signup&u=' . $objUser->getId() . '&k=' . $objUser->getRestoreKey(), 'http://' . $_CONFIG['domainUrl'], contrexx_raw2xhtml($objUserMail->getSenderName()), 'http://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . ASCMS_BACKEND_PATH . '/index.php?cmd=Access&act=user&tpl=modify&id=' . $objUser->getId());
         if ($mail2load == 'reg_confirm') {
             $imagePath = 'http://' . $_CONFIG['domainUrl'] . \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesAccessProfileWebPath() . '/';
             $objUser->objAttribute->first();
             while (!$objUser->objAttribute->EOF) {
                 $objAttribute = $objUser->objAttribute->getById($objUser->objAttribute->getId());
                 $placeholderName = strtoupper($objUser->objAttribute->getId());
                 $searchTerms[] = '[[USER_' . $placeholderName . ']]';
                 $placeholderValue = $this->parseAttribute($objUser, $objAttribute->getId(), 0, false, true);
                 if ($objAttribute->getType() == 'image' && $objAttribute->getId() == 'picture') {
                     $path = $imagePath . '0_noavatar.gif';
                     $imgName = $objUser->getProfileAttribute($objAttribute->getId());
                     if (\Cx\Lib\FileSystem\FileSystem::exists($imagePath . $imgName)) {
                         $path = $imagePath . $imgName;
                     }
                     $replaceHtmlTerms[] = \Html::getImageByPath($path, 'alt="' . $objUser->getEmail() . '"');
                     $replaceTextTerms[] = $path;
                 } else {
                     if (in_array($objUser->objAttribute->getType(), array('text', 'menu'))) {
                         $replaceTextTerms[] = html_entity_decode($placeholderValue, ENT_QUOTES, CONTREXX_CHARSET);
                         $replaceHtmlTerms[] = html_entity_decode($placeholderValue, ENT_QUOTES, CONTREXX_CHARSET);
                     } else {
                         $replaceTextTerms[] = $placeholderValue;
                         $replaceHtmlTerms[] = $placeholderValue;
                     }
                 }
                 $objUser->objAttribute->next();
             }
         }
         if ($isTextMail) {
             $objUserMail->getFormat() == 'text' ? $objMail->IsHTML(false) : false;
             $objMail->{($objUserMail->getFormat() == 'text' ? '' : 'Alt') . 'Body'} = str_replace($searchTerms, $replaceTextTerms, $objUserMail->getBodyText());
         }
         if ($isHtmlMail) {
             $objUserMail->getFormat() == 'html' ? $objMail->IsHTML(true) : false;
             $objMail->Body = str_replace($searchTerms, $replaceHtmlTerms, $objUserMail->getBodyHtml());
         }
         $objMail->AddAddress($mail2addr);
         if ($objMail->Send()) {
             $this->arrStatusMsg['ok'][] = $_ARRAYLANG['TXT_ACCESS_ACCOUNT_SUCCESSFULLY_CREATED'];
             if ($arrSettings['user_activation']['status']) {
                 $timeoutStr = '';
                 if ($arrSettings['user_activation_timeout']['status']) {
                     if ($arrSettings['user_activation_timeout']['value'] > 1) {
                         $timeoutStr = $arrSettings['user_activation_timeout']['value'] . ' ' . $_ARRAYLANG['TXT_ACCESS_HOURS_IN_STR'];
                     } else {
                         $timeoutStr = ' ' . $_ARRAYLANG['TXT_ACCESS_HOUR_IN_STR'];
                     }
                     $timeoutStr = str_replace('%TIMEOUT%', $timeoutStr, $_ARRAYLANG['TXT_ACCESS_ACTIVATION_TIMEOUT']);
                 }
                 $this->arrStatusMsg['ok'][] = str_replace('%TIMEOUT%', $timeoutStr, $_ARRAYLANG['TXT_ACCESS_ACTIVATION_BY_USER_MSG']);
             } else {
                 $this->arrStatusMsg['ok'][] = str_replace("%HOST%", $_CONFIG['domainUrl'], $_ARRAYLANG['TXT_ACCESS_ACTIVATION_BY_SYSTEM']);
             }
             return true;
         }
     }
     $mailSubject = str_replace("%HOST%", "http://" . $_CONFIG['domainUrl'], $_ARRAYLANG['TXT_ACCESS_COULD_NOT_SEND_ACTIVATION_MAIL']);
     $adminEmail = '<a href="mailto:' . $_CONFIG['coreAdminEmail'] . '?subject=' . $mailSubject . '" title="' . $_CONFIG['coreAdminEmail'] . '">' . $_CONFIG['coreAdminEmail'] . '</a>';
     $this->arrStatusMsg['error'][] = str_replace("%EMAIL%", $adminEmail, $_ARRAYLANG['TXT_ACCESS_COULD_NOT_SEND_EMAIL']);
     return false;
 }
예제 #3
0
 /**
  * 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;
 }
예제 #4
0
 /**
  * Get thumbnails
  *
  * Get the thumbnails from a day in the archive.
  * Create the thumbnails if they don't already exists.
  *
  * @return  boolean TRUE if the thumbs have been loaded, otherwise FALSE
  */
 protected function _getThumbs()
 {
     // set and sanitize the archive path
     $path = \Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . $this->camSettings['archivePath'] . '/' . $this->date . '/';
     $path = \Cx\Lib\FileSystem\FileSystem::sanitizePath($path);
     // set and sanitize the thumbnail path
     $thumbPath = \Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . $this->camSettings['thumbnailPath'];
     $thumbPath = \Cx\Lib\FileSystem\FileSystem::sanitizePath($thumbPath);
     if (!$path || !$thumbPath) {
         return false;
     }
     $objDirectory = @opendir($path);
     $chmoded = false;
     if (!$objDirectory) {
         return false;
     }
     while ($file = readdir($objDirectory)) {
         if ($file != "." && $file != "..") {
             //check and create thumbs
             $thumb = $thumbPath . '/tn_' . $this->date . '_' . $file;
             if (!\Cx\Lib\FileSystem\FileSystem::exists($thumb)) {
                 if (!$chmoded) {
                     \Cx\Lib\FileSystem\FileSystem::makeWritable($this->camSettings['thumbnailPath']);
                     $chmoded = true;
                 }
                 //create thumb
                 $im1 = @imagecreatefromjpeg($path . $file);
                 //erstellt ein Abbild im Speicher
                 if ($im1) {
                     /* Pr�fen, ob fehlgeschlagen */
                     // check_jpeg($thumb, $fix=false );
                     $size = getimagesize($path . $file);
                     //ermittelt die Gr��e des Bildes
                     $breite = $size[0];
                     //die Breite des Bildes
                     $hoehe = $size[1];
                     //die H�he des Bildes
                     $breite_neu = $this->camSettings['thumbMaxSize'];
                     //die breite des Thumbnails
                     $factor = $breite / $this->camSettings['thumbMaxSize'];
                     //berechnungsfaktor
                     $hoehe_neu = $size[1] / $factor;
                     //die H�he des Thumbnails
                     //$im2=imagecreate($breite_neu,$hoehe_neu); //Thumbnail im Speicher erstellen
                     $im2 = @imagecreatetruecolor($breite_neu, $hoehe_neu);
                     imagecopyresized($im2, $im1, 0, 0, 0, 0, $breite_neu, $hoehe_neu, $breite, $hoehe);
                     imagejpeg($im2, $thumb);
                     //Thumbnail speichern
                     imagedestroy($im1);
                     //Speicherabbild wieder l�schen
                     imagedestroy($im2);
                     //Speicherabbild wieder l�schen
                 }
             }
             //show pictures
             $minHour = date('G', $this->camSettings['showFrom']);
             $minMinutes = date('i', $this->camSettings['showFrom']);
             $maxHour = date('G', $this->camSettings['showTill']);
             $maxMinutes = date('i', $this->camSettings['showTill']);
             $hour = substr($file, 4, 2);
             $min = substr($file, 13, 2);
             $min = !empty($min) ? $min : "00";
             $time = $hour . ":" . $min . "&nbsp;Uhr";
             $minTime = mktime($minHour, $minMinutes);
             $maxTime = mktime($maxHour, $maxMinutes);
             $nowTime = mktime($hour, $min);
             /*
              * only show archive images if they are in range
              */
             if ($nowTime <= $maxTime && $nowTime >= $minTime) {
                 if ($this->camSettings['shadowboxActivate'] == 1) {
                     $linkUrl = \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteOffsetPath() . $this->camSettings['archivePath'] . '/' . $this->date . '/' . $file;
                 } else {
                     $linkUrl = '[[NODE_LIVECAM]]?file=' . $this->date . '/' . $file;
                 }
                 $arrThumbnail = array('link_url' => $linkUrl, 'image_url' => $this->camSettings['thumbnailPath'] . "/tn_" . $this->date . "_" . $file, 'time' => $time);
                 array_push($this->_arrArchiveThumbs, $arrThumbnail);
             }
         }
     }
     closedir($objDirectory);
     return true;
 }
예제 #5
0
 /**
  * Get thumbnails
  *
  * Get the thumbnails from a day in the archive.
  * Create the thumbnails if they don't already exists.
  *
  * @access private
  */
 function _getThumbs()
 {
     $path = ASCMS_DOCUMENT_ROOT . "/" . $this->camSettings['archivePath'] . '/' . $this->date . '/';
     $objDirectory = @opendir($path);
     $chmoded = false;
     if ($objDirectory) {
         while ($file = readdir($objDirectory)) {
             if ($file != "." && $file != "..") {
                 //check and create thumbs
                 $thumb = ASCMS_DOCUMENT_ROOT . $this->camSettings['thumbnailPath'] . '/tn_' . $this->date . '_' . $file;
                 if (!\Cx\Lib\FileSystem\FileSystem::exists($thumb)) {
                     if (!$chmoded) {
                         \Cx\Lib\FileSystem\FileSystem::chmod($this->camSettings['thumbnailPath'], '777');
                         $chmoded = true;
                     }
                     //create thumb
                     $im1 = @imagecreatefromjpeg($path . $file);
                     //erstellt ein Abbild im Speicher
                     if ($im1) {
                         /* Pr�fen, ob fehlgeschlagen */
                         // check_jpeg($thumb, $fix=false );
                         $size = getimagesize($path . $file);
                         //ermittelt die Gr��e des Bildes
                         $breite = $size[0];
                         //die Breite des Bildes
                         $hoehe = $size[1];
                         //die H�he des Bildes
                         $breite_neu = $this->camSettings['thumbMaxSize'];
                         //die breite des Thumbnails
                         $factor = $breite / $this->camSettings['thumbMaxSize'];
                         //berechnungsfaktor
                         $hoehe_neu = $size[1] / $factor;
                         //die H�he des Thumbnails
                         //$im2=imagecreate($breite_neu,$hoehe_neu); //Thumbnail im Speicher erstellen
                         $im2 = @imagecreatetruecolor($breite_neu, $hoehe_neu);
                         imagecopyresized($im2, $im1, 0, 0, 0, 0, $breite_neu, $hoehe_neu, $breite, $hoehe);
                         imagejpeg($im2, $thumb);
                         //Thumbnail speichern
                         imagedestroy($im1);
                         //Speicherabbild wieder l�schen
                         imagedestroy($im2);
                         //Speicherabbild wieder l�schen
                     }
                 }
                 //show pictures
                 $minHour = date('G', $this->camSettings['showFrom']);
                 $minMinutes = date('i', $this->camSettings['showFrom']);
                 $maxHour = date('G', $this->camSettings['showTill']);
                 $maxMinutes = date('i', $this->camSettings['showTill']);
                 $hour = substr($file, 4, 2);
                 $min = substr($file, 13, 2);
                 $min = !empty($min) ? $min : "00";
                 $time = $hour . ":" . $min . "&nbsp;Uhr";
                 $minTime = mktime($minHour, $minMinutes);
                 $maxTime = mktime($maxHour, $maxMinutes);
                 $nowTime = mktime($hour, $min);
                 /*
                  * only show archive images if they are in range
                  */
                 if ($nowTime <= $maxTime && $nowTime >= $minTime) {
                     if ($this->camSettings['shadowboxActivate'] == 1) {
                         $linkUrl = ASCMS_PATH_OFFSET . $this->camSettings['archivePath'] . '/' . $this->date . '/' . $file;
                     } else {
                         $linkUrl = '?section=Livecam&amp;file=' . $this->date . '/' . $file;
                     }
                     $arrThumbnail = array('link_url' => $linkUrl, 'image_url' => $this->camSettings['thumbnailPath'] . "/tn_" . $this->date . "_" . $file, 'time' => $time);
                     array_push($this->_arrArchiveThumbs, $arrThumbnail);
                 }
             }
         }
         closedir($objDirectory);
     }
 }
예제 #6
0
 /**
  * Show the cameras
  *
  * @access private
  * @global array
  * @global array
  * @global array
  */
 function showCams()
 {
     global $_ARRAYLANG, $_CONFIG, $_CORELANG;
     $this->_pageTitle = $_ARRAYLANG['TXT_SETTINGS'];
     $this->_objTpl->loadTemplateFile('module_livecam_cams.html');
     $amount = $this->arrSettings['amount_of_cams'];
     $cams = $this->getCamSettings();
     $this->_objTpl->setGlobalVariable(array('TXT_SETTINGS' => $_ARRAYLANG['TXT_SETTINGS'], 'TXT_CURRENT_IMAGE_URL' => $_ARRAYLANG['TXT_CURRENT_IMAGE_URL'], 'TXT_ARCHIVE_PATH' => $_ARRAYLANG['TXT_ARCHIVE_PATH'], 'TXT_SAVE' => $_ARRAYLANG['TXT_SAVE'], 'TXT_THUMBNAIL_PATH' => $_ARRAYLANG['TXT_THUMBNAIL_PATH'], 'TXT_SHADOWBOX_ACTIVE' => $_CORELANG['TXT_ACTIVATED'], 'TXT_SHADOWBOX_INACTIVE' => $_CORELANG['TXT_DEACTIVATED'], 'TXT_ACTIVATE_SHADOWBOX' => $_ARRAYLANG['TXT_ACTIVATE_SHADOWBOX'], 'TXT_ACTIVATE_SHADOWBOX_INFO' => $_ARRAYLANG['TXT_ACTIVATE_SHADOWBOX_INFO'], 'TXT_MAKE_A_FRONTEND_PAGE' => $_ARRAYLANG['TXT_MAKE_A_FRONTEND_PAGE'], 'TXT_CURRENT_IMAGE_MAX_SIZE' => $_ARRAYLANG['TXT_CURRENT_IMAGE_MAX_SIZE'], 'TXT_THUMBNAIL_MAX_SIZE' => $_ARRAYLANG['TXT_THUMBNAIL_MAX_SIZE'], 'TXT_CAM' => $_ARRAYLANG['TXT_CAM'], 'TXT_SUCCESS' => $_CORELANG['TXT_SETTINGS_UPDATED'], 'TXT_TO_MODULE' => $_ARRAYLANG['TXT_LIVECAM_TO_MODULE'], 'TXT_SHOWFROM' => $_ARRAYLANG['TXT_LIVECAM_SHOWFROM'], 'TXT_SHOWTILL' => $_ARRAYLANG['TXT_LIVECAM_SHOWTILL'], 'TXT_OCLOCK' => $_ARRAYLANG['TXT_LIVECAM_OCLOCK']));
     for ($i = 1; $i <= $amount; $i++) {
         if ($cams[$i]['shadowboxActivate'] == 1) {
             $shadowboxActive = 'checked="checked"';
             $shadowboxInctive = '';
         } else {
             $shadowboxActive = '';
             $shadowboxInctive = 'checked="checked"';
         }
         try {
             // fetch CMD specific livecam page
             $camUrl = \Cx\Core\Routing\Url::fromModuleAndCmd('Livecam', $i, FRONTEND_LANG_ID, array(), '', false);
         } catch (\Cx\Core\Routing\UrlException $e) {
             // fetch generic livecam page
             $camUrl = \Cx\Core\Routing\Url::fromModuleAndCmd('Livecam');
         }
         $this->_objTpl->setVariable(array('CAM_NUMBER' => $i, 'LIVECAM_CAM_URL' => $camUrl, 'CURRENT_IMAGE_URL' => $cams[$i]['currentImagePath'], 'ARCHIVE_PATH' => $cams[$i]['archivePath'], 'THUMBNAIL_PATH' => $cams[$i]['thumbnailPath'], 'SHADOWBOX_ACTIVE' => $shadowboxActive, 'SHADOWBOX_INACTIVE' => $shadowboxInctive, 'CURRENT_IMAGE_MAX_SIZE' => $cams[$i]['maxImageWidth'], 'THUMBNAIL_MAX_SIZE' => $cams[$i]['thumbMaxSize'], 'HOUR_FROM' => $this->getHourOptions($cams[$i]['showFrom']), 'MINUTE_FROM' => $this->getMinuteOptions($cams[$i]['showFrom']), 'HOUR_TILL' => $this->getHourOptions(!empty($cams[$i]['showTill']) ? $cams[$i]['showTill'] : mktime(23)), 'MINUTE_TILL' => $this->getMinuteOptions(!empty($cams[$i]['showTill']) ? $cams[$i]['showTill'] : mktime(0, 59))));
         if (preg_match("/^https{0,1}:\\/\\//", $cams[$i]['currentImagePath'])) {
             $filepath = $cams[$i]['currentImagePath'];
             $this->_objTpl->setVariable("PATH", $filepath);
             $this->_objTpl->parse("current_image");
         } else {
             $filepath = \Cx\Core\Core\Controller\Cx::instanciate()->getWebsitePath() . $cams[$i]['currentImagePath'];
             if (\Cx\Lib\FileSystem\FileSystem::exists($filepath) && is_file($filepath)) {
                 $this->_objTpl->setVariable("PATH", $cams[$i]['currentImagePath']);
                 $this->_objTpl->parse("current_image");
             } else {
                 $this->_objTpl->hideBlock("current_image");
             }
         }
         $this->_objTpl->parse("cam");
         /*
         $this->_objTpl->setVariable('BLOCK_USE_BLOCK_SYSTEM', $_CONFIG['blockStatus'] == '1' ? 'checked="checked"' : '');
         */
     }
 }
예제 #7
0
 /**
  * Regenerate the thumbnails
  * 
  * @param array $post $_POST values
  */
 protected function generateThumbnail($post)
 {
     // release the locks, session not needed
     $session = \cmsSession::getInstance();
     $session->releaseLocks();
     session_write_close();
     $cx = Cx::instanciate();
     $key = $_GET['key'];
     if (!preg_match("/[A-Z0-9]{5}/i", $key)) {
         die;
     }
     $processFile = $session->getTempPath() . '/progress' . $key . '.txt';
     if (\Cx\Lib\FileSystem\FileSystem::exists($processFile)) {
         die;
     }
     try {
         $objProcessFile = new \Cx\Lib\FileSystem\File($processFile);
         $objProcessFile->touch();
     } catch (\Cx\Lib\FileSystem\FileSystemException $ex) {
         die;
     }
     $recursiveIteratorIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($cx->getWebsiteImagesPath() . '/'), \RecursiveIteratorIterator::SELF_FIRST);
     $jsonFileArray = array();
     $thumbnailList = UploaderConfiguration::getInstance()->getThumbnails();
     $imageManager = new \ImageManager();
     $fileCounter = 0;
     $generalSuccess = true;
     $imageFiles = array();
     foreach ($recursiveIteratorIterator as $file) {
         /**
          * @var $file \SplFileInfo
          */
         $extension = 'Dir';
         if (!$file->isDir()) {
             $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
         }
         $filePathinfo = pathinfo($file->getRealPath());
         $fileNamePlain = $filePathinfo['filename'];
         // set preview if image
         $preview = 'none';
         $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen($cx->getCodeBasePath())), 'name' => $file->getFilename(), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'type' => $file->getType());
         // filters
         if ($fileInfos['name'] == '.' || preg_match('/\\.thumb/', $fileInfos['name']) || $fileInfos['name'] == 'index.php' || 0 === strpos($fileInfos['name'], '.')) {
             continue;
         }
         if (!preg_match("/(jpg|jpeg|gif|png)/i", ucfirst($extension))) {
             continue;
         }
         $imageFiles[] = $file;
     }
     $imageFilesCount = count($imageFiles);
     if ($imageFilesCount == 0) {
         $objProcessFile->write(100);
         die;
     }
     foreach ($imageFiles as $file) {
         /**
          * @var $file \SplFileInfo
          */
         $extension = 'Dir';
         if (!$file->isDir()) {
             $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION));
         }
         $filePathinfo = pathinfo($file->getRealPath());
         $fileNamePlain = $filePathinfo['filename'];
         $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen(ASCMS_PATH)), 'name' => $file->getFilename(), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'type' => $file->getType());
         $filePathinfo = pathinfo($file->getRealPath());
         $fileExtension = isset($filePathinfo['extension']) ? $filePathinfo['extension'] : '';
         $preview = $cx->getCodeBaseOffsetPath() . str_replace($cx->getCodeBaseDocumentRootPath(), '', $file->getRealPath());
         $previewList = array();
         foreach ($thumbnailList as $thumbnail) {
             $previewList[] = str_replace('.' . lcfirst($extension), $thumbnail['value'] . '.' . lcfirst($extension), $preview);
         }
         $allThumbnailsExists = true;
         foreach ($previewList as $previewImage) {
             if (!FileSystem::exists($previewImage)) {
                 $allThumbnailsExists = false;
             }
         }
         if (!$allThumbnailsExists) {
             if ($imageManager->_isImage($file->getRealPath())) {
                 ThumbnailGenerator::createThumbnail($file->getPath(), $fileNamePlain, $fileExtension, $imageManager, true);
             }
         }
         $fileCounter++;
         $objProcessFile->write($fileCounter / $imageFilesCount * 100);
     }
     $objProcessFile->write(100);
     die;
 }
예제 #8
0
 /**
  * Callable on session destroy
  * 
  * @param type $aKey
  * @param type $destroyCookie
  * @return boolean
  */
 function cmsSessionDestroy($aKey, $destroyCookie = true)
 {
     $query = "DELETE FROM " . DBPREFIX . "sessions WHERE sessionid = '" . $aKey . "'";
     \Env::get('db')->Execute($query);
     $query = "DELETE FROM " . DBPREFIX . "session_variable WHERE sessionid = '" . $aKey . "'";
     \Env::get('db')->Execute($query);
     if (\Cx\Lib\FileSystem\FileSystem::exists($this->sessionPath)) {
         \Cx\Lib\FileSystem\FileSystem::delete_folder($this->sessionPath, true);
     }
     if ($destroyCookie) {
         setcookie("PHPSESSID", '', time() - 3600, '/');
     }
     // do not write the session data
     $this->discardChanges = true;
     return true;
 }
 /**
  * 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;
 }
예제 #10
0
 /**
  * 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;
 }
예제 #11
0
 /**
  * Notifies the callback. Invoked on upload completion.
  */
 public function notifyCallback()
 {
     //temporary path where files were uploaded
     $tempDir = '/upload_' . $this->uploadId;
     $tempPath = $_SESSION->getTempPath() . $tempDir;
     $tempWebPath = $_SESSION->getWebTempPath() . $tempDir;
     //we're going to call the callbck, so the data is not needed anymore
     //well... not quite sure. need it again in contact form.
     //TODO: code session cleanup properly if time.
     //$this->cleanupCallbackData();
     $classFile = $this->callbackData[0];
     //call the callback, get return code
     if ($classFile != null) {
         if (!file_exists($classFile)) {
             throw new UploaderException("Class file '{$classFile}' specified for callback does not exist!");
         }
         require_once $this->callbackData[0];
     }
     $originalFileNames = array();
     if (isset($_SESSION['upload']['handlers'][$this->uploadId]['originalFileNames'])) {
         $originalFileNames = $_SESSION['upload']['handlers'][$this->uploadId]['originalFileNames'];
     }
     //various file infos are passed via this array
     $fileInfos = array('originalFileNames' => $originalFileNames);
     $response = null;
     //the response data.
     if (isset($_SESSION['upload']['handlers'][$this->uploadId]['response_data'])) {
         $response = UploadResponse::fromSession($_SESSION['upload']['handlers'][$this->uploadId]['response_data']);
     } else {
         $response = new UploadResponse();
     }
     $ret = call_user_func(array($this->callbackData[1], $this->callbackData[2]), $tempPath, $tempWebPath, $this->getData(), $this->uploadId, $fileInfos, $response);
     //clean up session: we do no longer need the array with the original file names
     unset($_SESSION['upload']['handlers'][$this->uploadId]['originalFileNames']);
     //same goes for the data
     //if(isset($_SESSION['upload']['handlers'][$this->uploadId]['data']))
     // TODO: unset this when closing the uploader dialog, but not before
     //            unset($_SESSION['upload']['handlers'][$this->uploadId]['data']);
     if (\Cx\Lib\FileSystem\FileSystem::exists($tempWebPath)) {
         //the callback could have returned a path where he wants the files moved to
         // check that $ret[1] is not empty is VERY important!!!
         if (!is_null($ret) && !empty($ret[1])) {
             //we need to move the files
             //gather target information
             $path = pathinfo($ret[0]);
             $pathWeb = pathinfo($ret[1]);
             //make sure the target directory is writable
             \Cx\Lib\FileSystem\FileSystem::makeWritable($pathWeb['dirname'] . '/' . $path['basename']);
             //revert $path and $pathWeb to whole path instead of pathinfo path for copying
             $path = $path['dirname'] . '/' . $path['basename'] . '/';
             $pathWeb = $pathWeb['dirname'] . '/' . $pathWeb['basename'] . '/';
             //trailing slash needed for File-class calls
             $tempPath .= '/';
             $tempWebPath .= '/';
             //move everything uploaded to target dir
             $h = opendir($tempPath);
             $im = new \ImageManager();
             while (false != ($f = readdir($h))) {
                 //skip . and ..
                 if ($f == '.' || $f == '..') {
                     continue;
                 }
                 //TODO: if return value = 'error' => react
                 \Cx\Lib\FileSystem\FileSystem::move($tempWebPath . $f, $pathWeb . $f, true);
                 if ($im->_isImage($path . $f)) {
                     $im->_createThumb($path, $pathWeb, $f);
                 }
                 $response->increaseUploadedFilesCount();
             }
             closedir($h);
         } else {
             // TODO: what now????
         }
         //delete the folder
         \Cx\Lib\FileSystem\FileSystem::delete_folder($tempWebPath, true);
     } else {
         // TODO: output error message to user that no files had been uploaded!!!
     }
     $response->uploadFinished();
     $_SESSION['upload']['handlers'][$this->uploadId]['response_data'] = $response->toSessionValue();
 }
예제 #12
0
 /**
  * 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;
 }
예제 #13
0
 /**
  * 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'].'"];';
             }
     */
 }
예제 #14
0
 /**
  * Display a section of settings present in the $arrSettings class array
  *
  * See the description of {@see show()} for details.
  * @param   \Cx\Core\Html\Sigma $objTemplateLocal   The Template object,
  *                                                  by reference
  * @param   string              $section      The optional section header
  *                                            text to add
  * @param   string              $prefix       The optional prefix for
  *                                            language variables.
  *                                            Defaults to 'TXT_'
  * @return  boolean                           True on success, false otherwise
  */
 static function show_section(&$objTemplateLocal, $section = '', $prefix = 'TXT_', $readOnly = false)
 {
     global $_ARRAYLANG, $_CORELANG;
     $arrSettings = self::getCurrentSettings();
     self::verify_template($objTemplateLocal);
     // This is set to multipart if necessary
     $enctype = '';
     $i = 0;
     if ($objTemplateLocal->blockExists('core_setting_row')) {
         $objTemplateLocal->setCurrentBlock('core_setting_row');
     }
     foreach ($arrSettings as $name => $arrSetting) {
         // Determine HTML element for type and apply values and selected
         $element = '';
         $value = $arrSetting['value'];
         $values = self::splitValues($arrSetting['values']);
         $type = $arrSetting['type'];
         // Not implemented yet:
         // Warn if some mandatory value is empty
         if (empty($value) && preg_match('/_mandatory$/', $type)) {
             \Message::warning(sprintf($_CORELANG['TXT_CORE_SETTING_WARNING_EMPTY'], $_ARRAYLANG[$prefix . strtoupper($name)], $name));
         }
         // Warn if some language variable is not defined
         if (empty($_ARRAYLANG[$prefix . strtoupper($name)])) {
             \Message::warning(sprintf($_CORELANG['TXT_CORE_SETTING_WARNING_MISSING_LANGUAGE'], $prefix . strtoupper($name), $name));
         }
         //DBG::log("Value: $value -> align $value_align");
         $isMultiSelect = false;
         switch ($type) {
             //Multiselect dropdown/Dropdown menu
             case self::TYPE_DROPDOWN_MULTISELECT:
                 $isMultiSelect = true;
             case self::TYPE_DROPDOWN:
                 $matches = null;
                 $arrValues = $arrSetting['values'];
                 if (preg_match('/^\\{src:([a-z0-9_\\\\:]+)\\(\\)\\}$/i', $arrSetting['values'], $matches)) {
                     $arrValues = call_user_func($matches[1]);
                 }
                 if (is_string($arrValues)) {
                     $arrValues = self::splitValues($arrValues);
                 }
                 $elementName = $isMultiSelect ? $name . '[]' : $name;
                 $value = $isMultiSelect ? self::splitValues($value) : $value;
                 $elementValue = is_array($value) ? array_flip($value) : $value;
                 $elementAttr = $isMultiSelect ? ' multiple class="chzn-select"' : '';
                 $element = \Html::getSelect($elementName, $arrValues, $elementValue, '', '', 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;' . (!$isMultiSelect && isset($arrValues[$value]) && is_numeric($arrValues[$value]) ? 'text-align: right;' : '') . '"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : '') . $elementAttr);
                 break;
             case self::TYPE_DROPDOWN_USER_CUSTOM_ATTRIBUTE:
                 $element = \Html::getSelect($name, User_Profile_Attribute::getCustomAttributeNameArray(), $arrSetting['value'], '', '', 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : ''));
                 break;
             case self::TYPE_DROPDOWN_USERGROUP:
                 $element = \Html::getSelect($name, UserGroup::getNameArray(), $arrSetting['value'], '', '', 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : ''));
                 break;
             case self::TYPE_WYSIWYG:
                 // These must be treated differently, as wysiwyg editors
                 // claim the full width
                 if ($readOnly) {
                     // TODO: this might be dangerous! should be rewritten probably
                     $element = $value;
                 } else {
                     $element = new \Cx\Core\Wysiwyg\Wysiwyg($name, $value);
                 }
                 $objTemplateLocal->setVariable(array('CORE_SETTING_ROW' => $_ARRAYLANG[$prefix . strtoupper($name)], 'CORE_SETTING_ROWCLASS1' => ++$i % 2 ? '1' : '2'));
                 $objTemplateLocal->parseCurrentBlock();
                 $objTemplateLocal->setVariable(array('CORE_SETTING_ROW' => $element . '<br /><br />', 'CORE_SETTING_ROWCLASS1' => ++$i % 2 ? '1' : '2'));
                 $objTemplateLocal->parseCurrentBlock();
                 // Skip the part below, all is done already
                 continue 2;
             case self::TYPE_FILEUPLOAD:
                 //echo("\Cx\Core\Setting\Controller\Setting::show_section(): Setting up upload for $name, $value<br />");
                 $element = \Html::getInputFileupload($name, $value ? $name : false, Filetype::MAXIMUM_UPLOAD_FILE_SIZE, $arrSetting['values'], 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : ''), true, $value ? $value : 'media/' . (isset($_REQUEST['cmd']) ? $_REQUEST['cmd'] : 'other'));
                 // File uploads must be multipart encoded
                 $enctype = 'enctype="multipart/form-data"';
                 break;
             case self::TYPE_BUTTON:
                 // The button is only available to trigger some event.
                 $event = 'onclick=\'' . 'if (confirm("' . $_ARRAYLANG[$prefix . strtoupper($name) . '_CONFIRM'] . '")) {' . 'document.getElementById("' . $name . '").value=1;' . 'document.formSettings_' . self::$tab_index . '.submit();' . '}\'';
                 //DBG::log("\Cx\Core\Setting\Controller\Setting::show_section(): Event: $event");
                 $element = \Html::getInputButton('__' . $name, $_ARRAYLANG[strtoupper($prefix . $name) . '_LABEL'], 'button', false, $event . ($readOnly ? \Html::ATTRIBUTE_DISABLED : '')) . \Html::getHidden($name, 0, '');
                 //DBG::log("\Cx\Core\Setting\Controller\Setting::show_section(): Element: $element");
                 break;
             case self::TYPE_TEXTAREA:
                 $element = \Html::getTextarea($name, $value, 80, 8, $readOnly ? \Html::ATTRIBUTE_DISABLED : '');
                 //                        'style="width: '.self::DEFAULT_INPUT_WIDTH.'px;'.$value_align.'"');
                 break;
             case self::TYPE_CHECKBOX:
                 $arrValues = self::splitValues($arrSetting['values']);
                 $value_true = current($arrValues);
                 $element = \Html::getCheckbox($name, $value_true, false, in_array($value, $arrValues), '', $readOnly ? \Html::ATTRIBUTE_DISABLED : '');
                 break;
             case self::TYPE_CHECKBOXGROUP:
                 $checked = self::splitValues($value);
                 $element = \Html::getCheckboxGroup($name, $values, $values, $checked, '', '', '<br />', $readOnly ? \Html::ATTRIBUTE_DISABLED : '', '');
                 break;
                 // 20120508 UNTESTED!
             // 20120508 UNTESTED!
             case self::TYPE_RADIO:
                 $checked = $value;
                 $element = \Html::getRadioGroup($name, $values, $checked, '', $readOnly ? \Html::ATTRIBUTE_DISABLED : '');
                 break;
             case self::TYPE_PASSWORD:
                 $element = \Html::getInputPassword($name, $value, 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : ''));
                 break;
                 //datepicker
             //datepicker
             case self::TYPE_DATE:
                 $element = \Html::getDatepicker($name, array('defaultDate' => $value), 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"');
                 break;
                 //datetimepicker
             //datetimepicker
             case self::TYPE_DATETIME:
                 $element = \Html::getDatetimepicker($name, array('defaultDate' => $value), 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;"');
                 break;
             case self::TYPE_IMAGE:
                 $cx = \Cx\Core\Core\Controller\Cx::instanciate();
                 if (!empty($arrSetting['value']) && \Cx\Lib\FileSystem\FileSystem::exists($cx->getWebsitePath() . '/' . $arrSetting['value'])) {
                     $element .= \Html::getImageByPath($cx->getWebsitePath() . '/' . $arrSetting['value'], 'id="' . $name . 'Image" ') . '&nbsp;&nbsp;';
                 }
                 $element .= \Html::getHidden($name, $arrSetting['value'], $name);
                 $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                 $mediaBrowser->setCallback($name . 'Callback');
                 $mediaBrowser->setOptions(array('type' => 'button', 'data-cx-mb-views' => 'filebrowser'));
                 $element .= $mediaBrowser->getXHtml($_ARRAYLANG['TXT_BROWSE']);
                 \JS::registerCode('
                     function ' . $name . 'Callback(data) {
                         if (data.type === "file" && data.data[0]) {
                             var filePath = data.data[0].datainfo.filepath;
                             jQuery("#' . $name . '").val(filePath);
                             jQuery("#' . $name . 'Image").attr("src", filePath);
                         }
                     }
                     jQuery(document).ready(function(){
                         var imgSrc = jQuery("#' . $name . 'Image").attr("src");
                         jQuery("#' . $name . 'Image").attr("src", imgSrc + "?t=" + new Date().getTime());
                     });
                 ');
                 break;
                 // Default to text input fields
             // Default to text input fields
             case self::TYPE_TEXT:
             case self::TYPE_EMAIL:
             default:
                 $element = \Html::getInputText($name, $value, false, 'style="width: ' . self::DEFAULT_INPUT_WIDTH . 'px;' . (is_numeric($value) ? 'text-align: right;' : '') . '"' . ($readOnly ? \Html::ATTRIBUTE_DISABLED : ''));
         }
         //add Tooltip
         $toolTips = '';
         $toolTipsHelp = '';
         if (isset($_ARRAYLANG[$prefix . strtoupper($name) . '_TOOLTIP'])) {
             // generate tooltip for configuration option
             $toolTips = '  <span class="icon-info tooltip-trigger"></span><span class="tooltip-message">' . $_ARRAYLANG[$prefix . strtoupper($name) . '_TOOLTIP'] . '</span>';
         }
         if (isset($_ARRAYLANG[$prefix . strtoupper($name) . '_TOOLTIP_HELP'])) {
             // generate tooltip for configuration option
             $toolTipsHelp = '  <span class="icon-info tooltip-trigger"></span><span class="tooltip-message">' . $_ARRAYLANG[$prefix . strtoupper($name) . '_TOOLTIP_HELP'] . '</span>';
         }
         $objTemplateLocal->setVariable(array('CORE_SETTING_NAME' => (isset($_ARRAYLANG[$prefix . strtoupper($name)]) ? $_ARRAYLANG[$prefix . strtoupper($name)] : $name) . $toolTips, 'CORE_SETTING_VALUE' => $element . $toolTipsHelp, 'CORE_SETTING_ROWCLASS2' => ++$i % 2 ? '1' : '2'));
         $objTemplateLocal->parseCurrentBlock();
         //echo("\Cx\Core\Setting\Controller\Setting::show(objTemplateLocal, $prefix): shown $name => $value<br />");
     }
     // Set form encoding to multipart if necessary
     if (!empty($enctype)) {
         $objTemplateLocal->setVariable('CORE_SETTING_ENCTYPE', $enctype);
     }
     if (!empty($section) && $objTemplateLocal->blockExists('core_setting_section')) {
         //echo("\Cx\Core\Setting\Controller\Setting::show(objTemplateLocal, $header, $prefix): creating section $header<br />");
         $objTemplateLocal->setVariable(array('CORE_SETTING_SECTION' => $section));
         //$objTemplateLocal->parse('core_setting_section');
     }
     return true;
 }
예제 #15
0
 /**
  * Return whether file is valid to show or not
  *
  * @param string $filePath  Folder path to the file
  * @param string $fileName  File name
  *
  * @return boolean True when file is valid to show, False otherwise
  */
 public function isFileValidToShow($filePath, $fileName)
 {
     if (empty($filePath) || empty($fileName) || self::isIllegalFileName($fileName)) {
         return false;
     }
     if (preg_match("/(?:\\.(?:thumb_thumbnail|thumb_medium|thumb_large)\\.[^.]+\$)|(?:\\.thumb)\$/i", $fileName)) {
         $originalFileName = preg_replace("/(?:\\.(?:thumb_thumbnail|thumb_medium|thumb_large)(\\.[^.]+)\$)|(?:\\.thumb)\$/mi", "\$1", $fileName);
         if (!\Cx\Lib\FileSystem\FileSystem::exists($filePath . '/' . $originalFileName)) {
             \Cx\Lib\FileSystem\FileSystem::delete_file($filePath . '/' . $fileName);
         }
         return false;
     }
     return true;
 }
예제 #16
0
 /**
  * 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;
     }
 }
예제 #17
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;
 }
예제 #18
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 '';
 }
예제 #19
0
 function cmsSessionDestroy($aKey)
 {
     $query = "DELETE FROM " . DBPREFIX . "sessions WHERE sessionid = '" . $aKey . "'";
     $this->_objDb->Execute($query);
     if (\Cx\Lib\FileSystem\FileSystem::exists($this->sessionPath)) {
         \Cx\Lib\FileSystem\FileSystem::delete_folder($this->sessionPath, true);
     }
     return true;
 }
예제 #20
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;
 }
예제 #21
0
 /**
  * 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));
 }
예제 #22
0
 /**
  * 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;
 }
예제 #23
0
 /**
  * Create all the thumbnails for a picture.
  *
  * @param string        $path          Path to the file. This can be a virtual path or a absolute path.
  * @param string        $fileNamePlain Plain file name without extension
  * @param string        $fileExtension Extension of the file
  * @param \ImageManager $imageManager
  *
  * <code>
  * <?php
  * \Cx\Core_Modules\MediaBrowser\Model\FileSystem::createThumbnail(
  *      'files/',
  *      'Django,
  *      'jpg',
  *      new ImageManager() // Please recycle the instance and don't create a new anonymous instance for each call.
  *                         // This is just a simple example.
  * );
  * ?>
  * </code>
  *
  * @param bool          $generateThumbnailByRatio
  * @param bool          $force Force creation of new Thumbnails. This overwrites any existing thumbnail.
  *
  * @return array Array with the relative paths to the thumbnails.
  */
 public function createThumbnail($path, $fileNamePlain, $fileExtension, \ImageManager $imageManager, $generateThumbnailByRatio = false, $force = false)
 {
     $thumbnails = array();
     foreach ($this->getThumbnails() as $thumbnail) {
         if ($force) {
             \Cx\Lib\FileSystem\FileSystem::delete_file(MediaSourceManager::getAbsolutePath($path) . '/' . $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension);
         } elseif (\Cx\Lib\FileSystem\FileSystem::exists(MediaSourceManager::getAbsolutePath($path) . '/' . $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension)) {
             $thumbnails[] = $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension;
             continue;
         }
         if ($imageManager->_createThumb(MediaSourceManager::getAbsolutePath($path) . '/', '', $fileNamePlain . '.' . $fileExtension, $thumbnail['size'], $thumbnail['quality'], $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension, $generateThumbnailByRatio)) {
             $thumbnails[] = $fileNamePlain . $thumbnail['value'] . '.' . $fileExtension;
             continue;
         }
     }
     return $thumbnails;
 }
예제 #24
0
 /**
  * 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;
     }
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $objSession = $cx->getComponent('Session')->getSession();
     $uploaderFolder = $objSession->getTempPath() . '/' . $uploaderId;
     if (!\Cx\Lib\FileSystem\FileSystem::exists($uploaderFolder)) {
         return false;
     }
     foreach (glob($uploaderFolder . '/*.csv') as $file) {
         return $file;
     }
     return false;
 }
예제 #25
0
 /**
  * Uploader callback function
  * 
  * @param string  $tempPath    Temp path
  * @param string  $tempWebPath Temp webpath
  * @param string  $data        post data
  * @param integer $uploadId    upload id
  * @param array   $fileInfos   file infos
  * @param object  $response    Upload api response object
  * 
  * @return array $tempPath and $tempWebPath
  */
 public static function uploadFinished($tempPath, $tempWebPath, $data, $uploadId, $fileInfos, $response)
 {
     // Delete existing files because we need only one file to upload
     if (\Cx\Lib\FileSystem\FileSystem::exists($tempPath)) {
         foreach (glob($tempPath . '/*') as $file) {
             if (basename($file) == $fileInfos['name']) {
                 continue;
             }
             \Cx\Lib\FileSystem\FileSystem::delete_file($file);
         }
     }
     return array($tempPath, $tempWebPath);
 }
예제 #26
0
 /**
  * create new file or folder
  * 
  * @param array $params supplied arguments from JsonData-request
  * @return string
  */
 public function newWithin($params)
 {
     global $_ARRAYLANG, $objInit;
     $_ARRAYLANG = $objInit->loadLanguageData('ViewManager');
     if (empty($params['post']['theme']) || empty($params['post']['name'])) {
         return array('status' => 'error', 'message' => $_ARRAYLANG['TXT_THEME_OPERATION_FAILED_FOR_EMPTY_NAME']);
     }
     if ($params['post']['isFolder'] && preg_match('/^\\./', trim($params['post']['name']))) {
         // folder name should not start with dot(.)
         return array('status' => 'error', 'reload' => false, 'message' => sprintf($_ARRAYLANG['TXT_THEME_FOLDER_NAME_NOT_ALLOWED'], contrexx_input2xhtml($params['post']['name'])));
     }
     $matches = null;
     preg_match('@{([0-9A-Za-z._-]+)(:([_a-zA-Z][A-Za-z_0-9]*))?}@sm', $params['post']['name'], $matches);
     if (!empty($matches)) {
         return array('status' => 'error', 'reload' => false, 'message' => sprintf($_ARRAYLANG['TXT_THEME_NAME_NOT_ALLOWED'], contrexx_input2xhtml($params['post']['newName'])));
     }
     // Cannot rename the virtual directory
     $virtualDirs = array('/' . \Cx\Core\Core\Model\Entity\SystemComponent::TYPE_CORE_MODULE, '/' . \Cx\Core\Core\Model\Entity\SystemComponent::TYPE_MODULE, '/' . \Cx\Core\Core\Model\Entity\SystemComponent::TYPE_CORE);
     $currentThemeFolderDirPath = \Env::get('cx')->getWebsiteThemesPath() . '/' . $params['post']['theme'] . '/';
     // Create the theme folder, if it does not exist
     if (!\Cx\Lib\FileSystem\FileSystem::exists($currentThemeFolderDirPath)) {
         if (!\Cx\Lib\FileSystem\FileSystem::make_folder($currentThemeFolderDirPath)) {
             return array('status' => 'error', 'reload' => false, 'message' => $_ARRAYLANG['TXT_THEME_NEWFILE_FAILED']);
         }
     }
     $newFileName = \Cx\Lib\FileSystem\FileSystem::replaceCharacters($params['post']['name']);
     if (!\FWValidator::is_file_ending_harmless($newFileName)) {
         return array('status' => 'error', 'reload' => false, 'message' => sprintf($_ARRAYLANG['TXT_THEME_FILE_EXTENSION_NOT_ALLOWED'], contrexx_input2xhtml($newFileName)));
     }
     if (in_array('/' . $newFileName, $virtualDirs)) {
         return array('status' => 'error', 'reload' => false, 'message' => $_ARRAYLANG['TXT_THEME_OPERATION_FAILED_FOR_VIRTUAL_FOLDER']);
     }
     if (!\Cx\Lib\FileSystem\FileSystem::exists($currentThemeFolderDirPath . $newFileName)) {
         if ($params['post']['isFolder']) {
             $status = \Cx\Lib\FileSystem\FileSystem::make_folder($currentThemeFolderDirPath . $newFileName);
             $succesMessage = sprintf($_ARRAYLANG['TXT_THEME_FOLDER_CREATE_SUCCESS'], contrexx_input2xhtml($newFileName));
         } else {
             $status = \Cx\Lib\FileSystem\FileSystem::touch($currentThemeFolderDirPath . $newFileName);
             $succesMessage = sprintf($_ARRAYLANG['TXT_THEME_FILE_CREATE_SUCCESS'], contrexx_input2xhtml($newFileName));
         }
         if (!$status) {
             return array('status' => 'error', 'message' => $_ARRAYLANG['TXT_THEME_NEWFILE_FAILED']);
         }
         return array('status' => 'success', 'reload' => true, 'message' => $succesMessage, 'path' => '/' . $newFileName);
     }
     return array('status' => 'error', 'message' => sprintf($_ARRAYLANG['TXT_THEME_OPERATION_FAILED_FOR_FILE_ALREADY_EXITS'], contrexx_input2xhtml($newFileName)));
 }
예제 #27
0
 /**
  * Uploader callback function
  *
  * This is called as soon as uploads have finished.
  *
  * @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    upload id
  * @param array   $fileInfos   uploaded file informations
  * @param object  $response    Upload api response object
  *
  * @return array $tempPath and $tempWebPath
  */
 public static function uploadFinished($tempPath, $tempWebPath, $data, $uploadId, $fileInfos, $response)
 {
     // in case uploader has been restricted to only allow one single file to be
     // uploaded, we'll have to clean up any previously uploaded files
     if (count($fileInfos['name'])) {
         // new files have been uploaded -> remove existing files
         if (\Cx\Lib\FileSystem\FileSystem::exists($tempPath)) {
             foreach (glob($tempPath . '/*') as $file) {
                 if (basename($file) == $fileInfos['name']) {
                     continue;
                 }
                 \Cx\Lib\FileSystem\FileSystem::delete_file($file);
             }
         }
     }
     return array($tempPath, $tempWebPath);
 }
 /**
  * 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)
 {
     if (empty($uploaderId) || empty($fileName)) {
         return false;
     }
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $sessionObj = $cx->getComponent('Session')->getSession();
     $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;
 }
예제 #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
 /**
  * Stores the posted Product, if any
  * @return  boolean           True on success, null on noop, false otherwise
  */
 static function store_product()
 {
     global $_ARRAYLANG;
     if (!isset($_POST['bstore'])) {
         return null;
     }
     $product_name = contrexx_input2raw($_POST['product_name']);
     $product_code = contrexx_input2raw($_POST['product_code']);
     // Multiple Categories
     $category_id = isset($_POST['shopCategoriesAssigned']) ? contrexx_input2raw(join(',', $_POST['shopCategoriesAssigned'])) : '';
     $customer_price = $_POST['customer_price'];
     $reseller_price = $_POST['reseller_price'];
     $discount_active = !empty($_POST['discount_active']);
     $discount_price = $_POST['discount_price'];
     //DBG::log("ShopManager::store_product(): customer_price $customer_price, reseller_price $reseller_price, discount_price $discount_price");
     $vat_id = $_POST['vat_id'];
     $short = contrexx_input2raw($_POST['short']);
     $long = contrexx_input2raw($_POST['long']);
     $stock = $_POST['stock'];
     $stock_visible = !empty($_POST['stock_visible']);
     $uri = contrexx_input2raw($_POST['uri']);
     $active = !empty($_POST['articleActive']);
     $b2b = !empty($_POST['B2B']);
     $b2c = !empty($_POST['B2C']);
     $date_start = contrexx_input2raw($_POST['date_start']);
     $date_end = contrexx_input2raw($_POST['date_end']);
     $manufacturer_id = isset($_POST['manufacturer_id']) ? contrexx_input2int($_POST['manufacturer_id']) : 0;
     $minimum_order_quantity = $_POST['minimum_order_quantity'];
     // Currently not used on the detail page
     //        $flags = (isset($_POST['Flags'])
     //                ? join(' ', $_POST['Flags']) : '');
     $distribution = $_POST['distribution'];
     // Different meaning of the "weight" field for downloads!
     // The getWeight() method will treat purely numeric values
     // like the validity period (in days) the same as a weight
     // without its unit and simply return its integer value.
     $weight = $distribution == 'delivery' ? Weight::getWeight($_POST['weight']) : $_POST['accountValidity'];
     // Assigned frontend groups for protected downloads
     $usergroup_ids = isset($_POST['groupsAssigned']) ? implode(',', $_POST['groupsAssigned']) : '';
     $discount_group_count_id = $_POST['discount_group_count_id'];
     $discount_group_article_id = $_POST['discount_group_article_id'];
     //DBG::log("ShopManager::store_product(): Set \$discount_group_article_id to $discount_group_article_id");
     $keywords = contrexx_input2raw($_POST['keywords']);
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     for ($i = 1; $i <= 3; ++$i) {
         // Images outside the above directory are copied to the shop image folder.
         // Note that the image paths below do not include the document root, but
         // are relative to it.
         $picture = contrexx_input2raw($_POST['productImage' . $i]);
         // Ignore the picture if it's the default image!
         // Storing it would be pointless.
         // Images outside the above directory are copied to the shop image folder.
         // Note that the image paths below do not include the document root, but
         // are relative to it.
         if ($picture == self::$defaultImage || !self::moveImage($picture)) {
             $picture = '';
         }
         // Update the posted path (used below)
         $_POST['productImage' . $i] = $picture;
         //Set the image width and height If empty
         if (!empty($_POST['productImage' . $i . '_width']) && !empty($_POST['productImage' . $i . '_height'])) {
             continue;
         }
         $picturePath = $cx->getWebsiteImagesShopPath() . '/' . $picture;
         if (!\Cx\Lib\FileSystem\FileSystem::exists($picturePath)) {
             continue;
         }
         $pictureSize = getimagesize($picturePath);
         $_POST['productImage' . $i . '_width'] = $pictureSize[0];
         $_POST['productImage' . $i . '_height'] = $pictureSize[1];
     }
     // add all to pictures DBstring
     $imageName = base64_encode($_POST['productImage1']) . '?' . base64_encode($_POST['productImage1_width']) . '?' . base64_encode($_POST['productImage1_height']) . ':' . base64_encode($_POST['productImage2']) . '?' . base64_encode($_POST['productImage2_width']) . '?' . base64_encode($_POST['productImage2_height']) . ':' . base64_encode($_POST['productImage3']) . '?' . base64_encode($_POST['productImage3_width']) . '?' . base64_encode($_POST['productImage3_height']);
     // Note that the flags of the Product *MUST NOT* be changed
     // when inserting or updating the Product data, as the original
     // flags are needed for their own update later.
     $objProduct = null;
     $product_id = intval($_POST['id']);
     if ($product_id) {
         $objProduct = Product::getById($product_id);
     }
     $new = false;
     if (!$objProduct) {
         $new = true;
         $objProduct = new Product($product_code, $category_id, $product_name, $distribution, $customer_price, $active, 0, $weight);
         if (!$objProduct->store()) {
             return \Message::error($_ARRAYLANG['TXT_SHOP_PRODUCT_ERROR_STORING']);
         }
         //            $product_id = $objProduct->id();
     }
     // Apply the changes to all Products with the same Product code.
     // Note: This is disabled for the time being, as virtual categories are, too.
     //        if ($product_code != '') {
     //            $arrProduct = Products::getByCustomId($product_code);
     //        } else {
     //            $arrProduct = array($objProduct);
     //        }
     //        if (!is_array($arrProduct)) return false;
     //        foreach ($arrProduct as $objProduct) {
     // Update each product
     $objProduct->code($product_code);
     // NOTE: Only change the parent ShopCategory for a Product
     // that is in a real ShopCategory.
     $objProduct->category_id($category_id);
     $objProduct->name($product_name);
     $objProduct->distribution($distribution);
     $objProduct->price($customer_price);
     $objProduct->active($active);
     // On the overview only: $objProduct->ord();
     $objProduct->weight($weight);
     $objProduct->resellerprice($reseller_price);
     $objProduct->discount_active($discount_active);
     $objProduct->discountprice($discount_price);
     $objProduct->vat_id($vat_id);
     $objProduct->short($short);
     $objProduct->long($long);
     $objProduct->stock($stock);
     $objProduct->minimum_order_quantity($minimum_order_quantity);
     $objProduct->stock_visible($stock_visible);
     $objProduct->uri($uri);
     $objProduct->b2b($b2b);
     $objProduct->b2c($b2c);
     $objProduct->date_start($date_start);
     $objProduct->date_end($date_end);
     $objProduct->manufacturer_id($manufacturer_id);
     $objProduct->pictures($imageName);
     // Currently not used on the detail page
     //                $objProduct->flags($flags);
     $objProduct->usergroup_ids($usergroup_ids);
     $objProduct->group_id($discount_group_count_id);
     $objProduct->article_id($discount_group_article_id);
     $objProduct->keywords($keywords);
     //DBG::log("ShopManager::store_product(): Product: reseller_price ".$objProduct->resellerprice());
     // Remove old Product Attributes.
     // They are re-added below.
     $objProduct->clearAttributes();
     // Add current product attributes
     if (isset($_POST['options']) && is_array($_POST['options'])) {
         foreach ($_POST['options'] as $valueId => $nameId) {
             $order = intval($_POST['productOptionsSortId'][$nameId]);
             $objProduct->addAttribute(intval($valueId), $order);
         }
     }
     // Mind that this will always be an *update*, see the call to
     // store() above.
     if (!$objProduct->store()) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_PRODUCT_ERROR_STORING']);
     }
     //        }
     // Add/remove Categories and Products to/from
     // virtual ShopCategories.
     // Note that this *MUST* be called *AFTER* the Product is updated
     // or inserted.
     // Virtual categories are disabled for the time being
     //        Products::changeFlagsByProductCode(
     //            $product_code, $flags
     //        );
     $objImage = new \ImageManager();
     $arrImages = Products::get_image_array_from_base64($imageName);
     // Create thumbnails if not available, or update them
     foreach ($arrImages as $arrImage) {
         if (!empty($arrImage['img']) && $arrImage['img'] != ShopLibrary::noPictureName) {
             if (!$objImage->_createThumbWhq(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesShopPath() . '/', \Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteImagesShopWebPath() . '/', $arrImage['img'], \Cx\Core\Setting\Controller\Setting::getValue('thumbnail_max_width', 'Shop'), \Cx\Core\Setting\Controller\Setting::getValue('thumbnail_max_height', 'Shop'), \Cx\Core\Setting\Controller\Setting::getValue('thumbnail_quality', 'Shop'))) {
                 \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_COULD_NOT_CREATE_THUMBNAIL'], $arrImage['img']));
             }
         }
     }
     \Message::ok($new ? $_ARRAYLANG['TXT_DATA_RECORD_ADDED_SUCCESSFUL'] : $_ARRAYLANG['TXT_DATA_RECORD_UPDATED_SUCCESSFUL']);
     switch ($_POST['afterStoreAction']) {
         case 'newEmpty':
             \Cx\Core\Csrf\Controller\Csrf::redirect('index.php?cmd=Shop' . MODULE_INDEX . '&act=products&tpl=manage');
         case 'newTemplate':
             \Cx\Core\Csrf\Controller\Csrf::redirect('index.php?cmd=Shop' . MODULE_INDEX . '&act=products&tpl=manage&id=' . $objProduct->id() . '&new=1');
     }
     \Cx\Core\Csrf\Controller\Csrf::redirect('index.php?cmd=Shop' . MODULE_INDEX . '&act=products');
     // Never reached
     return true;
 }