public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     // Details
     $thumbnailField = new UploadField('CoverImage', _t('ImageGalleryAlbum.COVERIMAGE', 'Cover Image'));
     $thumbnailField->getValidator()->setAllowedExtensions(File::config()->app_categories['image']);
     $fields->addFieldsToTab('Root.Main', array(new TextField('AlbumName', _t('ImageGalleryAlbum.ALBUMTITLE', 'Album Title'), null, 255), new TextareaField('Description', _t('ImageGalleryAlbum.DESCRIPTION', 'Description')), $thumbnailField));
     // Image listing
     $galleryConfig = GridFieldConfig_RecordEditor::create();
     // Enable bulk image loading if necessary module is installed
     // @see composer.json/suggests
     if (class_exists('GridFieldBulkManager')) {
         $galleryConfig->addComponent(new GridFieldBulkManager());
     }
     if (class_exists('GridFieldBulkImageUpload')) {
         $galleryConfig->addComponents($imageConfig = new GridFieldBulkImageUpload('ImageID'));
         $imageConfig->setConfig('fieldsClassBlacklist', array('ImageField', 'UploadField', 'FileField'));
         if ($uploadFolder = $this->Folder()) {
             // Set upload folder - Clean up 'assets' from target path
             $path = preg_replace('/(^' . ASSETS_DIR . '\\/?)|(\\/$)/i', '', $uploadFolder->RelativePath);
             $imageConfig->setConfig('folderName', $path);
         }
     }
     // Enable image sorting if necessary module is installed
     // @see composer.json/suggests
     if (class_exists('GridFieldSortableRows')) {
         $galleryConfig->addComponent(new GridFieldSortableRows('SortOrder'));
     }
     $galleryField = new GridField('GalleryItems', 'Gallery Items', $this->GalleryItems(), $galleryConfig);
     $fields->addFieldToTab('Root.Images', $galleryField);
     return $fields;
 }
 public function getCMSFields()
 {
     $fields = new FieldList();
     $fields->push(new TabSet('Root', new Tab('Main', _t('SiteTree.TABMAIN', 'Main'), new TextField('Title', _t('UniadsObject.db_Title', 'Title')))));
     if ($this->ID) {
         $previewLink = Director::absoluteBaseURL() . 'admin/' . UniadsAdmin::config()->url_segment . '/UniadsObject/preview/' . $this->ID;
         $fields->addFieldToTab('Root.Main', new ReadonlyField('Impressions', _t('UniadsObject.db_Impressions', 'Impressions')), 'Title');
         $fields->addFieldToTab('Root.Main', new ReadonlyField('Clicks', _t('UniadsObject.db_Clicks', 'Clicks')), 'Title');
         $fields->addFieldsToTab('Root.Main', array(DropdownField::create('CampaignID', _t('UniadsObject.has_one_Campaign', 'Campaign'), DataList::create('UniadsCampaign')->map())->setEmptyString(_t('UniadsObject.Campaign_none', 'none')), DropdownField::create('ZoneID', _t('UniadsObject.has_one_Zone', 'Zone'), DataList::create('UniadsZone')->map())->setEmptyString(_t('UniadsObject.Zone_select', 'select one')), new NumericField('Weight', _t('UniadsObject.db_Weight', 'Weight (controls how often it will be shown relative to others)')), new TextField('TargetURL', _t('UniadsObject.db_TargetURL', 'Target URL')), new Treedropdownfield('InternalPageID', _t('UniadsObject.has_one_InternalPage', 'Internal Page Link'), 'Page'), new CheckboxField('NewWindow', _t('UniadsObject.db_NewWindow', 'Open in a new Window')), $file = new UploadField('File', _t('UniadsObject.has_one_File', 'Advertisement File')), $AdContent = new TextareaField('AdContent', _t('UniadsObject.db_AdContent', 'Advertisement Content')), $Starts = new DateField('Starts', _t('UniadsObject.db_Starts', 'Starts')), $Expires = new DateField('Expires', _t('UniadsObject.db_Expires', 'Expires')), new NumericField('ImpressionLimit', _t('UniadsObject.db_ImpressionLimit', 'Impression Limit')), new CheckboxField('Active', _t('UniadsObject.db_Active', 'Active')), new LiteralField('Preview', '<a href="' . $previewLink . '" target="_blank">' . _t('UniadsObject.Preview', 'Preview this advertisement') . "</a>")));
         $app_categories = File::config()->app_categories;
         $file->setFolderName($this->config()->files_dir);
         $file->getValidator()->setAllowedMaxFileSize(array('*' => $this->config()->max_file_size));
         $file->getValidator()->setAllowedExtensions(array_merge($app_categories['image'], $app_categories['flash']));
         $AdContent->setRows(10);
         $AdContent->setColumns(20);
         $Starts->setConfig('showcalendar', true);
         $Starts->setConfig('dateformat', i18n::get_date_format());
         $Starts->setConfig('datavalueformat', 'yyyy-MM-dd');
         $Expires->setConfig('showcalendar', true);
         $Expires->setConfig('dateformat', i18n::get_date_format());
         $Expires->setConfig('datavalueformat', 'yyyy-MM-dd');
         $Expires->setConfig('min', date('Y-m-d', strtotime($this->Starts ? $this->Starts : '+1 days')));
     }
     $this->extend('updateCMSFields', $fields);
     return $fields;
 }
 /**
  * @return array|scalar
  */
 public function getExtensionsAllowed()
 {
     $allCategories = File::config()->app_categories;
     $ret = array_merge($allCategories['zip'], $allCategories['doc']);
     $ret[] = 'zip';
     return $ret;
 }
 public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     // Details
     $fields->addFieldToTab('Root.Main', new TextareaField('Caption', _t('ImageGalleryItem.CAPTION', 'Caption')));
     // Create image
     $imageField = new UploadField('Image');
     $imageField->getValidator()->setAllowedExtensions(File::config()->app_categories['image']);
     $fields->addFieldToTab('Root.Main', $imageField);
     return $fields;
 }
 public function getCMSFields()
 {
     $fields = new FieldList(new TabSet('Root'));
     // Details
     $fields->addFieldToTab('Root.Main', new TextareaField('Caption', _t('MagnificGalleryItem.CAPTION', 'Caption')));
     // Create image
     $imageField = new UploadField('Image');
     $imageField->getValidator()->setAllowedExtensions(File::config()->app_categories['image']);
     $imageField->setFolderName($this->Album()->getUploadFolder());
     $fields->addFieldToTab('Root.Main', $imageField);
     // Details
     $fields->addFieldToTab('Root.Main', new TextField('VideoLink', _t('MagnificGalleryItem.VIDEOLINK', 'Video link')));
     return $fields;
 }
