function index()
 {
     $posts = $this->request->postVars();
     $filename = $posts['filename'];
     $surveyID = intval($posts['surveyID']);
     if (!$filename || !Member::currentUser() || !$surveyID || !($Survey = Survey::get()->filter('ID', $surveyID)->first())) {
         return false;
     }
     $folder = Folder::find_or_make('jsonFormFiles');
     $fullFileName = Director::baseFolder() . '/' . $folder->getRelativePath() . $filename . '.json';
     $jsonString = '{"name":"' . $Survey->Name . '","startDate": "' . $Survey->StartDate . '", "endDate": "' . $Survey->EndDate . '","sections": [';
     foreach ($Survey->Sections() as $Section) {
         $jsonString .= '{"Title": "' . $Section->Title . '","Descripton": "' . $Section->Description . '","sectionQuestions": [';
         foreach ($Section->SurveyQuestions() as $SQ) {
             $jsonString .= '{"number": "' . $SQ->Number . '","title": "' . $SQ->Title . '","description":"' . $SQ->Description . '","helpText": "' . $SQ->HelpText . '","questions": [';
             foreach ($SQ->Questions() as $Question) {
                 $jsonString .= $Question->renderJson();
             }
             $jsonString = rtrim($jsonString, ",");
             $jsonString .= ']},';
         }
         $jsonString = rtrim($jsonString, ",");
         $jsonString .= ']},';
     }
     $jsonString = rtrim($jsonString, ",");
     $jsonString .= ']}';
     file_put_contents($fullFileName, $jsonString);
     $Survey->LastJsonGenerated = SS_Datetime::now()->getValue();
     $Survey->write();
 }
 protected function importMedia($item, $page)
 {
     $source = $item->getSource();
     $params = $this->importer->getParams();
     $folder = $params['AssetsPath'];
     $content = $item->Content;
     if ($folder) {
         $folderId = Folder::find_or_make($folder)->ID;
     }
     $url = trim(preg_replace('~^[a-z]+://~', null, $source->BaseUrl), '/');
     $pattern = sprintf('~[a-z]+://%s/wp-content/uploads/[^"]+~', $url);
     if (!preg_match_all($pattern, $page->Content, $matches)) {
         return;
     }
     foreach ($matches[0] as $match) {
         if (!($contents = @file_get_contents($match))) {
             continue;
         }
         $name = basename($match);
         $path = Controller::join_links(ASSETS_PATH, $folder, $name);
         $link = Controller::join_links(ASSETS_DIR, $folder, $name);
         file_put_contents($path, $contents);
         $page->Content = str_replace($match, $link, $page->Content);
     }
     Filesystem::sync($folderId);
     $page->write();
 }
 public function testCreateWithFilenameWithSubfolder()
 {
     // Note: We can't use fixtures/setUp() for this, as we want to create the db record manually.
     // Creating the folder is necessary to avoid having "Filename" overwritten by setName()/setRelativePath(),
     // because the parent folders don't exist in the database
     $folder = Folder::find_or_make('/FileTest/');
     $testfilePath = 'assets/FileTest/CreateWithFilenameHasCorrectPath.txt';
     // Important: No leading slash
     $fh = fopen(BASE_PATH . '/' . $testfilePath, "w");
     fwrite($fh, str_repeat('x', 1000000));
     fclose($fh);
     $file = new File();
     $file->Filename = $testfilePath;
     // TODO This should be auto-detected
     $file->ParentID = $folder->ID;
     $file->write();
     $this->assertEquals('CreateWithFilenameHasCorrectPath.txt', $file->Name, '"Name" property is automatically set from "Filename"');
     $this->assertEquals($testfilePath, $file->Filename, '"Filename" property remains unchanged');
     // TODO This should be auto-detected, see File->updateFilesystem()
     // $this->assertInstanceOf('Folder', $file->Parent(), 'Parent folder is created in database');
     // $this->assertFileExists($file->Parent()->getFullPath(), 'Parent folder is created on filesystem');
     // $this->assertEquals('FileTest', $file->Parent()->Name);
     // $this->assertInstanceOf('Folder', $file->Parent()->Parent(), 'Grandparent folder is created in database');
     // $this->assertFileExists($file->Parent()->Parent()->getFullPath(),
     // 'Grandparent folder is created on filesystem');
     // $this->assertEquals('assets', $file->Parent()->Parent()->Name);
 }
 public function squareImage()
 {
     Folder::find_or_make(Director::baseFolder() . '/assets/ytimages');
     if (!file_exists(Director::baseFolder() . '/assets/ytimages/' . $this->Code . '.png')) {
         //Your Image
         $imgSrc = "http://img.youtube.com/vi/{$this->Code}/hqdefault.jpg";
         //getting the image dimensions
         list($width, $height) = getimagesize($imgSrc);
         //saving the image into memory (for manipulation with GD Library)
         $myImage = imagecreatefromjpeg($imgSrc);
         // calculating the part of the image to use for thumbnail
         if ($width > $height) {
             $y = 0;
             $x = ($width - $height) / 2;
             $smallestSide = $height;
         } else {
             $x = 0;
             $y = ($height - $width) / 2;
             $smallestSide = $width;
         }
         // copying the part into thumbnail
         $thumbSize = 120;
         $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
         imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
         imagepng($thumb, Director::baseFolder() . '/assets/ytimages/' . $this->Code . '.png');
     }
     return '/assets/ytimages/' . $this->Code . '.png';
 }
 public function readFolder($folder = "")
 {
     $folderPath = ASSETS_PATH . '/' . $folder;
     if (!file_exists($folderPath)) {
         $this->httpError(404);
     }
     return Folder::find_or_make(str_replace(ASSETS_DIR, "", $folderPath));
 }
 function checkFolder()
 {
     // Ensure the album folder exists
     if (!(($folder = $this->Folder()) && $folder->exists()) && $this->URLSegment && (($page = $this->ImageGalleryPage()) && $page->exists()) && (($rootFolder = $page->RootFolder()) && $rootFolder->exists())) {
         $folder = Folder::find_or_make("image-gallery/{$rootFolder->Name}/{$this->URLSegment}");
         $this->FolderID = $folder->ID;
     }
 }
 function checkFolder()
 {
     // Ensure root folder exists, but avoid saving folders like "new-image-gallery-page"
     if ($this->exists() && !(($folder = $this->RootFolder()) && $folder->exists()) && $this->URLSegment) {
         $folder = Folder::find_or_make("image-gallery/{$this->URLSegment}");
         $this->RootFolderID = $folder->ID;
     }
 }
 /**
  * Specify the pdf location
  * 
  * @param string $folder The name of the desired folder. Creates a new one if folder doesn't exist.
  */
 public function setFolderName($folder = null)
 {
     if ($folder) {
         $folder = Folder::find_or_make($folder);
         $this->folderID = $folder->ID;
         $folder = str_replace('/assets/', '', $folder->Url);
         $this->folder = rtrim($this->folder . $folder, '/') . '/';
     }
 }
 public function updateCMSFields(\FieldList $oFields)
 {
     Folder::find_or_make('responsive-gallery');
     $aGalleryImagesFields = array();
     if ($this->owner->ID > 0) {
         $oFields->addFieldsToTab('Root.' . _t('ResponsiveGalleryExtension.GALLERYIMAGES_TAB', 'Gallery Images'), $this->getFieldsForImagesTab());
         $oFields->addFieldsToTab('Root.' . _t('ResponsiveGalleryExtension.GALLERYSETTINGS_TAB', 'Gallery Settings'), $this->getFieldsForSettingsTab());
     }
 }
 /**
  * sets up base file and folder ready for file generating
  * @param $filename
  */
 public function __construct($filename)
 {
     $folder = Folder::find_or_make('/ics-files/' . $filename);
     $this->fileName = strtolower($filename);
     $this->fileObject = new File();
     $this->fileObject->SetName($this->fileName . ".ics");
     $this->fileObject->setParentID($folder->ID);
     $this->fileObject->write();
     $this->filePath = $this->fileObject->getFullPath();
 }
 public function setUp()
 {
     parent::setUp();
     $this->folder = Folder::find_or_make(ASSETS_DIR . '/versionedfiles-test');
     $file = $this->folder->getFullPath() . 'test-file.txt';
     file_put_contents($file, 'first-version');
     $this->file = new File();
     $this->file->ParentID = $this->folder->ID;
     $this->file->Filename = $this->folder->getFilename() . 'test-file.txt';
     $this->file->write();
     SecurityToken::disable();
 }
 protected function file2FolderFilename($filename, $withoutBase = false)
 {
     if (self::$save_pdfs_here) {
         $folder = Director::baseFolder() . "/" . self::$save_pdfs_here . "/";
         $folderObject = Folder::find_or_make($folder);
         if ($withoutBase) {
             $folderFilename = $folderObject->getRelativePath() . $filename;
         } else {
             $folderFilename = $folderObject->getFullPath() . $filename;
         }
         return $folderFilename;
     }
 }
 /**
  * Save an file passed from a form post into this object.
  * 
  * @param $tmpFile array Indexed array that PHP generated for every file it uploads.
  * @param $folderPath string Folder path relative to /assets
  * @return Boolean|string Either success or error-message.
  */
 public function load($tmpFile, $folderPath = false)
 {
     if (!$folderPath) {
         $folderPath = Config::inst()->get('Upload', 'uploads_folder');
     }
     // @TODO This puts a HUGE limitation on files especially when lots
     // have been uploaded.
     $base = Director::baseFolder();
     $parentFolder = Folder::find_or_make($folderPath);
     // Generate default filename
     $fileArray = explode('/', $tmpFile);
     $fileName = $fileArray[count($fileArray) - 1];
     $nameFilter = FileNameFilter::create();
     $file = $nameFilter->filter($fileName);
     $fileName = basename($file);
     $relativeFilePath = ASSETS_DIR . "/" . $folderPath . "/{$fileName}";
     // if filename already exists, version the filename (e.g. test.gif to test1.gif)
     while (file_exists("{$base}/{$relativeFilePath}")) {
         $i = isset($i) ? $i + 1 : 2;
         $oldFilePath = $relativeFilePath;
         // make sure archives retain valid extensions
         if (substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.gz')) == '.tar.gz' || substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.bz2')) == '.tar.bz2') {
             $relativeFilePath = preg_replace('/[0-9]*(\\.tar\\.[^.]+$)/', $i . '\\1', $relativeFilePath);
         } else {
             if (strpos($relativeFilePath, '.') !== false) {
                 $relativeFilePath = preg_replace('/[0-9]*(\\.[^.]+$)/', $i . '\\1', $relativeFilePath);
             } else {
                 if (strpos($relativeFilePath, '_') !== false) {
                     $relativeFilePath = preg_replace('/_([^_]+$)/', '_' . $i, $relativeFilePath);
                 } else {
                     $relativeFilePath .= '_' . $i;
                 }
             }
         }
         if ($oldFilePath == $relativeFilePath && $i > 2) {
             user_error("Couldn't fix {$relativeFilePath} with {$i} tries", E_USER_ERROR);
         }
     }
     if (file_exists($tmpFile) && copy($tmpFile, $base . "/" . $relativeFilePath)) {
         $this->owner->ParentID = $parentFolder->ID;
         // This is to prevent it from trying to rename the file
         $this->owner->Name = basename($relativeFilePath);
         $this->owner->write();
         return true;
     } else {
         return false;
     }
 }
 /**
  * Find or make assets folder
  * called from onBeforeWrite.
  *
  * @param string $url
  * @param bool   $doWrite
  *
  * @return Folder|null
  */
 public function findOrMakeAssetsFolder($url, $doWrite = true)
 {
     $owner = $this->owner;
     $dir = Folder::find_or_make($url);
     $owner->AssetsFolderID = $dir->ID;
     if ($doWrite) {
         $owner->write();
     }
     //Special case for when creating a new subsite
     //the directory will need to be associated with the subsite
     if ($owner->ClassName == 'Subsite') {
         $dir->SubsiteID = $owner->ID;
         $dir->write();
     }
     return $dir;
 }
 /**
  * Implement this method in the task subclass to
  * execute via the TaskRunner
  */
 public function run($request)
 {
     $currentSite = Multisites::inst()->getCurrentSite();
     $folderName = $currentSite->Host ? $currentSite->Host : "site-{$currentSite->ID}";
     $folder = Folder::find_or_make($folderName);
     $files = File::get()->filter('ParentID', array(0))->exclude('ID', $folder->ID);
     if (!$files->count()) {
         return;
     }
     foreach ($files as $file) {
         if (file_exists($file->getFullPath())) {
             $file->ParentID = $folder->ID;
             $file->write();
             echo $file->Filename . ' moved <br />';
         }
     }
 }
 /**
  * Adds dropdown field for album folders (subfolders inside assets/cwsoft-foldergallery)
  *
  * @return modified backend fields
  */
 function getCMSFields()
 {
     // create folder assets/cwsoft-foldergallery if not already exists
     Folder::find_or_make('cwsoft-foldergallery');
     // get default CMS fields
     $fields = parent::getCMSFields();
     // get "cwsoft-foldergallery" folder object
     $album = Folder::get()->filter('Filename', 'assets/cwsoft-foldergallery/')->First();
     if (!$album) {
         return $fields;
     }
     // add dropdown field with album folders (subfolders of assets/cwsoft-foldergallery)
     $tree = new TreeDropdownField('AlbumFolderID', _t('cwsFolderGalleryPage.CHOOSE_IMAGE_FOLDER', 'Choose image folder (subfolder assets/cwsoft-foldergallery/)'), 'Folder');
     $tree->setTreeBaseID((int) $album->ID);
     $fields->addFieldToTab('Root.Main', $tree, 'Content');
     return $fields;
 }
