public function getDownloadElement($strTag)
 {
     $params = preg_split('/::/', $strTag);
     if (is_array($params) && !empty($params)) {
         if (strpos($params[0], 'download') === 0) {
             $singleSRC = strip_tags($params[1]);
             // remove <span> etc, otherwise Validator::isuuid fail
             $objDownload = new \stdClass();
             if (strpos($singleSRC, '/') !== false) {
                 if (($objFile = FilesModel::findByPath($singleSRC)) !== null && $objFile->uuid) {
                     $singleSRC = \StringUtil::binToUuid($objFile->uuid);
                 }
             }
             $objDownload->singleSRC = $singleSRC;
             $objDownload->linkTitle = strip_tags($params[2]);
             // remove <span> etc
             $objDownload->cssID[1] = 'inserttag_download ' . strip_tags($params[3]);
             $objDownload->cssID[0] = strip_tags($params[4]);
             $objContentDownload = new \ContentDownloadInserttag($objDownload);
             $output = $objContentDownload->generate();
             if ($params[0] == 'download') {
                 return $output;
             }
             if ($params[0] == 'download_link') {
                 return $objContentDownload->Template->href;
             }
             if ($params[0] == 'download_size') {
                 return $objContentDownload->Template->filesize;
             }
             return '';
         }
     }
     return false;
 }
 public function __construct($arrAttributes = null)
 {
     // check against arrAttributes, as 'onsubmit_callback' => 'multifileupload_moveFiles' does not provide valid attributes
     if ($arrAttributes !== null && !$arrAttributes['uploadFolder']) {
         throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['noUploadFolderDeclared'], $this->name));
     }
     $arrAttributes['uploadAction'] = static::$uploadAction;
     if (TL_MODE == 'FE') {
         $arrAttributes['uploadActionParams'] = http_build_query(AjaxAction::getParams(MultiFileUpload::NAME, static::$uploadAction));
     }
     $arrAttributes['addRemoveLinks'] = isset($arrAttributes['addRemoveLinks']) ? $arrAttributes['addRemoveLinks'] : true;
     if (!is_array($arrAttributes['value']) && !Validator::isBinaryUuid($arrAttributes['value'])) {
         $arrAttributes['value'] = json_decode($arrAttributes['value']);
     }
     // bin to string -> never pass binary to the widget!!
     if ($arrAttributes['value']) {
         if (is_array($arrAttributes['value'])) {
             $arrAttributes['value'] = array_map(function ($val) {
                 return \Validator::isBinaryUuid($val) ? \StringUtil::binToUuid($val) : $val;
             }, $arrAttributes['value']);
         } else {
             $arrAttributes['value'] = array(\Validator::isBinaryUuid($arrAttributes['value']) ? \StringUtil::binToUuid($arrAttributes['value']) : $arrAttributes['value']);
         }
     }
     parent::__construct($arrAttributes);
     $this->objUploader = new MultiFileUpload($arrAttributes);
     // add onsubmit_callback: move files after form submission
     $GLOBALS['TL_DCA'][$this->strTable]['config']['onsubmit_callback']['multifileupload_moveFiles'] = array('HeimrichHannot\\MultiFileUpload\\FormMultiFileUpload', 'moveFiles');
     Ajax::runActiveAction(MultiFileUpload::NAME, MultiFileUpload::ACTION_UPLOAD, $this);
 }
 public static function getDefaultAttachmentSRC($blnReturnPath = false)
 {
     $objFolder = new \Folder('files/submissions/uploads');
     if ($blnReturnPath) {
         return $objFolder->path;
     }
     if (\Validator::isUuid($objFolder->getModel()->uuid)) {
         return class_exists('Contao\\StringUtil') ? \StringUtil::binToUuid($objFolder->getModel()->uuid) : \String::binToUuid($objFolder->getModel()->uuid);
     }
     return null;
 }
 /**
  * {@inheritDoc}
  */
 public function format($value, $fieldName, array $fieldDefinition, $context = null)
 {
     if (is_array($value)) {
         $value = array_values(array_filter(array_map(function ($value) {
             return $value ? \StringUtil::binToUuid($value) : '';
         }, $value)));
     } else {
         $value = $value ? \StringUtil::binToUuid($value) : '';
     }
     return $value;
 }
 /**
  * Save callback for the DCA fields.
  * Converts any file path to a {{file::*}} insert tag.
  *
  * @param mixed $varValue The ipnut value
  *
  * @return string The processed value
  */
 public function saveCallback($varValue)
 {
     // search for the file
     if (($objFile = \FilesModel::findOneByPath(urldecode($varValue))) !== null) {
         // convert the uuid
         if (version_compare(VERSION . '.' . BUILD, '3.5.1', '<')) {
             $uuid = \String::binToUuid($objFile->uuid);
         } else {
             $uuid = \StringUtil::binToUuid($objFile->uuid);
         }
         // convert to insert tag
         $varValue = "{{file::{$uuid}}}";
     }
     // return the value
     return $varValue;
 }
 /**
  * Send a lost password e-mail
  *
  * @param \MemberModel $objMember
  */
 protected function sendPasswordLink($objMember)
 {
     $objNotification = \NotificationCenter\Model\Notification::findByPk($this->nc_notification);
     if ($objNotification === null) {
         $this->log('The notification was not found ID ' . $this->nc_notification, __METHOD__, TL_ERROR);
         return;
     }
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store the confirmation ID
     $objMember = \MemberModel::findByPk($objMember->id);
     $objMember->activation = $confirmationId;
     $objMember->save();
     $arrTokens = array();
     // Add member tokens
     foreach ($objMember->row() as $k => $v) {
         if (\Validator::isBinaryUuid($v)) {
             $v = \StringUtil::binToUuid($v);
         }
         $arrTokens['member_' . $k] = specialchars($v);
     }
     // FIX: Add salutation token
     $arrTokens['salutation_user'] = NotificationCenterPlus::createSalutation($GLOBALS['TL_LANGUAGE'], $objMember);
     // ENDFIX
     $arrTokens['recipient_email'] = $objMember->email;
     $arrTokens['domain'] = \Idna::decode(\Environment::get('host'));
     $arrTokens['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $confirmationId;
     // FIX: Add custom change password jump to
     if (($objJumpTo = $this->objModel->getRelated('changePasswordJumpTo')) !== null) {
         $arrTokens['link'] = \Idna::decode(\Environment::get('base')) . \Controller::generateFrontendUrl($objJumpTo->row(), '?token=' . $confirmationId);
     }
     // ENDFIX
     $objNotification->send($arrTokens, $GLOBALS['TL_LANGUAGE']);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . $objMember->email . ')', __METHOD__, TL_ACCESS);
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     StatusMessage::addSuccess(sprintf($GLOBALS['TL_LANG']['notification_center_plus']['sendPasswordLink']['messageSuccess'], $arrTokens['recipient_email']), $this->objModel->id);
     $this->reload();
 }