Example #6
0
 public static function open($file)
 {
     global $config;
     // static variable singleton
     if (!self::$config_file) {
         self::$config_file = $file;
     }
     // Check if config file exist and is readable, then include it
     if (is_readable(self::$config_file)) {
         require_once self::$config_file;
         //echo 'configuration file <b>' . self::$config_file . '</b> succesfully loaded <br />';
         self::$config = $config;
         return true;
     } else {
         throw new Exception("Config file not found or bad file permissions");
     }
 }
 /**
  * @param UploadField|\DisplayLogicWrapper $field
  * @param string                           $configVarName - allow you to switch config to check e.g. 'allowed_video_files'
  * @throws Exception
  */
 protected function configureUploadField($field, $configVarName = 'allowed_files')
 {
     $fieldName = $field->getName();
     if ($field instanceof \DisplayLogicWrapper) {
         // drill down into wrapper to get actual UploadField
         $field = $field->fieldByName($fieldName);
     }
     list($minlength, $maxlength, $pattern) = $this->fieldConstraints($fieldName, [0, 0, '']);
     $field->setAllowedMaxFileNumber($maxlength ?: null);
     // don't allow existing media to be re-attached it's a has_one so would be messy
     $allowExistingFiles = $this->config()->get('can_attach_existing');
     $field->setCanAttachExisting($allowExistingFiles);
     $field->setFolderName($this->uploadFolderName());
     // could be string for category or an array of extensions
     // try extension first, then model
     $extensions = $allowedFiles = $this->config()->get($configVarName) ?: $this()->config()->get($configVarName);
     $categories = [];
     if (!is_array($allowedFiles)) {
         // could be comma separated list of categories
         $categories = explode(',', $allowedFiles);
         // get extensions from category so we always get a list of extensions for the CMS right title
         $allCategoryExtensions = \File::config()->get('app_categories') ?: [];
         foreach ($categories as $category) {
             if (isset($allCategoryExtensions[$category])) {
                 $extensions = $allCategoryExtensions[$category];
             } else {
                 $extensions = [$category];
             }
         }
     }
     if (is_array($allowedFiles)) {
         // was an array originally, so pass merged extensions
         $field->setAllowedExtensions($extensions);
     } elseif ($categories) {
         // array of categories to apply to setAllowedFileCategories as parameters
         call_user_func_array([$field, 'setAllowedFileCategories'], $categories);
     } elseif ($allowedFiles) {
         // not an array so a category e.g. 'video'
         $field->setAllowedFileCategories($allowedFiles);
     } else {
         throw new Exception("No {$configVarName} configuration set");
     }
     $field->setRightTitle($this->fieldDecoration($fieldName, 'Label', $field->Title(), ['extensions' => implode(', ', $extensions)]));
 }
 public function getCMSFields()
 {
     // If the album is not created yet, ask first for an album title to create the folder
     if (!$this->ID) {
         $fields = new FieldList();
         $fields->push(new TextField('AlbumName', _t('MagnificGalleryAlbum.ALBUMTITLE', 'Album Title'), null, 255));
         $fields->push(new LiteralField('AlbumSaveInfos', _t('MagnificGalleryAlbum.ALBUMSAVEINFOS', 'You can add images and a description once the album is saved'), null, 255));
         return $fields;
     }
     $fields = new FieldList(new TabSet('Root'));
     // Image listing
     $galleryConfig = GridFieldConfig_RecordEditor::create();
     // Enable bulk image loading if necessary module is installed
     // @see composer.json/suggests
     if (class_exists('GridFieldBulkManager')) {
         $galleryConfig->addComponent(new GridFieldBulkManager());
     }
     if (class_exists('GridFieldBulkUpload')) {
         $galleryConfig->addComponents($imageConfig = new GridFieldBulkUpload('Image'));
         $imageConfig->setUfSetup('setFolderName', $this->getUploadFolder());
     }
     // Enable image sorting if necessary module is installed
     // @see composer.json/suggests
     if (class_exists('GridFieldSortableRows')) {
         $galleryConfig->addComponent(new GridFieldSortableRows('SortOrder'));
     } else {
         if (class_exists('GridFieldOrderableRows')) {
             $galleryConfig->addComponent(new GridFieldOrderableRows('SortOrder'));
         }
     }
     $galleryField = new GridField('GalleryItems', 'Gallery Items', $this->GalleryItems(), $galleryConfig);
     $fields->addFieldToTab('Root.Main', $galleryField);
     // Details
     $thumbnailField = new UploadField('CoverImage', _t('MagnificGalleryAlbum.COVERIMAGE', 'Cover Image'));
     $thumbnailField->getValidator()->setAllowedExtensions(File::config()->app_categories['image']);
     $thumbnailField->setFolderName($this->getUploadFolder());
     $fields->addFieldsToTab('Root.Album', array(new TextField('AlbumName', _t('MagnificGalleryAlbum.ALBUMTITLE', 'Album Title'), null, 255), new TextareaField('Description', _t('MagnificGalleryAlbum.DESCRIPTION', 'Description')), $thumbnailField));
     return $fields;
 }
 public function testPublicAdapter()
 {
     $_SERVER['SERVER_SOFTWARE'] = 'Apache/2.2.22 (Win64) PHP/5.3.13';
     $adapter = new PublicAssetAdapter($this->rootDir);
     $this->assertFileExists($this->rootDir . '/.htaccess');
     $this->assertFileNotExists($this->rootDir . '/web.config');
     $htaccess = $adapter->read('.htaccess');
     $content = $htaccess['contents'];
     // Allowed extensions set
     $this->assertContains('RewriteCond %{REQUEST_URI} !.(?i:', $content);
     foreach (File::config()->allowed_extensions as $extension) {
         $this->assertRegExp('/\\b' . preg_quote($extension) . '\\b/', $content);
     }
     // Rewrite rules
     $this->assertContains('RewriteRule .* ../framework/main.php?url=%1 [QSA]', $content);
     $this->assertContains('RewriteRule error[^\\/]*.html$ - [L]', $content);
     // Test flush restores invalid content
     \file_put_contents($this->rootDir . '/.htaccess', '# broken content');
     $adapter->flush();
     $htaccess2 = $adapter->read('.htaccess');
     $this->assertEquals($content, $htaccess2['contents']);
     // Test URL
     $this->assertEquals('/assets/AssetAdapterTest/file.jpg', $adapter->getPublicUrl('file.jpg'));
 }
 /**
  * Set this store as the new asset backend
  *
  * @param string $basedir Basedir to store assets, which will be placed beneath 'assets' folder
  */
 public static function activate($basedir)
 {
     // Assign this as the new store
     $adapter = new AssetAdapter(ASSETS_PATH . '/' . $basedir);
     $filesystem = new Filesystem($adapter);
     $filesystem->addPlugin(new FlysystemUrlPlugin());
     $backend = new AssetStoreTest_SpyStore();
     $backend->setFilesystem($filesystem);
     Injector::inst()->registerService($backend, 'AssetStore');
     // Disable legacy and set defaults
     Config::inst()->remove(get_class(new FlysystemAssetStore()), 'legacy_filenames');
     Config::inst()->update('Director', 'alternate_base_url', '/');
     DBFile::config()->force_resample = false;
     File::config()->force_resample = false;
     self::reset();
     self::$basedir = $basedir;
     // Ensure basedir exists
     SS_Filesystem::makeFolder(self::base_path());
 }
 /**
  * Creates a JSON string of all the variables that can be set in the Config
  *
  * @return string
  */
 public function JSONConfig()
 {
     $r = $this->request;
     // Remove null values and normalise leading dot
     $allExts = $r->getVar('allowedExtensions') ? explode(',', $r->getVar('allowedExtensions')) : File::config()->allowed_extensions;
     $exts = array_map(function ($item) {
         return $item[0] == '.' ? $item : '.' . $item;
     }, array_filter($allExts, 'strlen'));
     $types = explode(',', $r->getVar('allowedTypes'));
     return Convert::array2json(array('baseRoute' => Controller::join_links(Director::baseURL(), $this->Link()), 'maxFilesize' => FileAttachmentField::get_filesize_from_ini(), 'allowedExtensions' => implode(',', $exts), 'thumbnailsDir' => DROPZONE_DIR . '/images/file-icons', 'langNewFolder' => _t('AssetAdmin.NEWFOLDER', 'NewFolder'), 'iconSize' => self::ICON_SIZE, 'thumbnailWidth' => self::IMAGE_WIDTH, 'thumbnailHeight' => self::IMAGE_HEIGHT, 'defaultSort' => $this->config()->default_sort, 'defaultView' => $this->config()->default_view, 'maxCacheSize' => $this->config()->max_cache_size, 'folderExtension' => self::FOLDER_EXTENSION, 'allowSelection' => (bool) $r->getVar('allowSelection'), 'maxSelection' => (int) $r->getVar('maxSelection'), 'canUpload' => (bool) $r->getVar('canUpload'), 'canDelete' => (bool) $r->getVar('canDelete'), 'canEdit' => (bool) $r->getVar('canEdit'), 'canCreateFolder' => (bool) $r->getVar('canCreateFolder'), 'allowedTypes' => !empty($types) ? $types : null));
 }