Exemple #17
0
 public function toFile($filename = "file", $folder = "PDF")
 {
     $filename = $this->addFileExt($filename);
     $filedir = ASSETS_DIR . "/{$folder}/{$filename}";
     $filepath = ASSETS_PATH . DIRECTORY_SEPARATOR . $folder . DIRECTORY_SEPARATOR . $filename;
     $folder = Folder::find_or_make($folder);
     $output = $this->output();
     if ($fh = fopen($filepath, 'w')) {
         fwrite($fh, $output);
         fclose($fh);
     }
     $file = new File();
     $file->setName($filename);
     $file->Filename = $filedir;
     $file->ParentID = $folder->ID;
     $file->write();
     return $file;
 }
 private function getFileByURL($url, $fileName)
 {
     $folder = Folder::find_or_make(self::$media_upload_folder);
     // relative to assets
     // create the file in database (sets title and safely names)
     $file = new Image();
     $file->ParentID = $folder->ID;
     $file->setName($fileName);
     $file->write();
     // download the file
     $fp = fopen($file->getFullPath(), 'w');
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_FILE, $fp);
     $data = curl_exec($ch);
     curl_close($ch);
     fclose($fp);
     return $file;
 }
 public function getDummyPortrait()
 {
     $dummyName = $this->stat('dummy_image');
     $uploadPath = $this->stat('upload_path');
     $uploadFolder = Folder::find_or_make($uploadPath);
     $dummyPic = Image::find(join('/', [$uploadPath, $dummyName]));
     if (!$dummyPic) {
         //create it
         $defaultDummy = join('/', [BASE_PATH, $this->stat('default_dummy')]);
         $assetsDummy = join('/', [BASE_PATH, 'assets', $uploadPath, $dummyName]);
         if (copy($defaultDummy, $assetsDummy)) {
             $dummyPic = Image::create();
             $dummyPic->setFilename(join('/', [$uploadFolder->getRelativePath(), $dummyName]));
             $dummyPic->ParentID = $uploadFolder->ID;
             $dummyPic->write();
         }
     }
     return $dummyPic;
 }
 function setUp()
 {
     parent::setUp();
     // clear File to start.
     $files = DataObject::get("File");
     if ($files) {
         foreach ($files as $f) {
             $f->deleteDatabaseOnly();
         }
     }
     $folder = Folder::find_or_make('/dynamic-templates/');
     $test1 = $this->setUpTemplate($folder, 'tmp-TemplateNoManifest');
     $test2 = $this->setUpTemplate($folder, 'tmp-TemplateWithManifest');
     $this->recurse_copy(Director::baseFolder() . "/dynamictemplate/tests/TemplateNoManifest", Director::baseFolder() . "/assets/dynamic-templates/tmp-TemplateNoManifest");
     $this->recurse_copy(Director::baseFolder() . "/dynamictemplate/tests/TemplateWithManifest", Director::baseFolder() . "/assets/dynamic-templates/tmp-TemplateWithManifest");
     $test1->syncChildren();
     $test2->syncChildren();
     //		$this->dump_files("end of setUp");
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if ($this->isChanged('YouTubeID') && $this->YouTubeID) {
         // if($this->VideoThumbnail()->exists()) {
         // 	$this->VideoThumbnail()->delete();
         // }
         $img = @file_get_contents("http://img.youtube.com/vi/{$this->YouTubeID}/0.jpg");
         if ($img) {
             $folder = Folder::find_or_make('video-thumbnails');
             $path = $folder->Filename . "presentation-{$this->ID}-" . uniqid() . ".jpg";
             $fh = fopen(Director::baseFolder() . "/" . $path, 'wb');
             fwrite($fh, $img);
             fclose($fh);
             $image = Image::create(array('Filename' => $path, 'Name' => "presentation-{$this->ID}.jpg", 'Title' => "presentation-{$this->ID}"));
             $image->write();
             $this->VideoThumbnailID = $image->ID;
         }
     }
 }
 /**
  * Does the work of creating a new RootFolder, saves the relation in the extended DataObject
  */
 protected function createRootFolder()
 {
     //get path to parent folder
     $parent = $this->owner->hasExtension('Hierarchy') ? $this->owner->getParent() : null;
     if (is_a($parent, 'Page') && ($parentFolder = $parent->RootFolder())) {
         $folderRoot = $parent->getRootFolderName();
     } else {
         //fallback to classes folder_root which is defined in your config.yml
         $folderRoot = $this->getFolderRoot() . '/';
     }
     if ($folderRoot == '/') {
         $folderRoot = getFolderRoot() . '/';
     }
     $folder = Folder::find_or_make($folderRoot . $this->owner->URLSegment);
     $folder->Title = $this->owner->Title;
     $folder->setName($this->owner->URLSegment);
     $folder->write();
     $this->owner->RootFolderID = $folder->ID;
     $this->owner->write();
 }
 /**
  * Save Snapshots of extension in assets folder
  *
  * @param string $thumbnailUrl, $extensionName
  * @return int
  */
 public static function save_snapshot($thumbnailUrl, $extensionName)
 {
     $folderToSave = 'assets/Uploads/Snapshots/';
     $folderObject = Folder::get()->filter("Filename", $folderToSave)->first();
     if (!$folderObject) {
         $folderObject = Folder::find_or_make('Uploads/Snapshots/');
         $folderObject->write();
     }
     $fileExtension = preg_replace('/^.*\\.([^.]+)$/D', '$1', $thumbnailUrl);
     $thumbnailBaseName = str_replace('/', '-', $extensionName);
     $thumbnailName = $thumbnailBaseName . '-thumbnail.' . $fileExtension;
     $ch = curl_init();
     $timeout = 30;
     curl_setopt($ch, CURLOPT_URL, $thumbnailUrl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
     $data = curl_exec($ch);
     $response = curl_getinfo($ch);
     curl_close($ch);
     if ($response['http_code'] == '404') {
         throw new InvalidArgumentException("Image not found on given Url Please check 'Snapshot' field in composer.json file");
     }
     $imageContent = $data;
     if ($folderObject) {
         $thumbnailFile = fopen(BASE_PATH . DIRECTORY_SEPARATOR . $folderToSave . $thumbnailName, 'w');
         fwrite($thumbnailFile, $imageContent);
         fclose($thumbnailFile);
     } else {
         throw new InvalidArgumentException("Could not create {$folderToSave} , Please create it mannually ");
     }
     if ($thumbnailObject = Image::get()->filter("Name", $thumbnailName)->first()) {
         return $thumbnailObject->ID;
     } else {
         $thumbnailObject = new Image();
         $thumbnailObject->ParentID = $folderObject->ID;
         $thumbnailObject->Name = $thumbnailName;
         $thumbnailObject->OwnerID = Member::currentUser() ? Member::currentUser()->ID : 0;
         $thumbnailObject->write();
         return $thumbnailObject->ID;
     }
 }
 /**
  * Ensure this field is secured, but does not write changes to the database
  */
 public function makeSecure()
 {
     // Skip if disabled or already secure
     if (!$this->getIsSecurityEnabled() || $this->owner->getIsSecure()) {
         return;
     }
     // Ensure folder exists
     $folder = $this->owner->Folder();
     if (!$folder || !$folder->exists()) {
         // Create new folder in default location
         $folder = Folder::find_or_make($this->owner->config()->secure_folder_name);
         $this->owner->FolderID = $folder->ID;
     } elseif ($this->isFolderSecured($folder)) {
         // If folder exists and is secure stop
         return;
     }
     // Make secure
     $folder->CanViewType = 'OnlyTheseUsers';
     $folder->ViewerGroups()->add($this->findAdminGroup());
     $folder->write();
 }
 function Form()
 {
     if ($this->request->requestVar('_REDIRECT_BACK_URL')) {
         $url = $this->request->requestVar('_REDIRECT_BACK_URL');
     } else {
         if ($this->request->getHeader('Referer')) {
             $url = $this->request->getHeader('Referer');
         } else {
             $url = Director::baseURL();
         }
     }
     $folder = Folder::find_or_make("ErrorScreenshots");
     $whatDidYouTryDoField = new TextareaField('WhatDidYouTryToDo', 'What did you try to do');
     $whatDidYouTryDoField->setRows(3);
     $whatWentWrongField = new TextareaField('WhatWentWrong', 'What went wrong');
     $whatWentWrongField->setRows(3);
     $screenshotField = new FileField('Screenshot', 'To take a screenshot press the PRT SCR button on your keyboard, then open MS Word or MS Paint and paste the screenshot. Save the file and then attach (upload) the file here.');
     $screenshotField->setFolderName($folder->Name);
     $form = new Form($this, 'Form', new FieldList(new TextField('Name'), new TextField('Email'), new TextField('URL', 'What is the URL of the page the error occured (this is the address shown in the address bar (e.g. http://www.mysite.com/mypage/with/errors/)', $url), $whatDidYouTryDoField, $whatWentWrongField, $screenshotField), new FieldList(new FormAction('senderror', 'Submit Error')), new RequiredFields(array("Email", "Name")));
     return $form;
 }
 function createFiles()
 {
     $files = $this->owner->Product()->Files();
     if ($files && $files->exists()) {
         foreach ($files as $file) {
             $parentFolder = Folder::find_or_make(self::$productFolder);
             $origin = $file->getFullPath();
             $destination = $parentFolder->getFullPath() . $file->Name . '.dwn';
             if (copy($origin, $destination)) {
                 $downloadable = new Downloadable_File();
                 $downloadable->ParentID = $parentFolder ? $parentFolder->ID : 0;
                 $downloadable->Name = $file->Name . '.dwn';
                 $downloadable->Ext = pathinfo($file->Name, PATHINFO_EXTENSION);
                 $downloadable->Title = $file->Title;
                 $downloadable->FileName = $parentFolder->getRelativePath() . $file->Name . '.dwn';
                 $downloadable->ItemID = $this->owner->ID;
                 $downloadable->DownloadLimit = self::$downloadLimit * $this->owner->Quantity;
                 $downloadable->write();
             }
         }
     }
 }
 /**
  * Fetch and update the media thumbnail
  */
 public function updateOEmbedThumbnail()
 {
     $oembed = $this->Media();
     if ($oembed && $oembed->thumbnail_url) {
         $fileName = preg_replace('/[^A-z0-9\\._-]/', '', $oembed->thumbnail_url);
         if ($existing = File::find($fileName)) {
             $this->MediaThumbID = $existing->ID;
         } else {
             $contents = @file_get_contents($oembed->thumbnail_url);
             if ($contents) {
                 $folder = Folder::find_or_make('downloaded');
                 file_put_contents($folder->getFullPath() . $fileName, $contents);
                 $file = Image::create();
                 $file->setFilename($folder->getFilename() . $fileName);
                 $file->ParentID = $folder->ID;
                 $this->MediaThumbID = $file->write();
             }
         }
     } else {
         $this->MediaThumbID = 0;
     }
 }
    function getCMSFields()
    {
        $folder = Folder::find_or_make(self::get_folder_name_for_images());
        $fields = new FieldList(new HeaderField("FieldExplanations", "Enter optional fields below..."), new TextField("WidgetTitle", "Title"), new TextField("SubTitle", "Sub title"), new TextField("Quote", "Quote"), new TextField("PublishedIn", "Published in"), new TextField("ExtraPublishingInformation", "Extra publishing information, e.g date"), new TextField("PersonQuoted", "Person quoted"));
        $hasPhoto = false;
        if ($this->ID) {
            $images = Image::get()->filter('ParentID', $folder->ID);
            if ($images->exists()) {
                $list = $images->map();
                $fields->push(new DropdownField("PhotoID", "Photo", $list, null, null, " --- select image --- "));
                $hasPhoto = true;
            }
        }
        $fields->push(new HeaderField("PhotoExplanation", '
			<p>HOW TO ADD PHOTO?</p>
			<ul>
				<li>save this page</li>
				<li>make sure you <a href="/admin/assets/show/' . $folder->ID . '">have uploaded</a> the right photo in the following folder: <i>' . self::get_folder_name_for_images() . '</i></li>
				<li>come back here and select the photo.</li>
			</ul>', $headingLevel = 5, $allowHTML = true));
        return $fields;
    }
 protected function importAttachments($item, $page)
 {
     $source = $item->getSource();
     $params = $this->importer->getParams();
     $relation = $params['FileRelation'];
     $folderPath = $params['AssetsPath'];
     $baseURL = $params['BaseUrl'];
     // Check that we should import the files and import them into the specified relation.
     if (!$relation || $page->getRelationClass($relation) != 'File') {
         return;
     }
     if ($folderPath) {
         $folder = Folder::find_or_make($folderPath);
     } else {
         $folder = Folder::get_one('Folder', "'ParentID' = 0");
     }
     $relationList = $page->{$relation}();
     foreach ($item->Files as $file) {
         $fileURL = $file['filepath'];
         // Append the site's URL if it's a relative URL.
         if (strpos($fileURL, '://') === false) {
             $fileURL = Controller::join_links($baseURL, $fileURL);
         }
         $fileName = basename($fileURL);
         $path = Controller::join_links(ASSETS_PATH, $folderPath, $fileName);
         if (file_exists($path)) {
             $SQLFilename = Controller::join_links(ASSETS_DIR, $folderPath, $fileName);
             $file = File::get_one('File', "Filename = '{$SQLFilename}'");
         } else {
             if (!($contents = file_get_contents(str_replace(' ', '%20', $fileURL)))) {
                 continue;
             }
             file_put_contents($path, $contents);
             $fileID = $folder->constructChild($fileName);
             $file = File::get_by_id('File', $fileID);
         }
         $relationList->add($file);
     }
 }
 function checkFolder()
 {
     if (!$this->exists()) {
         return;
     }
     if (!$this->URLSegment) {
         return;
     }
     $baseFolder = '';
     if (class_exists('Subsite') && self::config()->use_subsite_integration) {
         if ($this->SubsiteID) {
             $subsite = $this->Subsite();
             if ($subsite->hasField('BaseFolder')) {
                 $baseFolder = $subsite->BaseFolder;
             } else {
                 $filter = new FileNameFilter();
                 $baseFolder = $filter->filter($subsite->getTitle());
                 $baseFolder = str_replace(' ', '', ucwords(str_replace('-', ' ', $baseFolder)));
             }
             $baseFolder .= '/';
         }
     }
     $folderPath = $baseFolder . "galleries/{$this->URLSegment}";
     $folder = Folder::find_or_make($folderPath);
     if ($this->RootFolderID && $folder->ID != $this->RootFolderID) {
         if ($this->RootFolder()->exists()) {
             // We need to rename current folder
             $this->RootFolder()->setFilename($folder->Filename);
             $this->RootFolder()->write();
             $folder->deleteDatabaseOnly();
             //Otherwise we keep a stupid clone that will be used as the parent
         } else {
             $this->RootFolderID = $folder->ID;
         }
     } else {
         $this->RootFolderID = $folder->ID;
     }
 }