Пример #7
0
 /**
  * Validate the input and set the value
  */
 public function validate()
 {
     // No file specified
     if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) {
         if ($this->mandatory) {
             if ($this->strLabel == '') {
                 $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']);
             } else {
                 $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel));
             }
         }
         return;
     }
     $file = $_FILES[$this->strName];
     $maxlength_kb = $this->getMaximumUploadSize();
     $maxlength_kb_readable = $this->getReadableSize($maxlength_kb);
     // Sanitize the filename
     try {
         $file['name'] = \StringUtil::sanitizeFileName($file['name']);
     } catch (\InvalidArgumentException $e) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['filename']);
         return;
     }
     // Invalid file name
     if (!\Validator::isValidFileName($file['name'])) {
         $this->addError($GLOBALS['TL_LANG']['ERR']['filename']);
         return;
     }
     // File was not uploaded
     if (!is_uploaded_file($file['tmp_name'])) {
         if ($file['error'] == 1 || $file['error'] == 2) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable));
         } elseif ($file['error'] == 3) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name']));
         } elseif ($file['error'] > 0) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileerror'], $file['error'], $file['name']));
         }
         unset($_FILES[$this->strName]);
         return;
     }
     // File is too big
     if ($file['size'] > $maxlength_kb) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb_readable));
         unset($_FILES[$this->strName]);
         return;
     }
     $objFile = new \File($file['name']);
     $uploadTypes = \StringUtil::trimsplit(',', strtolower($this->extensions));
     // File type is not allowed
     if (!in_array($objFile->extension, $uploadTypes)) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
         unset($_FILES[$this->strName]);
         return;
     }
     if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) {
         // Image exceeds maximum image width
         if ($arrImageSize[0] > \Config::get('imageWidth')) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], \Config::get('imageWidth')));
             unset($_FILES[$this->strName]);
             return;
         }
         // Image exceeds maximum image height
         if ($arrImageSize[1] > \Config::get('imageHeight')) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], \Config::get('imageHeight')));
             unset($_FILES[$this->strName]);
             return;
         }
     }
     // Store file in the session and optionally on the server
     if (!$this->hasErrors()) {
         $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName];
         if ($this->storeFile) {
             $intUploadFolder = $this->uploadFolder;
             // Overwrite the upload folder with user's home directory
             if ($this->useHomeDir && FE_USER_LOGGED_IN) {
                 $this->import('FrontendUser', 'User');
                 if ($this->User->assignDir && $this->User->homeDir) {
                     $intUploadFolder = $this->User->homeDir;
                 }
             }
             $objUploadFolder = \FilesModel::findByUuid($intUploadFolder);
             // The upload folder could not be found
             if ($objUploadFolder === null) {
                 throw new \Exception("Invalid upload folder ID {$intUploadFolder}");
             }
             $strUploadFolder = $objUploadFolder->path;
             // Store the file if the upload folder exists
             if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) {
                 $this->import('Files');
                 // Do not overwrite existing files
                 if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'])) {
                     $offset = 1;
                     $arrAll = scan(TL_ROOT . '/' . $strUploadFolder);
                     $arrFiles = preg_grep('/^' . preg_quote($objFile->filename, '/') . '.*\\.' . preg_quote($objFile->extension, '/') . '/', $arrAll);
                     foreach ($arrFiles as $strFile) {
                         if (preg_match('/__[0-9]+\\.' . preg_quote($objFile->extension, '/') . '$/', $strFile)) {
                             $strFile = str_replace('.' . $objFile->extension, '', $strFile);
                             $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1));
                             $offset = max($offset, $intValue);
                         }
                     }
                     $file['name'] = str_replace($objFile->filename, $objFile->filename . '__' . ++$offset, $file['name']);
                 }
                 // Move the file to its destination
                 $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $file['name']);
                 $this->Files->chmod($strUploadFolder . '/' . $file['name'], \Config::get('defaultFileChmod'));
                 $strUuid = null;
                 $strFile = $strUploadFolder . '/' . $file['name'];
                 // Generate the DB entries
                 if (\Dbafs::shouldBeSynchronized($strFile)) {
                     $objModel = \FilesModel::findByPath($strFile);
                     if ($objModel === null) {
                         $objModel = \Dbafs::addResource($strFile);
                     }
                     $strUuid = \StringUtil::binToUuid($objModel->uuid);
                     // Update the hash of the target folder
                     \Dbafs::updateFolderHashes($strUploadFolder);
                 }
                 // Add the session entry (see #6986)
                 $_SESSION['FILES'][$this->strName] = array('name' => $file['name'], 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strFile, 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true, 'uuid' => $strUuid);
                 // Add a log entry
                 $this->log('File "' . $strUploadFolder . '/' . $file['name'] . '" has been uploaded', __METHOD__, TL_FILES);
             }
         }
     }
     unset($_FILES[$this->strName]);
 }
Пример #8
0
    /**
     * Return all non-excluded fields of a record as HTML table
     *
     * @return string
     */
    public function show()
    {
        if (!strlen($this->intId)) {
            return '';
        }
        $objRow = $this->Database->prepare("SELECT * FROM " . $this->strTable . " WHERE id=?")->limit(1)->execute($this->intId);
        if ($objRow->numRows < 1) {
            return '';
        }
        $count = 1;
        $return = '';
        $row = $objRow->row();
        // Get the order fields
        $objDcaExtractor = \DcaExtractor::getInstance($this->strTable);
        $arrOrder = $objDcaExtractor->getOrderFields();
        // Get all fields
        $fields = array_keys($row);
        $allowedFields = array('id', 'pid', 'sorting', 'tstamp');
        if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'])) {
            $allowedFields = array_unique(array_merge($allowedFields, array_keys($GLOBALS['TL_DCA'][$this->strTable]['fields'])));
        }
        // Use the field order of the DCA file
        $fields = array_intersect($allowedFields, $fields);
        // Show all allowed fields
        foreach ($fields as $i) {
            if (!in_array($i, $allowedFields) || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['inputType'] == 'password' || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['doNotShow'] || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['hideInput']) {
                continue;
            }
            // Special treatment for table tl_undo
            if ($this->strTable == 'tl_undo' && $i == 'data') {
                continue;
            }
            $value = deserialize($row[$i]);
            // Decrypt the value
            if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['encrypt']) {
                $value = \Encryption::decrypt($value);
            }
            $class = $count++ % 2 == 0 ? ' class="tl_bg"' : '';
            // Get the field value
            if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['foreignKey'])) {
                $temp = array();
                $chunks = explode('.', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['foreignKey'], 2);
                foreach ((array) $value as $v) {
                    $objKey = $this->Database->prepare("SELECT " . $chunks[1] . " AS value FROM " . $chunks[0] . " WHERE id=?")->limit(1)->execute($v);
                    if ($objKey->numRows) {
                        $temp[] = $objKey->value;
                    }
                }
                $row[$i] = implode(', ', $temp);
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['inputType'] == 'fileTree' || in_array($i, $arrOrder)) {
                if (is_array($value)) {
                    foreach ($value as $kk => $vv) {
                        $value[$kk] = $vv ? \StringUtil::binToUuid($vv) : '';
                    }
                    $row[$i] = implode(', ', $value);
                } else {
                    $row[$i] = $value ? \StringUtil::binToUuid($value) : '';
                }
            } elseif (is_array($value)) {
                foreach ($value as $kk => $vv) {
                    if (is_array($vv)) {
                        $vals = array_values($vv);
                        $value[$kk] = $vals[0] . ' (' . $vals[1] . ')';
                    }
                }
                $row[$i] = implode(', ', $value);
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['rgxp'] == 'date') {
                $row[$i] = $value ? \Date::parse(\Config::get('dateFormat'), $value) : '-';
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['rgxp'] == 'time') {
                $row[$i] = $value ? \Date::parse(\Config::get('timeFormat'), $value) : '-';
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['rgxp'] == 'datim' || in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['flag'], array(5, 6, 7, 8, 9, 10)) || $i == 'tstamp') {
                $row[$i] = $value ? \Date::parse(\Config::get('datimFormat'), $value) : '-';
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['multiple']) {
                $row[$i] = $value != '' ? $GLOBALS['TL_LANG']['MSC']['yes'] : $GLOBALS['TL_LANG']['MSC']['no'];
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['inputType'] == 'textarea' && ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['allowHtml'] || $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['preserveTags'])) {
                $row[$i] = specialchars($value);
            } elseif (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['reference'])) {
                $row[$i] = isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['reference'][$row[$i]]) ? is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['reference'][$row[$i]]) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['reference'][$row[$i]][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['reference'][$row[$i]] : $row[$i];
            } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['options'])) {
                $row[$i] = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['options'][$row[$i]];
            } else {
                $row[$i] = $value;
            }
            // Label
            if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['label'])) {
                $label = is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['label']) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['label'][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['label'];
            } else {
                $label = is_array($GLOBALS['TL_LANG']['MSC'][$i]) ? $GLOBALS['TL_LANG']['MSC'][$i][0] : $GLOBALS['TL_LANG']['MSC'][$i];
            }
            if ($label == '') {
                $label = $i;
            }
            $return .= '
  <tr>
    <td' . $class . '><span class="tl_label">' . $label . ': </span></td>
    <td' . $class . '>' . $row[$i] . '</td>
  </tr>';
        }
        // Special treatment for tl_undo
        if ($this->strTable == 'tl_undo') {
            $arrData = deserialize($objRow->data);
            foreach ($arrData as $strTable => $arrTableData) {
                \System::loadLanguageFile($strTable);
                $this->loadDataContainer($strTable);
                foreach ($arrTableData as $arrRow) {
                    $count = 0;
                    $return .= '
  <tr>
    <td colspan="2" style="padding:0"><div style="margin-bottom:26px;line-height:24px;border-bottom:1px dotted #ccc">&nbsp;</div></td>
  </tr>';
                    foreach ($arrRow as $i => $v) {
                        if (is_array(deserialize($v))) {
                            continue;
                        }
                        $class = $count++ % 2 == 0 ? ' class="tl_bg"' : '';
                        // Get the field label
                        if (isset($GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label'])) {
                            $label = is_array($GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label']) ? $GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label'][0] : $GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label'];
                        } else {
                            $label = is_array($GLOBALS['TL_LANG']['MSC'][$i]) ? $GLOBALS['TL_LANG']['MSC'][$i][0] : $GLOBALS['TL_LANG']['MSC'][$i];
                        }
                        if (!strlen($label)) {
                            $label = $i;
                        }
                        // Always encode special characters (thanks to Oliver Klee)
                        $return .= '
  <tr>
    <td' . $class . '><span class="tl_label">' . $label . ': </span></td>
    <td' . $class . '>' . specialchars($v) . '</td>
  </tr>';
                    }
                }
            }
        }
        // Return table
        return '
<div id="tl_buttons">' . (!\Input::get('popup') ? '
<a href="' . $this->getReferer(true) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>' : '') . '
</div>

<table class="tl_show">' . $return . '
</table>';
    }