Example #12
0
 /**
  * Synchronize the file database with the actual content of the assets
  * folder.
  */
 public function syncChildren()
 {
     $parentID = (int) $this->ID;
     // parentID = 0 on the singleton, used as the 'root node';
     $added = 0;
     $deleted = 0;
     $skipped = 0;
     // First, merge any children that are duplicates
     $duplicateChildrenNames = DB::prepared_query('SELECT "Name" FROM "File" WHERE "ParentID" = ? GROUP BY "Name" HAVING count(*) > 1', array($parentID))->column();
     if ($duplicateChildrenNames) {
         foreach ($duplicateChildrenNames as $childName) {
             // Note, we do this in the database rather than object-model; otherwise we get all sorts of problems
             // about deleting files
             $children = DB::prepared_query('SELECT "ID" FROM "File" WHERE "Name" = ? AND "ParentID" = ?', array($childName, $parentID))->column();
             if ($children) {
                 $keptChild = array_shift($children);
                 foreach ($children as $removedChild) {
                     DB::prepared_query('UPDATE "File" SET "ParentID" = ? WHERE "ParentID" = ?', array($keptChild, $removedChild));
                     DB::prepared_query('DELETE FROM "File" WHERE "ID" = ?', array($removedChild));
                 }
             } else {
                 user_error("Inconsistent database issue: SELECT ID FROM \"File\" WHERE Name = '{$childName}'" . " AND ParentID = {$parentID} should have returned data", E_USER_WARNING);
             }
         }
     }
     // Get index of database content
     // We don't use DataObject so that things like subsites doesn't muck with this.
     $dbChildren = DB::prepared_query('SELECT * FROM "File" WHERE "ParentID" = ?', array($parentID));
     $hasDbChild = array();
     if ($dbChildren) {
         foreach ($dbChildren as $dbChild) {
             $className = $dbChild['ClassName'];
             if (!$className) {
                 $className = "File";
             }
             $hasDbChild[$dbChild['Name']] = new $className($dbChild);
         }
     }
     $unwantedDbChildren = $hasDbChild;
     // if we're syncing a folder with no ID, we assume we're syncing the root assets folder
     // however the Filename field is populated with "NewFolder", so we need to set this to empty
     // to satisfy the baseDir variable below, which is the root folder to scan for new files in
     if (!$parentID) {
         $this->Filename = '';
     }
     // Iterate through the actual children, correcting the database as necessary
     $baseDir = $this->FullPath;
     // @todo this shouldn't call die() but log instead
     if ($parentID && !$this->Filename) {
         die($this->ID . " - " . $this->FullPath);
     }
     if (file_exists($baseDir)) {
         $actualChildren = scandir($baseDir);
         $ignoreRules = Filesystem::config()->sync_blacklisted_patterns;
         $allowedExtensions = File::config()->allowed_extensions;
         $checkExtensions = $this->config()->apply_restrictions_to_admin || !Permission::check('ADMIN');
         foreach ($actualChildren as $actualChild) {
             $skip = false;
             // Check ignore patterns
             if ($ignoreRules) {
                 foreach ($ignoreRules as $rule) {
                     if (preg_match($rule, $actualChild)) {
                         $skip = true;
                         break;
                     }
                 }
             }
             // Check allowed extensions, unless admin users are allowed to bypass these exclusions
             if ($checkExtensions && !is_dir($baseDir . $actualChild) && ($extension = self::get_file_extension($actualChild)) && !in_array(strtolower($extension), $allowedExtensions)) {
                 $skip = true;
             }
             if ($skip) {
                 $skipped++;
                 continue;
             }
             // A record with a bad class type doesn't deserve to exist. It must be purged!
             if (isset($hasDbChild[$actualChild])) {
                 $child = $hasDbChild[$actualChild];
                 if (!$child instanceof Folder && is_dir($baseDir . $actualChild) || $child instanceof Folder && !is_dir($baseDir . $actualChild)) {
                     DB::prepared_query('DELETE FROM "File" WHERE "ID" = ?', array($child->ID));
                     unset($hasDbChild[$actualChild]);
                 }
             }
             if (isset($hasDbChild[$actualChild])) {
                 $child = $hasDbChild[$actualChild];
                 unset($unwantedDbChildren[$actualChild]);
             } else {
                 $added++;
                 $childID = $this->constructChild($actualChild);
                 $child = DataObject::get_by_id("File", $childID);
             }
             if ($child && is_dir($baseDir . $actualChild)) {
                 $childResult = $child->syncChildren();
                 $added += $childResult['added'];
                 $deleted += $childResult['deleted'];
                 $skipped += $childResult['skipped'];
             }
             // Clean up the child record from memory after use. Important!
             $child->destroy();
             $child = null;
         }
         // Iterate through the unwanted children, removing them all
         if (isset($unwantedDbChildren)) {
             foreach ($unwantedDbChildren as $unwantedDbChild) {
                 DB::prepared_query('DELETE FROM "File" WHERE "ID" = ?', array($unwantedDbChild->ID));
                 $deleted++;
             }
         }
     } else {
         DB::prepared_query('DELETE FROM "File" WHERE "ID" = ?', array($this->ID));
     }
     return array('added' => $added, 'deleted' => $deleted, 'skipped' => $skipped);
 }
 /**
  * Check if the following path is valid
  *
  * @param type $path
  */
 protected function isValidFile($path)
 {
     $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
     $allowed = array_map('strtolower', File::config()->allowed_extensions);
     return in_array($extension, $allowed);
 }
Example #14
0
 /**
  * Hook to validate this record against a validation result
  *
  * @param ValidationResult $result
  * @param string $filename Optional filename to validate. If omitted, the current value is validated.
  * @return bool Valid flag
  */
 public function validate(ValidationResult $result, $filename = null)
 {
     if (empty($filename)) {
         $filename = $this->getFilename();
     }
     if (empty($filename) || $this->isValidFilename($filename)) {
         return true;
     }
     // Check allowed extensions
     $extensions = $this->getAllowedExtensions();
     if (empty($extensions)) {
         $extensions = File::config()->allowed_extensions;
     }
     sort($extensions);
     $message = _t('File.INVALIDEXTENSION', 'Extension is not allowed (valid: {extensions})', 'Argument 1: Comma-separated list of valid extensions', array('extensions' => wordwrap(implode(', ', $extensions))));
     $result->error($message);
     return false;
 }
Example #15
0
 /**
  * Limit allowed file extensions by specifying categories of file types.
  * These may be 'image', 'audio', 'mov', 'zip', 'flash', or 'doc'
  * See {@link File::$allowed_extensions} for details of allowed extensions
  * for each of these categories
  * 
  * @param string $category Category name
  * @param string,... $categories Additional category names
  * @return UploadField Self reference
  */
 public function setAllowedFileCategories($category)
 {
     $extensions = array();
     $knownCategories = File::config()->app_categories;
     // Parse arguments
     $categories = func_get_args();
     if (func_num_args() === 1 && is_array(reset($categories))) {
         $categories = reset($categories);
     }
     // Merge all categories into list of extensions
     foreach (array_filter($categories) as $category) {
         if (isset($knownCategories[$category])) {
             $extensions = array_merge($extensions, $knownCategories[$category]);
         } else {
             user_error("Unknown file category: {$category}", E_USER_ERROR);
         }
     }
     return $this->setAllowedExtensions($extensions);
 }
 public function testFolderConstructChild()
 {
     $orig = File::config()->class_for_file_extension;
     File::config()->class_for_file_extension = array('gif' => 'FileTest_MyCustomFile');
     $folder1 = $this->objFromFixture('Folder', 'folder1');
     $fileID = $folder1->constructChild('myfile.gif');
     $file = DataObject::get_by_id('File', $fileID);
     $this->assertEquals('FileTest_MyCustomFile', get_class($file));
     File::config()->class_for_file_extension = $orig;
 }
 /**
  * Form used for importing data from the client
  * @return {Form} Form to be used in the popup
  */
 public function ImportFromClientForm()
 {
     if (!Permission::check('ADMIN')) {
         Security::permissionFailure($this);
         return;
     }
     $uploadField = new FileField('ImportFile', _t('CodeBank.EXPORT_FILE', '_Client Export File'));
     $uploadField->getValidator()->setAllowedExtensions(array('cbexport'));
     File::config()->allowed_extensions = array('cbexport');
     $fields = new FieldList(new LiteralField('ImportWarning', '<p class="message warning">' . _t('CodeBank.IMPORT_DATA_WARNING', '_Warning clicking import will erase all snippets in the database, it is recommended you backup your database before proceeding') . '</p>'), new TabSet('Root', new Tab('Main', $uploadField, new CheckboxField('AppendData', _t('CodeBank.APPEND_IMPORT', '_Import and Append Data (keep your existing data however appending may cause duplicates)')))));
     $actions = new FieldList(FormAction::create('doImportData', _t('CodeBank.IMPORT', '_Import'))->addExtraClass('ss-ui-button ss-ui-action-constructive')->setAttribute('data-icon', 'accept')->setUseButtonTag(true));
     $validator = new RequiredFields('ImportFile');
     $form = new Form($this, 'ImportFromClientForm', $fields, $actions, $validator);
     $form->addExtraClass('member-profile-form');
     return $form;
 }
 /**
  * Handles media objects from kapost
  * @param {mixed} $blog_id Site Config related to this content object
  * @param {array} $content Content object to be handled
  * @return {xmlrpcresp} XML-RPC Response object
  */
 protected function newMediaObject($blog_id, $content)
 {
     $fileName = $content['name'];
     $validator = new Upload_Validator(array('name' => $fileName));
     $validator->setAllowedExtensions(File::config()->allowed_extensions);
     //Verify we have a valid extension
     if ($validator->isValidExtension() == false) {
         return $this->httpError(403, _t('KapostService.FILE_NOT_ALLOWED', '_File extension is not allowed'));
     }
     //Generate default filename
     $nameFilter = FileNameFilter::create();
     $file = $nameFilter->filter($fileName);
     while ($file[0] == '_' || $file[0] == '.') {
         $file = substr($file, 1);
     }
     $doubleBarrelledExts = array('.gz', '.bz', '.bz2');
     $ext = "";
     if (preg_match('/^(.*)(\\.[^.]+)$/', $file, $matches)) {
         $file = $matches[1];
         $ext = $matches[2];
         // Special case for double-barrelled
         if (in_array($ext, $doubleBarrelledExts) && preg_match('/^(.*)(\\.[^.]+)$/', $file, $matches)) {
             $file = $matches[1];
             $ext = $matches[2] . $ext;
         }
     }
     $origFile = $file;
     //Find the kapost media folder
     $kapostMediaFolder = Folder::find_or_make($this->config()->kapost_media_folder);
     if (file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) {
         if (self::config()->duplicate_assets == 'overwrite') {
             $obj = File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename . $file . $ext))->first();
             if (!empty($obj) && $obj !== false && $obj->ID > 0) {
                 //Update the Title for the image
                 $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name));
                 $obj->write();
                 //Write the file to the file system
                 $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w');
                 fwrite($f, $content['bits']);
                 fclose($f);
                 return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL());
             }
             return $this->httpError(404, _t('KapostService.FILE_NOT_FOUND', '_File not found'));
         } else {
             if (self::config()->duplicate_assets == 'ignore') {
                 return $this->httpError(409, _t('KapostService.DUPLICATE_FILE', '_Duplicate file detected, please rename the file and try again'));
             } else {
                 if (self::config()->duplicate_assets == 'smart_rename' && file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) {
                     $obj = File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename . $file . $ext))->first();
                     if (!empty($obj) && $obj !== false && $obj->ID > 0) {
                         $fileHash = sha1_file($kapostMediaFolder->getFullPath() . '/' . $file . $ext);
                         if ($fileHash == sha1($content['bits'])) {
                             return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL());
                         }
                     }
                 }
                 $i = 1;
                 while (file_exists($kapostMediaFolder->getFullPath() . '/' . $file . $ext)) {
                     $i++;
                     $oldFile = $file;
                     if (strpos($file, '.') !== false) {
                         $file = preg_replace('/[0-9]*(\\.[^.]+$)/', $i . '\\1', $file);
                     } else {
                         if (strpos($file, '_') !== false) {
                             $file = preg_replace('/_([^_]+$)/', '_' . $i, $file);
                         } else {
                             $file .= '_' . $i;
                         }
                     }
                     if ($oldFile == $file && $i > 2) {
                         return $this->httpError(500, _t('KapostService.FILE_RENAME_FAIL', '_Could not fix {filename} with {attempts} attempts', array('filename' => $file . $ext, 'attempts' => $i)));
                     }
                 }
                 //Write the file to the file system
                 $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w');
                 fwrite($f, $content['bits']);
                 fclose($f);
                 //Write the file to the database
                 $className = File::get_class_for_file_extension(substr($ext, 1));
                 $obj = new $className();
                 $obj->Name = $file . $ext;
                 $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name));
                 $obj->FileName = $kapostMediaFolder->getRelativePath() . '/' . $file . $ext;
                 $obj->ParentID = $kapostMediaFolder->ID;
                 //If subsites is enabled add it to the correct subsite
                 if (File::has_extension('FileSubsites')) {
                     $obj->SubsiteID = $blog_id;
                 }
                 $obj->write();
                 $this->extend('updateNewMediaAsset', $blog_id, $content, $obj);
                 return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL());
             }
         }
     } else {
         //Write the file to the file system
         $f = fopen($kapostMediaFolder->getFullPath() . '/' . $file . $ext, 'w');
         fwrite($f, $content['bits']);
         fclose($f);
         //Write the file to the database
         $className = File::get_class_for_file_extension(substr($ext, 1));
         $obj = new $className();
         $obj->Name = $file . $ext;
         $obj->Title = !empty($content['alt']) ? $content['alt'] : str_replace(array('-', '_'), ' ', preg_replace('/\\.[^.]+$/', '', $obj->Name));
         $obj->FileName = $kapostMediaFolder->getRelativePath() . '/' . $file . $ext;
         $obj->ParentID = $kapostMediaFolder->ID;
         //If subsites is enabled add it to the correct subsite
         if (File::has_extension('FileSubsites')) {
             $obj->SubsiteID = $blog_id;
         }
         $obj->write();
         $this->extend('updateNewMediaAsset', $blog_id, $content, $obj);
         return array('id' => $obj->ID, 'url' => $obj->getAbsoluteURL());
     }
 }
 /**
  * Render server configuration file from a template file
  *
  * @param string $template
  * @return DBHTMLText Rendered results
  */
 protected function renderTemplate($template)
 {
     // Build allowed extensions
     $allowedExtensions = new ArrayList();
     foreach (\File::config()->allowed_extensions as $extension) {
         if ($extension) {
             $allowedExtensions->push(new \ArrayData(array('Extension' => preg_quote($extension))));
         }
     }
     $viewer = new \SSViewer(array($template));
     return (string) $viewer->process(new \ArrayData(array('AllowedExtensions' => $allowedExtensions)));
 }
 /**
  * @return array|scalar
  */
 public function getExtensionsAllowed()
 {
     $allCategories = File::config()->app_categories;
     return array_merge($allCategories['image'], array('svg'));
 }