Пример #9
0
   /**
    * Generate the widget and return it as string
    *
    * @return string
    */
   public function generate()
   {
       $arrSet = array();
       $arrValues = array();
       $blnHasOrder = $this->orderField != '' && is_array($this->{$this->orderField});
       if (!empty($this->varValue)) {
           $objFiles = \FilesModel::findMultipleByUuids((array) $this->varValue);
           $allowedDownload = trimsplit(',', strtolower(\Config::get('allowedDownload')));
           if ($objFiles !== null) {
               while ($objFiles->next()) {
                   // File system and database seem not in sync
                   if (!file_exists(TL_ROOT . '/' . $objFiles->path)) {
                       continue;
                   }
                   $arrSet[$objFiles->id] = $objFiles->uuid;
                   // Show files and folders
                   if (!$this->isGallery && !$this->isDownloads) {
                       if ($objFiles->type == 'folder') {
                           $arrValues[$objFiles->uuid] = \Image::getHtml('folderC.gif') . ' ' . $objFiles->path;
                       } else {
                           $objFile = new \File($objFiles->path, true);
                           $strInfo = $objFiles->path . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';
                           if ($objFile->isImage) {
                               $image = 'placeholder.png';
                               if (($objFile->isSvgImage || $objFile->height <= \Config::get('gdMaxImgHeight') && $objFile->width <= \Config::get('gdMaxImgWidth')) && $objFile->viewWidth && $objFile->viewHeight) {
                                   $image = \Image::get($objFiles->path, 80, 60, 'center_center');
                               }
                               $arrValues[$objFiles->uuid] = \Image::getHtml($image, '', 'class="gimage" title="' . specialchars($strInfo) . '"');
                           } else {
                               $arrValues[$objFiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
                           }
                       }
                   } else {
                       if ($objFiles->type == 'folder') {
                           $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
                           if ($objSubfiles === null) {
                               continue;
                           }
                           while ($objSubfiles->next()) {
                               // Skip subfolders
                               if ($objSubfiles->type == 'folder') {
                                   continue;
                               }
                               $objFile = new \File($objSubfiles->path, true);
                               $strInfo = '<span class="dirname">' . dirname($objSubfiles->path) . '/</span>' . $objFile->basename . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';
                               if ($this->isGallery) {
                                   // Only show images
                                   if ($objFile->isImage) {
                                       $image = 'placeholder.png';
                                       if (($objFile->isSvgImage || $objFile->height <= \Config::get('gdMaxImgHeight') && $objFile->width <= \Config::get('gdMaxImgWidth')) && $objFile->viewWidth && $objFile->viewHeight) {
                                           $image = \Image::get($objSubfiles->path, 80, 60, 'center_center');
                                       }
                                       $arrValues[$objSubfiles->uuid] = \Image::getHtml($image, '', 'class="gimage" title="' . specialchars($strInfo) . '"');
                                   }
                               } else {
                                   // Only show allowed download types
                                   if (in_array($objFile->extension, $allowedDownload) && !preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                                       $arrValues[$objSubfiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
                                   }
                               }
                           }
                       } else {
                           $objFile = new \File($objFiles->path, true);
                           $strInfo = '<span class="dirname">' . dirname($objFiles->path) . '/</span>' . $objFile->basename . ' <span class="tl_gray">(' . $this->getReadableSize($objFile->size) . ($objFile->isImage ? ', ' . $objFile->width . 'x' . $objFile->height . ' px' : '') . ')</span>';
                           if ($this->isGallery) {
                               // Only show images
                               if ($objFile->isImage) {
                                   $image = 'placeholder.png';
                                   if (($objFile->isSvgImage || $objFile->height <= \Config::get('gdMaxImgHeight') && $objFile->width <= \Config::get('gdMaxImgWidth')) && $objFile->viewWidth && $objFile->viewHeight) {
                                       $image = \Image::get($objFiles->path, 80, 60, 'center_center');
                                   }
                                   $arrValues[$objFiles->uuid] = \Image::getHtml($image, '', 'class="gimage" title="' . specialchars($strInfo) . '"');
                               }
                           } else {
                               // Only show allowed download types
                               if (in_array($objFile->extension, $allowedDownload) && !preg_match('/^meta(_[a-z]{2})?\\.txt$/', $objFile->basename)) {
                                   $arrValues[$objFiles->uuid] = \Image::getHtml($objFile->icon) . ' ' . $strInfo;
                               }
                           }
                       }
                   }
               }
           }
           // Apply a custom sort order
           if ($blnHasOrder) {
               $arrNew = array();
               foreach ((array) $this->{$this->orderField} as $i) {
                   if (isset($arrValues[$i])) {
                       $arrNew[$i] = $arrValues[$i];
                       unset($arrValues[$i]);
                   }
               }
               if (!empty($arrValues)) {
                   foreach ($arrValues as $k => $v) {
                       $arrNew[$k] = $v;
                   }
               }
               $arrValues = $arrNew;
               unset($arrNew);
           }
       }
       // Load the fonts for the drag hint (see #4838)
       \Config::set('loadGoogleFonts', true);
       // Convert the binary UUIDs
       $strSet = implode(',', array_map('StringUtil::binToUuid', $arrSet));
       $strOrder = $blnHasOrder ? implode(',', array_map('StringUtil::binToUuid', $this->{$this->orderField})) : '';
       $return = '<input type="hidden" name="' . $this->strName . '" id="ctrl_' . $this->strId . '" value="' . $strSet . '">' . ($blnHasOrder ? '
 <input type="hidden" name="' . $this->strOrderName . '" id="ctrl_' . $this->strOrderId . '" value="' . $strOrder . '">' : '') . '
 <div class="selector_container">' . ($blnHasOrder && count($arrValues) > 1 ? '
   <p class="sort_hint">' . $GLOBALS['TL_LANG']['MSC']['dragItemsHint'] . '</p>' : '') . '
   <ul id="sort_' . $this->strId . '" class="' . trim(($blnHasOrder ? 'sortable ' : '') . ($this->isGallery ? 'sgallery' : '')) . '">';
       foreach ($arrValues as $k => $v) {
           $return .= '<li data-id="' . \StringUtil::binToUuid($k) . '">' . $v . '</li>';
       }
       $return .= '</ul>
   <p><a href="contao/file.php?do=' . \Input::get('do') . '&amp;table=' . $this->strTable . '&amp;field=' . $this->strField . '&amp;act=show&amp;id=' . $this->activeRecord->id . '&amp;value=' . implode(',', array_keys($arrSet)) . '&amp;rt=' . REQUEST_TOKEN . '" class="tl_submit" onclick="Backend.getScrollOffset();Backend.openModalSelector({\'width\':768,\'title\':\'' . specialchars(str_replace("'", "\\'", $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField]['label'][0])) . '\',\'url\':this.href,\'id\':\'' . $this->strId . '\'});return false">' . $GLOBALS['TL_LANG']['MSC']['changeSelection'] . '</a></p>' . ($blnHasOrder ? '
   <script>Backend.makeMultiSrcSortable("sort_' . $this->strId . '", "ctrl_' . $this->strOrderId . '")</script>' : '') . '
 </div>';
       if (!\Environment::get('isAjaxRequest')) {
           $return = '<div>' . $return . '</div>';
       }
       return $return;
   }
Пример #10
0
 /**
  * Save the current value
  *
  * @param mixed $varValue
  */
 protected function save($varValue)
 {
     if (\Input::post('FORM_SUBMIT') != $this->strTable) {
         return;
     }
     $arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strField];
     // Make sure that checkbox values are boolean
     if ($arrData['inputType'] == 'checkbox' && !$arrData['eval']['multiple']) {
         $varValue = $varValue ? true : false;
     }
     if ($varValue != '') {
         // Convert binary UUIDs (see #6893)
         if ($arrData['inputType'] == 'fileTree') {
             $varValue = deserialize($varValue);
             if (!is_array($varValue)) {
                 $varValue = \StringUtil::binToUuid($varValue);
             } else {
                 $varValue = serialize(array_map('StringUtil::binToUuid', $varValue));
             }
         }
         // Convert date formats into timestamps
         if ($varValue != '' && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) {
             $objDate = new \Date($varValue, \Date::getFormatFromRgxp($arrData['eval']['rgxp']));
             $varValue = $objDate->tstamp;
         }
         // Handle entities
         if ($arrData['inputType'] == 'text' || $arrData['inputType'] == 'textarea') {
             $varValue = deserialize($varValue);
             if (!is_array($varValue)) {
                 $varValue = \StringUtil::restoreBasicEntities($varValue);
             } else {
                 $varValue = serialize(array_map('StringUtil::restoreBasicEntities', $varValue));
             }
         }
     }
     // Trigger the save_callback
     if (is_array($arrData['save_callback'])) {
         foreach ($arrData['save_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $this);
             } elseif (is_callable($callback)) {
                 $varValue = $callback($varValue, $this);
             }
         }
     }
     $strCurrent = $this->varValue;
     // Handle arrays and strings
     if (is_array($strCurrent)) {
         $strCurrent = serialize($strCurrent);
     } elseif (is_string($strCurrent)) {
         $strCurrent = html_entity_decode($this->varValue, ENT_QUOTES, \Config::get('characterSet'));
     }
     // Save the value if there was no error
     if ((strlen($varValue) || !$arrData['eval']['doNotSaveEmpty']) && $strCurrent != $varValue) {
         \Config::persist($this->strField, $varValue);
         $deserialize = deserialize($varValue);
         $prior = is_bool(\Config::get($this->strField)) ? \Config::get($this->strField) ? 'true' : 'false' : \Config::get($this->strField);
         // Add a log entry
         if (!is_array(deserialize($prior)) && !is_array($deserialize)) {
             if ($arrData['inputType'] == 'password' || $arrData['inputType'] == 'textStore') {
                 $this->log('The global configuration variable "' . $this->strField . '" has been changed', __METHOD__, TL_CONFIGURATION);
             } else {
                 $this->log('The global configuration variable "' . $this->strField . '" has been changed from "' . $prior . '" to "' . $varValue . '"', __METHOD__, TL_CONFIGURATION);
             }
         }
         // Set the new value so the input field can show it
         $this->varValue = $deserialize;
         \Config::set($this->strField, $deserialize);
     }
 }
Пример #11
0
 /**
  * Implode a multi-dimensional array recursively
  *
  * @param mixed   $var
  * @param boolean $binary
  *
  * @return string
  */
 protected function implodeRecursive($var, $binary = false)
 {
     if (!is_array($var)) {
         return $binary ? \StringUtil::binToUuid($var) : $var;
     } elseif (!is_array(current($var))) {
         return implode(', ', $binary ? array_map('StringUtil::binToUuid', $var) : $var);
     } else {
         $buffer = '';
         foreach ($var as $k => $v) {
             $buffer .= $k . ": " . $this->implodeRecursive($v) . "\n";
         }
         return trim($buffer);
     }
 }
Пример #12
0
 /**
  * @param $value
  * @return string
  */
 public static function binToUuid($value)
 {
     // Convert bin to uuid
     if (\Validator::isBinaryUuid($value)) {
         return \StringUtil::binToUuid($value);
     }
     return $value;
 }
 /**
  * @param  bool   $import        True for import, false for export
  * @param  array  $data          Data of element or parent list item
  * @param  array  $config        Fields configuration
  * @param  array  $idMappingData ID mapping for imported database rows
  * @param  string $fieldPrefix
  * @return array                 Converted $data
  */
 protected function convertDataForImportExportParseFields($import, $data, $config, $idMappingData, $fieldPrefix = 'rsce_field_')
 {
     foreach ($data as $fieldName => $value) {
         $fieldConfig = $this->getNestedConfig($fieldPrefix . $fieldName, $config);
         if (empty($fieldConfig['inputType'])) {
             continue;
         }
         if ($fieldConfig['inputType'] === 'list') {
             for ($dataKey = 0; isset($value[$dataKey]); $dataKey++) {
                 $data[$fieldName][$dataKey] = $this->convertDataForImportExportParseFields($import, $value[$dataKey], $config, $idMappingData, $fieldPrefix . $fieldName . '__' . $dataKey . '__');
             }
         } else {
             if ($value && ($fieldConfig['inputType'] === 'fileTree' || $fieldConfig['inputType'] === 'fineUploader')) {
                 if (empty($fieldConfig['eval']['multiple'])) {
                     if ($import) {
                         $file = \FilesModel::findByPath(\Config::get('uploadPath') . '/' . preg_replace('(^files/)', '', $value));
                         if ($file) {
                             $data[$fieldName] = \StringUtil::binToUuid($file->uuid);
                         }
                     } else {
                         $file = \FilesModel::findById($value);
                         if ($file) {
                             $data[$fieldName] = 'files/' . preg_replace('(^' . preg_quote(\Config::get('uploadPath')) . '/)', '', $file->path);
                         }
                     }
                 } else {
                     $data[$fieldName] = serialize(array_map(function ($value) use($import) {
                         if ($import) {
                             $file = \FilesModel::findByPath(\Config::get('uploadPath') . '/' . preg_replace('(^files/)', '', $value));
                             if ($file) {
                                 return \StringUtil::binToUuid($file->uuid);
                             }
                         } else {
                             $file = \FilesModel::findById($value);
                             if ($file) {
                                 return 'files/' . preg_replace('(^' . preg_quote(\Config::get('uploadPath')) . '/)', '', $file->path);
                             }
                         }
                         return $value;
                     }, deserialize($value, true)));
                 }
             } else {
                 if ($fieldConfig['inputType'] === 'imageSize' && $value && $import) {
                     $value = deserialize($value, true);
                     if (!empty($value[2]) && is_numeric($value[2]) && !empty($idMappingData['tl_image_size'][$value[2]])) {
                         $value[2] = $idMappingData['tl_image_size'][$value[2]];
                         $data[$fieldName] = serialize($value);
                     }
                 }
             }
         }
     }
     return $data;
 }
 /**
  * Generate the widget and return it as string
  * @param array
  * @return string
  */
 public function parse($arrAttributes = null)
 {
     if (!$this->blnValuesPrepared) {
         $arrSet = array();
         $arrValues = array();
         $arrUuids = array();
         $arrTemp = array();
         if (!empty($this->varValue)) {
             // Can be an array
             $this->varValue = (array) $this->varValue;
             foreach ($this->varValue as $varFile) {
                 if (\Validator::isUuid($varFile)) {
                     $arrUuids[] = $varFile;
                 } else {
                     $arrTemp[] = $varFile;
                 }
             }
             $objFiles = \FilesModel::findMultipleByUuids($arrUuids);
             // Get the database files
             if ($objFiles !== null) {
                 while ($objFiles->next()) {
                     $chunk = $this->generateFileItem($objFiles->path);
                     if (strlen($chunk)) {
                         $arrValues[$objFiles->uuid] = array('id' => in_array($objFiles->uuid, $arrTemp) ? $objFiles->uuid : \StringUtil::binToUuid($objFiles->uuid), 'value' => $chunk);
                         $arrSet[] = $objFiles->uuid;
                     }
                 }
             }
             // Get the temporary files
             foreach ($arrTemp as $varFile) {
                 $chunk = $this->generateFileItem($varFile);
                 if (strlen($chunk)) {
                     $arrValues[$varFile] = array('id' => in_array($varFile, $arrTemp) ? $varFile : \StringUtil::binToUuid($varFile), 'value' => $chunk);
                     $arrSet[] = $varFile;
                 }
             }
         }
         // Parse the set array
         foreach ($arrSet as $k => $v) {
             if (in_array($v, $arrTemp)) {
                 $strSet[$k] = $v;
             } else {
                 $arrSet[$k] = \StringUtil::binToUuid($v);
             }
         }
         $this->set = implode(',', $arrSet);
         $this->values = $arrValues;
         $this->deleteTitle = specialchars($GLOBALS['TL_LANG']['MSC']['delete']);
         $this->extensions = json_encode(trimsplit(',', $this->arrConfiguration['extensions']));
         $this->limit = $this->arrConfiguration['uploaderLimit'] ? $this->arrConfiguration['uploaderLimit'] : 0;
         $this->minSizeLimit = $this->arrConfiguration['minlength'] ? $this->arrConfiguration['minlength'] : 0;
         $this->sizeLimit = $this->arrConfiguration['maxlength'] ? $this->arrConfiguration['maxlength'] : 0;
         $this->chunkSize = $this->arrConfiguration['chunkSize'] ? $this->arrConfiguration['chunkSize'] : 0;
         $this->concurrent = $this->arrConfiguration['concurrent'] ? true : false;
         $this->maxConnections = $this->arrConfiguration['maxConnections'] ? $this->arrConfiguration['maxConnections'] : 3;
         $this->blnValuesPrepared = true;
     }
     return parent::parse($arrAttributes);
 }
 /**
  *
  * Add contao core tokens, as long as the cron job does not have these information
  * on sending mail in queue mode
  *
  * @param $arrTokens
  * @param $strLanguage
  * @return bool false if context_tokens has been set already (required by cron)
  */
 protected function addContextTokens($objMessage, &$arrTokens, $strLanguage)
 {
     // add context tokens only once (queue will trigger this function again, and tokens might be overwritten)
     if (isset($arrTokens['context_tokens'])) {
         return false;
     }
     $arrTokens['context_tokens'] = true;
     // add environment variables as token
     $arrTokens['env_host'] = \Idna::decode(\Environment::get('host'));
     $arrTokens['env_http_host'] = \Idna::decode(\Environment::get('httpHost'));
     $arrTokens['env_url'] = \Idna::decode(\Environment::get('url'));
     $arrTokens['env_path'] = \Idna::decode(\Environment::get('base'));
     $arrTokens['env_request'] = \Idna::decode(\Environment::get('indexFreeRequest'));
     $arrTokens['env_ip'] = \Idna::decode(\Environment::get('ip'));
     $arrTokens['env_referer'] = \System::getReferer();
     $arrTokens['env_files_url'] = TL_FILES_URL;
     $arrTokens['env_plugins_url'] = TL_ASSETS_URL;
     $arrTokens['env_script_url'] = TL_ASSETS_URL;
     // add date tokens
     $arrTokens['date'] = \Controller::replaceInsertTags('{{date}}');
     $arrTokens['last_update'] = \Controller::replaceInsertTags('{{last_update}}');
     if (TL_MODE == 'FE') {
         // add current page as token
         global $objPage;
         if ($objPage !== null) {
             foreach ($objPage->row() as $key => $value) {
                 $arrTokens['page_' . $key] = $value;
             }
             if ($objPage->pageTitle == '') {
                 $arrTokens['pageTitle'] = $objPage->title;
             } else {
                 if ($objPage->parentPageTitle == '') {
                     $arrTokens['parentPageTitle'] = $objPage->parentTitle;
                 } else {
                     if ($objPage->mainPageTitle == '') {
                         $arrTokens['mainPageTitle'] = $objPage->mainTitle;
                     }
                 }
             }
         }
         // add user attributes as token
         if (FE_USER_LOGGED_IN) {
             $arrUserData = \FrontendUser::getInstance()->getData();
             if (is_array($arrUserData)) {
                 foreach ($arrUserData as $key => $value) {
                     if (!is_array($value) && \Validator::isBinaryUuid($value)) {
                         $value = \StringUtil::binToUuid($value);
                         $objFile = \FilesModel::findByUuid($value);
                         if ($objFile !== null) {
                             $value = $objFile->path;
                         }
                     }
                     $arrTokens['user_' . $key] = $value;
                 }
             }
         }
     }
 }
 public function prepareFile($varUuid)
 {
     if (($objFile = Files::getFileFromUuid($varUuid, true)) !== null && $objFile->exists()) {
         static::addAllowedDownload($objFile->value);
         $arrReturn = array('name' => StringUtil::preg_replace_last('@_[a-f0-9]{13}@', $objFile->name), 'uuid' => \StringUtil::binToUuid($objFile->getModel()->uuid), 'size' => $objFile->filesize);
         if (($strImage = $this->getPreviewImage($objFile)) !== null) {
             $arrReturn['url'] = $strImage;
         }
         if (($strInfoUrl = $this->getInfoAction($objFile)) !== null) {
             $arrReturn['info'] = $strInfoUrl;
         }
         return $arrReturn;
     }
     return false;
 }
Пример #17
0
 /**
  * Move temp files. If DBAFS support is enabled add entries to the dbafs.
  *
  * @CtoCommunication Enable
  *
  * @param  array   $arrFileList List with files for moving.
  *
  * @param  boolean $blnIsDbafs  Flag if we have to change the dbafs system.
  *
  * @return array The list with some more information about the moving of the file.
  */
 public function moveTempFile($arrFileList, $blnIsDbafs)
 {
     foreach ($arrFileList as $key => $value) {
         try {
             $blnMovedFile = false;
             $strTempFile = $this->objSyncCtoHelper->standardizePath($GLOBALS['SYC_PATH']['tmp'], "sync", $value["path"]);
             // Check if the tmp file exists.
             if (!file_exists(TL_ROOT . DIRECTORY_SEPARATOR . $strTempFile)) {
                 $arrFileList[$key]['saved'] = false;
                 $arrFileList[$key]['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['unknown_file'], $strTempFile);
                 $arrFileList[$key]['skipreasons'] = $GLOBALS['TL_LANG']['ERR']['missing_file_information'];
                 continue;
             }
             // Generate the folder if not already there.
             $strFolderPath = dirname($value["path"]);
             if ($strFolderPath != ".") {
                 $objFolder = new Folder($strFolderPath);
                 unset($objFolder);
             }
             // Build folders.
             $strFileSource = $this->objSyncCtoHelper->standardizePath($GLOBALS['SYC_PATH']['tmp'], "sync", $value["path"]);
             $strFileDestination = $this->objSyncCtoHelper->standardizePath($value["path"]);
             // DBAFS support. Check if we have the file already in the locale dbafs system.
             if ($blnIsDbafs) {
                 // Get the information from the dbafs.
                 /**  @var \Model $objLocaleData */
                 $objLocaleData = \FilesModel::findByPath($strFileDestination);
                 // If we have no entry in the dbafs just overwrite the current file and add the entry to the dbafs.
                 if ($objLocaleData == null) {
                     // Move file.
                     $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                     // If success add file to the database.
                     if ($blnMovedFile) {
                         // First add it to the dbafs.
                         $objLocaleData = \Dbafs::addResource($strFileDestination);
                         // PHP 7 compatibility
                         // See #309 (https://github.com/contao/core-bundle/issues/309)
                         if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                             $objLocaleData->uuid = \StringUtil::uuidToBin($value['tl_files']['uuid']);
                         } else {
                             $objLocaleData->uuid = \String::uuidToBin($value['tl_files']['uuid']);
                         }
                         $objLocaleData->meta = $value['tl_files']['meta'];
                         $objLocaleData->save();
                         // Add a status report for debugging and co.
                         $arrFileList[$key]['dbafs']['msg'] = 'Moved file and add to database.';
                         $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_CREATE;
                     }
                 } else {
                     // PHP 7 compatibility
                     // See #309 (https://github.com/contao/core-bundle/issues/309)
                     if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                         // Get the readable UUID for the work.
                         $strLocaleUUID = \StringUtil::binToUuid($objLocaleData->uuid);
                     } else {
                         // Get the readable UUID for the work.
                         $strLocaleUUID = \String::binToUuid($objLocaleData->uuid);
                     }
                     // Okay it seems we have already a file with this values.
                     if ($strLocaleUUID == $value['tl_files']['uuid']) {
                         // Move file.
                         $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                         // If success add file to the database.
                         if ($blnMovedFile) {
                             $objLocaleData->hash = $value['checksum'];
                             $objLocaleData->meta = $value['tl_files']['meta'];
                             $objLocaleData->save();
                             // Add a status report for debugging and co.
                             $arrFileList[$key]['dbafs']['msg'] = 'UUID same no problem found. Update database with new hash.';
                             $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_SAME;
                         }
                     } elseif ($strLocaleUUID != $value['tl_files']['uuid']) {
                         // Get information about the current file information.
                         $arrDestinationInformation = pathinfo($strFileDestination);
                         // Try to rename it to _1 or _2 and so on.
                         $strNewDestinationName = null;
                         $intFileNumber = 1;
                         for ($i = 1; $i < 100; $i++) {
                             $strNewDestinationName = sprintf('%s' . DIRECTORY_SEPARATOR . '%s_%s.%s', $arrDestinationInformation['dirname'], $arrDestinationInformation['filename'], $i, $arrDestinationInformation['extension']);
                             if (!file_exists(TL_ROOT . DIRECTORY_SEPARATOR . $strNewDestinationName)) {
                                 $intFileNumber = $i;
                                 break;
                             }
                         }
                         // Move the current file to another name, that we have space for the new one.
                         $this->objFiles->copy($strFileDestination, $strNewDestinationName);
                         $objRenamedLocaleData = \Dbafs::moveResource($strFileDestination, $strNewDestinationName);
                         // Move the tmp file.
                         $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
                         // If success add file to the database.
                         if ($blnMovedFile) {
                             // First add it to the dbafs.
                             $objLocaleData = \Dbafs::addResource($strFileDestination);
                             // PHP 7 compatibility
                             // See #309 (https://github.com/contao/core-bundle/issues/309)
                             if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                                 $objLocaleData->uuid = \StringUtil::uuidToBin($value['tl_files']['uuid']);
                             } else {
                                 $objLocaleData->uuid = \String::uuidToBin($value['tl_files']['uuid']);
                             }
                             $objLocaleData->meta = $value['tl_files']['meta'];
                             $objLocaleData->save();
                             // Add a status report for debugging and co.
                             $arrFileList[$key]['dbafs']['msg'] = $GLOBALS['TL_LANG']['ERR']['dbafs_uuid_conflict'];
                             $arrFileList[$key]['dbafs']['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['dbafs_uuid_conflict_rename'], $intFileNumber);
                             $arrFileList[$key]['dbafs']['rename'] = $strNewDestinationName;
                             $arrFileList[$key]['dbafs']['state'] = SyncCtoEnum::DBAFS_CONFLICT;
                         }
                     }
                 }
             } else {
                 $blnMovedFile = $this->objFiles->copy($strFileSource, $strFileDestination);
             }
             // Check the state at moving and add a msg to the return array.
             if ($blnMovedFile) {
                 $arrFileList[$key]['saved'] = true;
                 $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_MOVED;
             } else {
                 $arrFileList[$key]['saved'] = false;
                 $arrFileList[$key]['error'] = sprintf($GLOBALS['TL_LANG']['ERR']['cant_move_file'], $strFileSource, $strFileDestination);
                 $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED;
                 $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_move_files'];
             }
         } catch (Exception $e) {
             $arrFileList[$key]['saved'] = false;
             $arrFileList[$key]['error'] = sprintf('Can not move file - %s. Exception message: %s', $value["path"], $e->getMessage());
             $arrFileList[$key]['transmission'] = SyncCtoEnum::FILETRANS_SKIPPED;
             $arrFileList[$key]['skipreason'] = $GLOBALS['TL_LANG']['ERR']['cant_move_files'];
         }
     }
     return $arrFileList;
 }
 /**
  * Run the controller and parse the template
  */
 public function run()
 {
     if ($this->strFile == '') {
         die('No file given');
     }
     // Make sure there are no attempts to hack the file system
     if (preg_match('@^\\.+@i', $this->strFile) || preg_match('@\\.+/@i', $this->strFile) || preg_match('@(://)+@i', $this->strFile)) {
         die('Invalid file name');
     }
     // Limit preview to the files directory
     if (!preg_match('@^' . preg_quote(\Config::get('uploadPath'), '@') . '@i', $this->strFile)) {
         die('Invalid path');
     }
     // Check whether the file exists
     if (!file_exists(TL_ROOT . '/' . $this->strFile)) {
         die('File not found');
     }
     // Check whether the file is mounted (thanks to Marko Cupic)
     if (!$this->User->hasAccess($this->strFile, 'filemounts')) {
         die('Permission denied');
     }
     // Open the download dialogue
     if (\Input::get('download')) {
         $objFile = new \File($this->strFile, true);
         $objFile->sendToBrowser();
     }
     /** @var \BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_popup');
     // Add the resource (see #6880)
     if (($objModel = \FilesModel::findByPath($this->strFile)) === null) {
         if (\Dbafs::shouldBeSynchronized($this->strFile)) {
             $objModel = \Dbafs::addResource($this->strFile);
         }
     }
     if ($objModel !== null) {
         $objTemplate->uuid = \StringUtil::binToUuid($objModel->uuid);
         // see #5211
     }
     // Add the file info
     if (is_dir(TL_ROOT . '/' . $this->strFile)) {
         $objFile = new \Folder($this->strFile, true);
         $objTemplate->filesize = $this->getReadableSize($objFile->size) . ' (' . number_format($objFile->size, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)';
     } else {
         $objFile = new \File($this->strFile, true);
         // Image
         if ($objFile->isImage) {
             $objTemplate->isImage = true;
             $objTemplate->width = $objFile->width;
             $objTemplate->height = $objFile->height;
             $objTemplate->src = $this->urlEncode($this->strFile);
         }
         $objTemplate->href = ampersand(\Environment::get('request'), true) . '&amp;download=1';
         $objTemplate->filesize = $this->getReadableSize($objFile->filesize) . ' (' . number_format($objFile->filesize, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)';
     }
     $objTemplate->icon = $objFile->icon;
     $objTemplate->mime = $objFile->mime;
     $objTemplate->ctime = \Date::parse(\Config::get('datimFormat'), $objFile->ctime);
     $objTemplate->mtime = \Date::parse(\Config::get('datimFormat'), $objFile->mtime);
     $objTemplate->atime = \Date::parse(\Config::get('datimFormat'), $objFile->atime);
     $objTemplate->path = specialchars($this->strFile);
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = specialchars($this->strFile);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->headline = basename(utf8_convert_encoding($this->strFile, \Config::get('characterSet')));
     $objTemplate->label_uuid = $GLOBALS['TL_LANG']['MSC']['fileUuid'];
     $objTemplate->label_imagesize = $GLOBALS['TL_LANG']['MSC']['fileImageSize'];
     $objTemplate->label_filesize = $GLOBALS['TL_LANG']['MSC']['fileSize'];
     $objTemplate->label_ctime = $GLOBALS['TL_LANG']['MSC']['fileCreated'];
     $objTemplate->label_mtime = $GLOBALS['TL_LANG']['MSC']['fileModified'];
     $objTemplate->label_atime = $GLOBALS['TL_LANG']['MSC']['fileAccessed'];
     $objTemplate->label_path = $GLOBALS['TL_LANG']['MSC']['filePath'];
     $objTemplate->download = specialchars($GLOBALS['TL_LANG']['MSC']['fileDownload']);
     \Config::set('debugMode', false);
     $objTemplate->output();
 }
 /**
  * Generate the widget and return it as string
  * @param array
  * @return string
  */
 public function parse($arrAttributes = null)
 {
     $arrSet = array();
     $arrValues = array();
     if (!empty($this->varValue)) {
         // Can be an array
         $arrUuids = array();
         $arrTemp = array();
         $this->varValue = (array) $this->varValue;
         foreach ($this->varValue as $varFile) {
             if (\Validator::isBinaryUuid($varFile)) {
                 $arrUuids[] = $varFile;
             } else {
                 $arrTemp[] = $varFile;
             }
         }
         $objFiles = \FilesModel::findMultipleByUuids($arrUuids);
         // Get the database files
         if ($objFiles !== null) {
             while ($objFiles->next()) {
                 $chunk = $this->generateFileItem($objFiles->path);
                 if (strlen($chunk)) {
                     $arrValues[$objFiles->uuid] = array('id' => in_array($objFiles->uuid, $arrTemp) ? $objFiles->uuid : \StringUtil::binToUuid($objFiles->uuid), 'value' => $chunk);
                     $arrSet[] = $objFiles->uuid;
                 }
             }
         }
         // Get the temporary files
         foreach ($arrTemp as $varFile) {
             $chunk = $this->generateFileItem($varFile);
             if (strlen($chunk)) {
                 $arrValues[$varFile] = array('id' => in_array($varFile, $arrTemp) ? $varFile : \StringUtil::binToUuid($varFile), 'value' => $chunk);
                 $arrSet[] = $varFile;
             }
         }
     }
     // Load the fonts for the drag hint (see #4838)
     $GLOBALS['TL_CONFIG']['loadGoogleFonts'] = true;
     // Parse the set array
     foreach ($arrSet as $k => $v) {
         if (in_array($v, $arrTemp)) {
             $strSet[$k] = $v;
         } else {
             $arrSet[$k] = \StringUtil::binToUuid($v);
         }
     }
     $this->set = implode(',', $arrSet);
     $this->sortable = count($arrValues) > 1;
     $this->orderHint = $GLOBALS['TL_LANG']['MSC']['dragItemsHint'];
     $this->values = $arrValues;
     $this->ajax = \Environment::get('isAjaxRequest') && \Input::post('action') !== 'toggleSubpalette';
     $this->deleteTitle = specialchars($GLOBALS['TL_LANG']['MSC']['delete']);
     $this->extensions = json_encode(trimsplit(',', $this->arrConfiguration['extensions']));
     $this->limit = $this->arrConfiguration['uploaderLimit'] ? $this->arrConfiguration['uploaderLimit'] : 0;
     $this->minSizeLimit = $this->arrConfiguration['minlength'] ? $this->arrConfiguration['minlength'] : 0;
     $this->sizeLimit = $this->arrConfiguration['maxlength'] ? $this->arrConfiguration['maxlength'] : 0;
     $this->chunkSize = $this->arrConfiguration['chunkSize'] ? $this->arrConfiguration['chunkSize'] : 0;
     $this->concurrent = $this->arrConfiguration['concurrent'] ? true : false;
     $this->maxConnections = $this->arrConfiguration['maxConnections'] ? $this->arrConfiguration['maxConnections'] : 3;
     return parent::parse($arrAttributes);
 }
Пример #20
0
 /**
  * Last Steps for all functions
  */
 private function pageSyncToShowStep6()
 {
     /* ---------------------------------------------------------------------
      * Init
      */
     if ($this->objStepPool->step == null) {
         $this->objStepPool->step = 1;
     }
     // Set content back to normale mode
     $this->booError = false;
     $this->strError = "";
     $this->objData->setState(SyncCtoEnum::WORK_WORK);
     // Get the file list.
     $fileList = new \SyncCto\Sync\FileList\Base($this->arrListCompare);
     /* ---------------------------------------------------------------------
      * Run page
      */
     try {
         switch ($this->objStepPool->step) {
             /**
              * Init
              */
             case 1:
                 $this->objData->setState(SyncCtoEnum::WORK_WORK);
                 $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']);
                 $this->objData->setTitle($GLOBALS['TL_LANG']['MSC']['step'] . " %s");
                 $this->objStepPool->step++;
                 break;
             case 2:
                 $this->objSyncCtoCommunicationClient->purgeCache();
                 $this->objStepPool->step++;
                 break;
                 /**
                  * Import files
                  */
             /**
              * Import files
              */
             case 3:
                 // Reset the msg.
                 $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']);
                 $this->setErrorMsg('');
                 try {
                     // Get the file list.
                     $itCore = $fileList->getTransferCore(true, false);
                     $itPrivate = $fileList->getTransferPrivate(true, false);
                     $itDbafs = $fileList->getDbafs(true, false);
                     $itOverall = $fileList->getTransferFiles(true, true);
                     // Count some values.
                     $waitingFiles = iterator_count($itCore) + iterator_count($itPrivate) + iterator_count($itDbafs);
                     $overallFiles = iterator_count($itOverall);
                     // Add the status.
                     $this->objData->setDescription(sprintf($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_3"]['description_2'], $overallFiles - $waitingFiles, $overallFiles));
                     // Check if we have some files.
                     if ($waitingFiles == 0) {
                         $this->objData->setHtml('');
                         $this->objStepPool->step++;
                         break;
                     }
                     // Check for endless run.
                     if ($waitingFiles == $this->arrSyncSettings['last_transfer']) {
                         $this->objData->setHtml('');
                         $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']);
                         $this->setError(true);
                         $this->setErrorMsg('Error on moving files. Some files could not be moved.');
                         break;
                     }
                     // Add the current count to the config.
                     $this->arrSyncSettings['last_transfer'] = $waitingFiles;
                     // Run core if we have files.
                     if (iterator_count($itCore) != 0) {
                         $arrTransmission = $this->objSyncCtoCommunicationClient->runFileImport(iterator_to_array($itCore), false);
                         foreach ($arrTransmission as $key => $value) {
                             $this->arrListCompare['core'][$key] = $value;
                         }
                     } else {
                         if (iterator_count($itPrivate) != 0) {
                             // Get only 100 files.
                             $itSupSet = new LimitIterator($itPrivate, 0, 100);
                             $itSupSet = iterator_to_array($itSupSet);
                             // Get the dbafs information.
                             foreach ($itSupSet as $key => $value) {
                                 // Get the information from the tl_files.
                                 $objModel = \FilesModel::findByPath($value['path']);
                                 // Okay we have the file ...
                                 if ($objModel != null) {
                                     $arrModelData = $objModel->row();
                                     // PHP 7 compatibility
                                     // See #309 (https://github.com/contao/core-bundle/issues/309)
                                     if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                                         $arrModelData['pid'] = strlen($arrModelData['pid']) ? \StringUtil::binToUuid($arrModelData['pid']) : $arrModelData['pid'];
                                         $arrModelData['uuid'] = \StringUtil::binToUuid($arrModelData['uuid']);
                                     } else {
                                         $arrModelData['pid'] = strlen($arrModelData['pid']) ? \String::binToUuid($arrModelData['pid']) : $arrModelData['pid'];
                                         $arrModelData['uuid'] = \String::binToUuid($arrModelData['uuid']);
                                     }
                                 } else {
                                     $objModel = \Dbafs::addResource($value['path']);
                                     $arrModelData = $objModel->row();
                                     // PHP 7 compatibility
                                     // See #309 (https://github.com/contao/core-bundle/issues/309)
                                     if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
                                         $arrModelData['pid'] = strlen($arrModelData['pid']) ? \StringUtil::binToUuid($arrModelData['pid']) : $arrModelData['pid'];
                                         $arrModelData['uuid'] = \StringUtil::binToUuid($arrModelData['uuid']);
                                     } else {
                                         $arrModelData['pid'] = strlen($arrModelData['pid']) ? \String::binToUuid($arrModelData['pid']) : $arrModelData['pid'];
                                         $arrModelData['uuid'] = \String::binToUuid($arrModelData['uuid']);
                                     }
                                 }
                                 $itSupSet[$key]['tl_files'] = $arrModelData;
                             }
                             // Send the data to the client.
                             $arrTransmission = $this->objSyncCtoCommunicationClient->runFileImport($itSupSet, true);
                             // Add the information to the current list.
                             foreach ($arrTransmission as $key => $value) {
                                 $this->arrListCompare['files'][$key] = $value;
                             }
                         } else {
                             if (iterator_count($itDbafs) != 0) {
                                 // Get only 100 files.
                                 $itSupSet = new LimitIterator($itDbafs, 0, 100);
                                 // Send it to the client.
                                 $arrTransmission = $this->objSyncCtoCommunicationClient->updateDbafs(iterator_to_array($itSupSet));
                                 // Update the current list.
                                 foreach ($arrTransmission as $key => $value) {
                                     // Set the state.
                                     if ($value['saved']) {
                                         $value["transmission"] = SyncCtoEnum::FILETRANS_SEND;
                                     } else {
                                         $value["transmission"] = SyncCtoEnum::FILETRANS_SKIPPED;
                                     }
                                     $this->arrListCompare['files'][$key] = $value;
                                 }
                             }
                         }
                     }
                 } catch (Exception $e) {
                     $this->objData->setHtml('');
                     $this->objData->setDescription($e->getMessage());
                     $this->setError(true);
                     $this->setErrorMsg('Error on moving files. Some files could not be moved.');
                 }
                 break;
                 /**
                  * Delete Files
                  */
             /**
              * Delete Files
              */
             case 4:
                 // Reset the msg.
                 $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_2']);
                 $this->setErrorMsg('');
                 try {
                     // Get the file list.
                     $itCore = $fileList->getDeletedCore(true);
                     $itPrivate = $fileList->getDeletedPrivate(true);
                     $itOverall = $fileList->getDeletedFiles(false);
                     // Count some values.
                     $waitingFiles = iterator_count($itCore) + iterator_count($itPrivate);
                     $overallFiles = iterator_count($itOverall);
                     // Add the status.
                     $this->objData->setDescription(sprintf($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_3"]['description_2'], $overallFiles - $waitingFiles, $overallFiles));
                     // Check if we have some files.
                     if ($waitingFiles == 0) {
                         $this->objData->setHtml('');
                         $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']);
                         $this->objStepPool->step++;
                         break;
                     }
                     // Check for endless run.
                     if ($waitingFiles == $this->arrSyncSettings['last_delete']) {
                         $this->objData->setHtml('');
                         $this->objData->setDescription($GLOBALS['TL_LANG']['tl_syncCto_sync']["step_5"]['description_1']);
                         $this->setError(true);
                         $this->setErrorMsg('Error on deleting files. Some files could not be deleted.');
                         break;
                     }
                     // Add the current count to the config.
                     $this->arrSyncSettings['last_delete'] = $waitingFiles;
                     // Run core if we have files.
                     if (iterator_count($itCore) != 0) {
                         // Get only 100 files.
                         $itSupSet = new LimitIterator($itCore, 0, 100);
                         // Send them to the client.
                         $arrTransmission = $this->objSyncCtoCommunicationClient->deleteFiles(iterator_to_array($itSupSet), false);
                         // Add all information to the file list.
                         foreach ($arrTransmission as $key => $value) {
                             $this->arrListCompare['core'][$key] = $value;
                         }
                     } else {
                         if (iterator_count($itPrivate) != 0) {
                             // Get only 100 files.
                             $itSupSet = new LimitIterator($itPrivate, 0, 100);
                             // Send them to the client.
                             $arrTransmission = $this->objSyncCtoCommunicationClient->deleteFiles(iterator_to_array($itSupSet), false);
                             // Add all information to the file list.
                             foreach ($arrTransmission as $key => $value) {
                                 $this->arrListCompare['files'][$key] = $value;
                             }
                         }
                     }
                 } catch (Exception $e) {
                     // If there was an error just go on. The endless protection will
                     // handle any problem.
                 }
                 break;
             case 5:
                 $this->objSyncCtoCommunicationClient->createCache();
                 $this->objStepPool->step++;
                 break;
                 /**
                  * Import Config
                  */
             /**
              * Import Config
              */
             case 6:
                 if ($this->arrSyncSettings["syncCto_Type"] == 'all' || in_array("localconfig_update", $this->arrSyncSettings["syncCto_Type"])) {
                     $this->objSyncCtoCommunicationClient->runLocalConfigImport();
                     $this->objStepPool->step++;
                     break;
                 }
                 $this->objStepPool->step++;
                 /**
                  * Import Config / Set show error
                  */
             /**
              * Import Config / Set show error
              */
             case 7:
                 $this->objSyncCtoCommunicationClient->setDisplayErrors($this->arrSyncSettings["syncCto_ShowError"]);
                 $this->objStepPool->step++;
                 break;
                 /**
                  * Import Config / Set referrer check
                  */
             /**
              * Import Config / Set referrer check
              */
             case 8:
                 if (is_array($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]) && count($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]) != 0) {
                     $this->objSyncCtoCommunicationClient->runMaintenance($this->arrSyncSettings["syncCto_Systemoperations_Maintenance"]);
                 }
                 $this->objStepPool->step++;
                 break;
             case 9:
                 if ($this->arrSyncSettings["syncCto_AttentionFlag"] == true) {
                     $this->objSyncCtoCommunicationClient->setAttentionFlag(false);
                 }
                 $this->log(vsprintf("Successfully finishing of synchronization client ID %s.", array(\Input::get("id"))), __CLASS__ . " " . __FUNCTION__, "INFO");
                 /**
                  * Cleanup
                  */
             /**
              * Cleanup
              */
             case 10:
                 if (in_array("temp_folders", $this->arrSyncSettings["syncCto_Systemoperations_Maintenance"])) {
                     $this->objSyncCtoCommunicationClient->purgeTempFolder();
                     $this->objSyncCtoFiles->purgeTemp();
                 }
                 $this->objStepPool->step++;
                 $this->objData->setState(SyncCtoEnum::WORK_OK);
                 $this->objData->setHtml("");
                 $this->booRefresh = true;
                 $this->intStep++;
                 break;
             default:
                 $this->objData->setState(SyncCtoEnum::WORK_OK);
                 $this->objData->setHtml("");
                 $this->booRefresh = true;
                 $this->intStep++;
                 break;
         }
     } catch (Exception $exc) {
         $this->objStepPool->step++;
         $this->log(vsprintf("Error on synchronization client ID %s with msg: %s", array(\Input::get("id"), $exc->getMessage())), __CLASS__ . " " . __FUNCTION__, "ERROR");
     }
 }
 /**
  * generate an albumalias based on the albumname and create a directory of the same name
  * and register the directory in tl files
  * @param $strAlias
  * @param \Contao\DataContainer $dc
  * @return mixed|string
  */
 public function saveCbGenerateAlias($strAlias, \Contao\DataContainer $dc)
 {
     $blnDoNotCreateDir = false;
     // get current row
     $objAlbum = GalleryCreatorAlbumsModel::findByPk($dc->id);
     if ($objAlbum === null) {
         return;
     }
     // Save assigned Dir if it was defined.
     if ($this->Input->post('FORM_SUBMIT') && strlen($this->Input->post('assignedDir'))) {
         $objAlbum->assignedDir = $this->Input->post('assignedDir');
         $objAlbum->save();
         $blnDoNotCreateDir = true;
     }
     $strAlias = standardize($strAlias);
     // if there isn't an existing albumalias generate one from the albumname
     if (!strlen($strAlias)) {
         $strAlias = standardize($dc->activeRecord->name);
     }
     // limit alias to 50 characters
     $strAlias = substr($strAlias, 0, 43);
     // remove invalid characters
     $strAlias = preg_replace("/[^a-z0-9\\_\\-]/", "", $strAlias);
     // if alias already exists add the album-id to the alias
     $objAlb = $this->Database->prepare('SELECT * FROM tl_gallery_creator_albums WHERE id!=? AND alias=?')->execute($dc->activeRecord->id, $strAlias);
     if ($objAlb->numRows) {
         $strAlias = 'id-' . $dc->id . '-' . $strAlias;
     }
     // Create default upload folder
     if ($blnDoNotCreateDir === false) {
         // create the new folder and register it in tl_files
         $objFolder = new Folder($this->uploadPath . '/' . $strAlias);
         $oFolder = Dbafs::addResource($objFolder->path, true);
         $objAlbum->assignedDir = $oFolder->uuid;
         $objAlbum->save();
         // Important
         Input::setPost('assignedDir', \StringUtil::binToUuid($objAlbum->assignedDir));
     }
     return $strAlias;
 }