Example #21
0
 /**
  * Returns the files and subfolders contained in the currently selected folder,
  * defaulting to the root node. Doubles as search results, if any search parameters
  * are set through {@link SearchForm()}.
  * 
  * @return SS_List
  */
 public function getList()
 {
     $folder = $this->currentPage();
     $context = $this->getSearchContext();
     // Overwrite name filter to search both Name and Title attributes
     $context->removeFilterByName('Name');
     $params = $this->getRequest()->requestVar('q');
     $list = $context->getResults($params);
     // Don't filter list when a detail view is requested,
     // to avoid edge cases where the filtered list wouldn't contain the requested
     // record due to faulty session state (current folder not always encoded in URL, see #7408).
     if (!$folder->ID && $this->getRequest()->requestVar('ID') === null && $this->getRequest()->param('ID') == 'field') {
         return $list;
     }
     // Re-add previously removed "Name" filter as combined filter
     // TODO Replace with composite SearchFilter once that API exists
     if (!empty($params['Name'])) {
         $list = $list->filterAny(array('Name:PartialMatch' => $params['Name'], 'Title:PartialMatch' => $params['Name']));
     }
     // Always show folders at the top
     $list = $list->sort('(CASE WHEN "File"."ClassName" = \'Folder\' THEN 0 ELSE 1 END), "Name"');
     // If a search is conducted, check for the "current folder" limitation.
     // Otherwise limit by the current folder as denoted by the URL.
     if (empty($params) || !empty($params['CurrentFolderOnly'])) {
         $list = $list->filter('ParentID', $folder->ID);
     }
     // Category filter
     if (!empty($params['AppCategory']) && !empty(File::config()->app_categories[$params['AppCategory']])) {
         $exts = File::config()->app_categories[$params['AppCategory']];
         $list = $list->filter('Name:PartialMatch', $exts);
     }
     // Date filter
     if (!empty($params['CreatedFrom'])) {
         $fromDate = new DateField(null, null, $params['CreatedFrom']);
         $list = $list->filter("Created:GreaterThanOrEqual", $fromDate->dataValue() . ' 00:00:00');
     }
     if (!empty($params['CreatedTo'])) {
         $toDate = new DateField(null, null, $params['CreatedTo']);
         $list = $list->filter("Created:LessThanOrEqual", $toDate->dataValue() . ' 23:59:59');
     }
     return $list;
 }
Example #22
0
 /**
  * Returns the files and subfolders contained in the currently selected folder,
  * defaulting to the root node. Doubles as search results, if any search parameters
  * are set through {@link SearchForm()}.
  * 
  * @return SS_List
  */
 public function getList()
 {
     $folder = $this->currentPage();
     $context = $this->getSearchContext();
     // Overwrite name filter to search both Name and Title attributes
     $context->removeFilterByName('Name');
     $params = $this->request->requestVar('q');
     $list = $context->getResults($params);
     // Don't filter list when a detail view is requested,
     // to avoid edge cases where the filtered list wouldn't contain the requested
     // record due to faulty session state (current folder not always encoded in URL, see #7408).
     if (!$folder->ID && $this->request->requestVar('ID') === null && $this->request->param('ID') == 'field') {
         return $list;
     }
     // Re-add previously removed "Name" filter as combined filter
     // TODO Replace with composite SearchFilter once that API exists
     if (isset($params['Name'])) {
         $list = $list->where(sprintf('"Name" LIKE \'%%%s%%\' OR "Title" LIKE \'%%%s%%\'', Convert::raw2sql($params['Name']), Convert::raw2sql($params['Name'])));
     }
     // Always show folders at the top
     $list = $list->sort('(CASE WHEN "File"."ClassName" = \'Folder\' THEN 0 ELSE 1 END), "Name"');
     // If a search is conducted, check for the "current folder" limitation.
     // Otherwise limit by the current folder as denoted by the URL.
     if (!$params || @$params['CurrentFolderOnly']) {
         $list = $list->filter('ParentID', $folder->ID);
     }
     // Category filter
     if (isset($params['AppCategory'])) {
         if (isset(File::config()->app_categories[$params['AppCategory']])) {
             $exts = File::config()->app_categories[$params['AppCategory']];
         } else {
             $exts = array();
         }
         $categorySQLs = array();
         foreach ($exts as $ext) {
             $categorySQLs[] = '"File"."Name" LIKE \'%.' . $ext . '\'';
         }
         // TODO Use DataList->filterAny() once OR connectives are implemented properly
         if (count($categorySQLs) > 0) {
             $list = $list->where('(' . implode(' OR ', $categorySQLs) . ')');
         }
     }
     return $list;
 }
 /**
  * Set this store as the new asset backend
  *
  * @param string $basedir Basedir to store assets, which will be placed beneath 'assets' folder
  */
 public static function activate($basedir)
 {
     // Assign this as the new store
     $publicAdapter = new PublicAssetAdapter(ASSETS_PATH . '/' . $basedir);
     $publicFilesystem = new Filesystem($publicAdapter, ['visibility' => AdapterInterface::VISIBILITY_PUBLIC]);
     $protectedAdapter = new ProtectedAssetAdapter(ASSETS_PATH . '/' . $basedir . '/.protected');
     $protectedFilesystem = new Filesystem($protectedAdapter, ['visibility' => AdapterInterface::VISIBILITY_PRIVATE]);
     $backend = new AssetStoreTest_SpyStore();
     $backend->setPublicFilesystem($publicFilesystem);
     $backend->setProtectedFilesystem($protectedFilesystem);
     Injector::inst()->registerService($backend, 'AssetStore');
     // Assign flysystem backend to generated asset handler at the same time
     $generated = new FlysystemGeneratedAssetHandler();
     $generated->setFilesystem($publicFilesystem);
     Injector::inst()->registerService($generated, 'GeneratedAssetHandler');
     Requirements::backend()->setAssetHandler($generated);
     // Disable legacy and set defaults
     Config::inst()->remove(get_class(new FlysystemAssetStore()), 'legacy_filenames');
     Config::inst()->update('Director', 'alternate_base_url', '/');
     DBFile::config()->force_resample = false;
     File::config()->force_resample = false;
     self::reset();
     self::$basedir = $basedir;
     // Ensure basedir exists
     \Filesystem::makeFolder(self::base_path());
 }
 /**
  * Gets the list of all extensions for testing
  *
  * @return array
  */
 public function allowedExtensions()
 {
     $args = array();
     foreach (array_filter(File::config()->allowed_extensions) as $ext) {
         $args[] = array($ext);
     }
     return $args;
 }