/** * Completes the job by zipping up the generated export and creating an * export record for it. */ protected function complete() { $siteTitle = SiteConfig::current_site_config()->Title; $filename = preg_replace('/[^a-zA-Z0-9-.+]/', '-', sprintf('%s-%s.zip', $siteTitle, date('c'))); $dir = Folder::findOrMake(SiteExportExtension::EXPORTS_DIR); $dirname = ASSETS_PATH . '/' . SiteExportExtension::EXPORTS_DIR; $pathname = "{$dirname}/{$filename}"; SiteExportUtils::zip_directory($this->tempDir, "{$dirname}/{$filename}"); Filesystem::removeFolder($this->tempDir); $file = new File(); $file->ParentID = $dir->ID; $file->Title = $siteTitle . ' ' . date('c'); $file->Filename = $dir->Filename . $filename; $file->write(); $export = new SiteExport(); $export->ParentClass = $this->rootClass; $export->ParentID = $this->rootId; $export->Theme = $this->theme; $export->BaseUrlType = ucfirst($this->baseUrlType); $export->BaseUrl = $this->baseUrl; $export->ArchiveID = $file->ID; $export->write(); if ($this->email) { $email = new Email(); $email->setTo($this->email); $email->setTemplate('SiteExportCompleteEmail'); $email->setSubject(sprintf('Site Export For "%s" Complete', $siteTitle)); $email->populateTemplate(array('SiteTitle' => $siteTitle, 'Link' => $file->getAbsoluteURL())); $email->send(); } }
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::findOrMake('/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->assertType('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->assertType('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); }
private function requireDefaultAlbum() { $class = $this->albumClass; $album = new $class(); $album->AlbumName = "Default Album"; $album->ImageGalleryPageID = $this->ID; $album->ParentID = $this->RootFolderID; $folder = Folder::findOrMake('image-gallery/' . $this->RootFolder()->Name . '/' . $album->AlbumName); $folder->write(); $album->FolderID = $folder->ID; $album->write(); }
public function doExport($data, $form) { $data = $form->getData(); $links = array(); $siteTitle = SiteConfig::current_site_config()->Title; // If the queued jobs module is installed, then queue up an export // job rather than performing the export. if (class_exists('QueuedJobService')) { $job = new SiteExportJob($form->getRecord()); $job->theme = $data['ExportSiteTheme']; $job->baseUrl = $data['ExportSiteBaseUrl']; $job->baseUrlType = $data['ExportSiteBaseUrlType']; $job->email = $data['ExportSiteCompleteEmail']; singleton('QueuedJobService')->queueJob($job); return new SS_HTTPResponse($form->dataFieldByName('SiteExports')->FieldHolder(), 200, 'The site export job has been queued.'); } // First generate a temp directory to store the export content in. $temp = TEMP_FOLDER; $temp .= sprintf('/siteexport_%s', date('Y-m-d-His')); mkdir($temp); $exporter = new SiteExporter(); $exporter->root = $form->getRecord(); $exporter->theme = $data['ExportSiteTheme']; $exporter->baseUrl = $data['ExportSiteBaseUrl']; $exporter->makeRelative = $data['ExportSiteBaseUrlType'] == 'rewrite'; $exporter->exportTo($temp); // Then place the exported content into an archive, stored in the assets // root, and create a site export for it. $filename = preg_replace('/[^a-zA-Z0-9-.+]/', '-', sprintf('%s-%s.zip', $siteTitle, date('c'))); $dir = Folder::findOrMake(self::EXPORTS_DIR); $dirname = ASSETS_PATH . '/' . self::EXPORTS_DIR; $pathname = "{$dirname}/{$filename}"; SiteExportUtils::zip_directory($temp, "{$dirname}/{$filename}"); Filesystem::removeFolder($temp); $file = new File(); $file->ParentID = $dir->ID; $file->Title = $siteTitle . ' ' . date('c'); $file->Filename = $dir->Filename . $filename; $file->write(); $export = new SiteExport(); $export->ParentClass = $form->getRecord()->class; $export->ParentID = $form->getRecord()->ID; $export->Theme = SSViewer::current_theme(); $export->BaseUrlType = ucfirst($data['ExportSiteBaseUrlType']); $export->BaseUrl = $data['ExportSiteBaseUrl']; $export->ArchiveID = $file->ID; $export->write(); return new SS_HTTPResponse($form->dataFieldByName('SiteExports')->FieldHolder(), 200, 'The site export has been generated.'); }
function onBeforeWrite() { parent::onBeforeWrite(); if (isset($_POST['AlbumName'])) { $clean_name = SiteTree::generateURLSegment($_POST['AlbumName']); if ($this->FolderID) { $this->Folder()->setName($clean_name); $this->Folder()->Title = $clean_name; $this->Folder()->write(); } else { $folder = Folder::findOrMake('image-gallery/' . $this->ImageGalleryPage()->RootFolder()->Name . '/' . $clean_name); $this->FolderID = $folder->ID; } } }
/** * Processes the uploaded files in the request. Most of the legwork is handled in {@link KickAssetUtil} * * @return SS_HTTPResponse */ public function upload(SS_HTTPRequest $r) { // We don't want anyone uploading to the root assets folder.. if (!$this->defaultFolder) { $this->defaultFolder = Folder::findOrMake("Uploads"); } $response = KickAssetUtil::handle_upload($r, $this->defaultFolder); if (empty($response)) { return new SS_HTTPResponse("File did not upload", 500); } if (is_array($response)) { return new SS_HTTPResponse(implode(',', $response), 200); } return new SS_HTTPResponse("Error: " . $response, 500); }
public function Field($properties = array()) { Requirements::javascript(THIRDPARTY_DIR . '/jquery-livequery/jquery.livequery.js'); Requirements::javascript('pixlr/thirdparty/supa/Supa.js'); Requirements::javascript('pixlr/javascript/supa-field.js'); Requirements::css('pixlr/css/pixlr.css'); $id = $this->id(); $div = '<div id="' . $id . 'Container" class="' . $this->extraClass() . ' supaField">'; $div .= '<div class="supaButtons">'; $div .= $this->createTag('input', array('id' => $id . 'Paste', 'value' => _t('Pixlr.PASTE', 'Paste'), 'type' => 'button', 'class' => 'supaPasteButton')); $div .= $this->createTag('input', array('id' => $id . 'Upload', 'value' => _t('Pixlr.UPLOAD', 'Upload'), 'type' => 'button', 'class' => 'supaUploadButton', 'style' => 'display: none')); $div .= $this->createTag('input', array('type' => 'checkbox', 'value' => '1', 'name' => 'AndEdit', 'id' => $id . 'AndEdit')); $div .= '<label for="' . $id . 'AndEdit' . '">and Edit</label>'; $div .= $this->createTag('input', array('class' => 'supaFileID', 'type' => 'hidden', 'value' => '')); $div .= '</div><div class="supaOptions" style="display: none">'; if ($this->options['show_selector']) { $treeField = new TreeDropdownField('SupaLocation', _t('Pixlr.UPLOAD_LOCATION', 'Save to'), 'File'); $div .= $treeField->Field(); } else { // create a default target for uploading to $target = Folder::findOrMake($this->options['target']); $div .= $this->createTag('input', array('type' => 'hidden', 'name' => 'SupaLocation', 'value' => $target->ID)); } $div .= $this->createTag('input', array('id' => $id . 'Filename', 'value' => $this->options['name'], 'name' => 'SupaImageName')); $params = array('parent' => '{input[name=FolderID]}', 'force' => true, 'imgstate' => 'existing', 'title' => '{#' . $id . 'Filename}.png'); $pixlr = new PixlrEditorField('EditSelectedImage' . $id, _t('Pixlr.EDIT_SELECTED', 'Edit Selected'), '{#' . $id . 'Container .supaFileID}', $params); $div .= $pixlr->Field(); $div .= '</div><div class="supaFileUrl"></div><div class="supaAppletWrapper" id="' . $id . 'AppletWrapper">'; $url = Director::absoluteBaseURL() . 'pixlr/thirdparty/supa/Supa.jar'; $div .= '<applet id="' . $id . 'Applet" class="supaApplet" archive="' . $url . '" code="de.christophlinder.supa.SupaApplet" width="' . $this->options['width'] . '" height="' . $this->options['height'] . '"> <!--param name="clickforpaste" value="true"--> <param name="imagecodec" value="png"> <param name="encoding" value="base64"> <param name="previewscaler" value="fit to canvas"> <!--param name="trace" value="true"--> Applets disabled :( </applet> '; $div .= '</div></div>'; return $div; }
function setUp() { parent::setUp(); // clear File to start. $files = DataObject::get("File"); if ($files) { foreach ($files as $f) { $f->deleteDatabaseOnly(); } } $folder = Folder::findOrMake('/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"); }
/** * Determine the "current" upload folder, e.g. If the {@see $uploadFolder} is not defined, * then get the folder of the last file uploaded * * @return Folder */ public function CurrentUploadFolder() { if ($this->allowFolderSelection && $this->getUploadFolder() == "Uploads") { if ($result = $this->Files()) { if ($result instanceof File) { return $result->Parent(); } elseif ($result instanceof DataObjectSet) { return $result->First()->Parent(); } } } return Folder::findOrMake($this->getUploadFolder()); }
/** * 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. */ function load($tmpFile, $folderPath = false) { $this->clearErrors(); if(!$folderPath) $folderPath = self::$uploads_folder; if(!$this->file) $this->file = new File(); if(!is_array($tmpFile)) { user_error("File::loadUploaded() Not passed an array. Most likely, the form hasn't got the right enctype", E_USER_ERROR); } if(!$tmpFile['size']) { $this->errors[] = _t('File.NOFILESIZE', 'Filesize is zero bytes.'); return false; } $valid = $this->validate($tmpFile); if(!$valid) return false; // @TODO This puts a HUGE limitation on files especially when lots // have been uploaded. $base = Director::baseFolder(); $parentFolder = Folder::findOrMake($folderPath); // Create a folder for uploading. if(!file_exists(ASSETS_PATH)){ mkdir(ASSETS_PATH, Filesystem::$folder_create_mask); } if(!file_exists(ASSETS_PATH . "/" . $folderPath)){ mkdir(ASSETS_PATH . "/" . $folderPath, Filesystem::$folder_create_mask); } // Generate default filename $fileName = str_replace(' ', '-',$tmpFile['name']); $fileName = ereg_replace('[^A-Za-z0-9+.-]+','',$fileName); $fileName = ereg_replace('-+', '-',$fileName); $fileName = basename($fileName); $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 = ereg_replace('[0-9]*(\.tar\.[^.]+$)',$i . '\\1', $relativeFilePath); } else { $relativeFilePath = ereg_replace('[0-9]*(\.[^.]+$)',$i . '\\1', $relativeFilePath); } if($oldFilePath == $relativeFilePath && $i > 2) user_error("Couldn't fix $relativeFilePath with $i tries", E_USER_ERROR); } if(file_exists($tmpFile['tmp_name']) && copy($tmpFile['tmp_name'], "$base/$relativeFilePath")) { $this->file->ParentID = $parentFolder->ID; // This is to prevent it from trying to rename the file $this->file->Name = basename($relativeFilePath); $this->file->write(); return true; } else { $this->errors[] = _t('File.NOFILESIZE', 'Filesize is zero bytes.'); return false; } }
public static function create_empty_template($name) { $template = new DynamicTemplate(); $base = $name; $holder = Folder::findOrMake(self::$dynamic_template_folder); $template->ParentID = $holder->ID; $suffix = 1; while (DataObject::get('DynamicTemplate', "\"Name\" LIKE '%" . $name . "%'")) { $name = "{$base}{$suffix}"; $suffix++; } $template->Name = $name; $template->Title = $name; $template->write(); if (!file_exists($template->getFullPath())) { mkdir($template->getFullPath(), Filesystem::$folder_create_mask); } return $template; }
/** * Transfer all the content from the Image table into the File table. * @deprecated This function is only used to migrate content from old databases. */ function transferlegacycontent() { if (!Permission::check('ADMIN')) { Security::permissionFailure($this); } $images = DB::query("SELECT * FROM _obsolete_Image"); echo "<h3>Transferring images</h3>"; foreach ($images as $image) { if (($className = $image['ClassName']) && $image['Filename']) { echo "<li>Importing {$image['Filename']}"; $folderName = str_replace('assets/', '', dirname($image['Filename'])); $name = basename($image['Filename']); $folderObj = Folder::findOrMake($folderName); $fileObj = new $className(); $fileObj->Name = $name; $fileObj->ParentID = $folderObj->ID; $fileObj->write(); $fileObj->destroy(); echo " as {$fileObj->ID}"; list($baseClass, $fieldName) = explode('_', $className, 2); //if($baseClass == 'News') $baseClass = 'NewsHolder'; //if($baseClass == 'FAQ') $baseClass = 'FaqHolder'; $parentObj = DataObject::get_by_id($baseClass, $image['ParentID']); if ($parentObj && $fieldName) { $fieldName .= "ID"; echo "<li>{$parentObj->class}.{$parentObj->ID}.{$fieldName} = {$fileObj->ID}"; $parentObj->{$fieldName} = $fileObj->ID; $parentObj->write(); $parentObj->destroy(); } // echo " and linking to $baseClass.$image[ParentID]->$fieldName"; } } }
function moverootfilesto() { if ($folder = $this->urlParams[ID]) { $newParent = Folder::findOrMake($folder); $files = DataObject::get("File", "ClassName != 'Folder' AND ParentID = 0"); foreach ($files as $file) { echo "<li>", $file->RelativePath; $file->ParentID = $newParent->ID; echo " -> ", $file->RelativePath; } } }
/** * Gets the report folder needed for storing the report files * * @param String $format */ protected function getReportFolder() { $id = $this->ReportID; if (!$id) { $id = 'preview'; } $folderName = 'advanced-reports/' . $this->ReportID . '/' . $this->ID; return Folder::findOrMake($folderName); }
private function createThumbnail() { $img_title = "flv_thumb_" . $this->ID; if ($existing = DataObject::get("Image", "Title = '{$img_title}'")) { foreach ($existing as $file) { $file->delete(); } } $folder = Folder::findOrMake(self::$thumbnail_folder); $img_filename = self::clean_file(self::remove_file_extension($this->Title)) . ".jpg"; $abs_thumb = Director::baseFolder() . "/" . $folder->Filename . $img_filename; $args = sprintf("-y -i %s -an -s %s -ss %d -an -r 1 -vframes 1 -y -vcodec mjpeg -f mjpeg %s", $this->absoluteFLVPath(), self::$default_thumbnail_width . "x" . self::$default_thumbnail_height, self::$thumbnail_seconds, $abs_thumb); self::ffmpeg($args); $img = new Image(); $img->setField('ParentID', $folder->ID); $img->Filename = $folder->Filename . $img_filename; $img->Title = $img_title; $img->write(); }
function requireDefaultRecords() { parent::requireDefaultRecords(); $ebook = DataObject::get_one('Ebook', "\"Title\" = 'Silhouetted against the moon'"); if (!($ebook && $ebook->exists())) { $ebook = new Ebook(); $ebook->Title = 'Silhouetted against the moon'; $ebook->Summary = <<<HTML \t\t\t<p>A frightful product that will keep you on the edge of your seat!</p> \t\t\t<p>Cover <a href="http://www.sxc.hu/photo/991793">image</a> courtesy of <a href="http://www.sxc.hu/profile/nazreth" target="_blank">nazreth</a> on <a href="http://www.sxc.hu/" target="_blank">sxc.hu</a></p> HTML; $coverPhoto = DataObject::get_one('CoverPhoto', "\"Name\" = 'silhouetted-against-the-moon.png'"); if (!($coverPhoto && $coverPhoto->exists())) { $uploadfolder = Folder::findOrMake("Uploads"); $command = "cp ../payment-test/templates/Images/silhouetted-against-the-moon.png ../" . $uploadfolder->Filename; `{$command}`; $coverPhoto = new CoverPhoto(array('ClassName' => 'CoverPhoto')); $coverPhoto->Name = 'silhouetted-against-the-moon.png'; $coverPhoto->Title = 'silhouetted-against-the-moon'; $coverPhoto->Filename = 'assets/Uploads/silhouetted-against-the-moon.png'; $coverPhoto->ParentID = $uploadfolder->ID; $coverPhoto->OwnerID = Member::currentUserID(); $coverPhoto->write(); } $file = DataObject::get_one('EbookFile', "\"Name\" = 'silhouetted-against-th-moon.pdf'"); if (!($file && $file->exists())) { $uploadfolder = Folder::findOrMake("Uploads"); $command = "cp ../payment-test/templates/Images/silhouetted-against-th-moon.pdf ../" . $uploadfolder->Filename; `{$command}`; $file = new EbookFile(array('ClassName' => 'EbookFile')); $file->Name = 'silhouetted-against-th-moon.pdf'; $file->Title = 'silhouetted-against-th-moon'; $file->Filename = 'assets/Uploads/silhouetted-against-th-moon.pdf'; $file->ParentID = $uploadfolder->ID; $file->OwnerID = Member::currentUserID(); $file->write(); } $ebook->CoverPhotoID = $coverPhoto->ID; $ebook->FileID = $file->ID; $ebook->Amount->Amount = '5.99'; $ebook->Amount->Currency = 'USD'; $ebook->write(); $author = DataObject::get_one('Author', "\"Name\" = 'Michael Lorenzo'"); if (!($author && $author->exists())) { $author = new Author(array('ClassName' => 'Author')); $author->Name = 'Michael Lorenzo'; $author->Introduction = <<<HTML <p>Hi everyone! =) Thank you for viewing my gallery. My images are for free and I would love to see your projects or send me a link to your website so that I can see where you used nazreth's photos. It's a pleasure to see your artworks and it would inspire me to come up with more useful images. =)<br /><br />Thanks again and enjoy viewing my gallery! =)</p> HTML; $author->write(); } $ebook->Authors()->add($author); DB::alteration_message('payable Ebook example \'Silhouetted against the moon\'', 'created'); } }
/** * Save an file passed from a form post into this object. * File names are filtered through {@link FileNameFilter}, see class documentation * on how to influence this behaviour. * * @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. */ function load($tmpFile, $folderPath = false) { $this->clearErrors(); if (!$folderPath) { $folderPath = self::$uploads_folder; } if (!$this->file) { $fileClass = File::get_class_for_file_extension(pathinfo($tmpFile['name'], PATHINFO_EXTENSION)); $this->file = new $fileClass(); } if (!is_array($tmpFile)) { user_error("Upload::load() Not passed an array. Most likely, the form hasn't got the right enctype", E_USER_ERROR); } if (!$tmpFile['size']) { $this->errors[] = _t('File.NOFILESIZE', 'Filesize is zero bytes.'); return false; } $valid = $this->validate($tmpFile); if (!$valid) { return false; } // @TODO This puts a HUGE limitation on files especially when lots // have been uploaded. $base = Director::baseFolder(); $parentFolder = Folder::findOrMake($folderPath); // Create a folder for uploading. if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH, Filesystem::$folder_create_mask); } if (!file_exists(ASSETS_PATH . "/" . $folderPath)) { mkdir(ASSETS_PATH . "/" . $folderPath, Filesystem::$folder_create_mask); } // Generate default filename $nameFilter = Object::create('FileNameFilter'); $file = $nameFilter->filter($tmpFile['name']); $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 = ereg_replace('[0-9]*(\\.tar\\.[^.]+$)', $i . '\\1', $relativeFilePath); } else { if (strpos($relativeFilePath, '.') !== false) { $relativeFilePath = ereg_replace('[0-9]*(\\.[^.]+$)', $i . '\\1', $relativeFilePath); } else { if (strpos($relativeFilePath, '_') !== false) { $relativeFilePath = ereg_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['tmp_name']) && copy($tmpFile['tmp_name'], "{$base}/{$relativeFilePath}")) { $this->file->ParentID = $parentFolder->ID; // This is to prevent it from trying to rename the file $this->file->Name = basename($relativeFilePath); $this->file->write(); return true; } else { $this->errors[] = _t('File.NOFILESIZE', 'Filesize is zero bytes.'); return false; } }
static function import($page) { include_once '../googledocspage/libs/simplehtmldom/simple_html_dom.php'; //if import url is set, use that, else fall back on google doc id if (strlen($page->ImportURL) > 1) { $url = $page->ImportURL; } else { $url = GoogleDocsPage::$gdoc_pub_urlbase . $page->GoogleDocID; } //echo $url; $html = file_get_html($url); //$contents = $html->find('div[id="contents"]', 0)->innertext; $contents = $html->find('div[id="contents"]', 0); // remove h1 //var_dump($contents->find('h1')); if (isset($contents)) { foreach ($contents->find('h1') as $e) { $e->outertext = ''; } } else { return "Error retrieving document. <br /> Try visiting this URL: <br /><br /><a href=\"{$url}\">{$url}</a>"; } // save style $style = ""; foreach ($contents->find('style') as $e) { $style = $e->innertext; } $e->outertext = ''; //changing img path $i = 1; foreach ($html->find('img') as $e) { if ($i < 99) { //echo $e->src . "<br />"; //$e->outertext = ''; $e->src = "http://docs.google.com/document/" . $e->src; //var_dump($page->PageID); $folderPath = 'import/' . $page->ID; //var_dump($folderPath); $folder = Folder::findOrMake($folderPath); //$tempFileName = $i . ".png"; $tempFileName = $i; $filepath = "assets/" . $folderPath . "/" . $tempFileName; $src = str_replace("amp;", "", $e->src); $img = file_get_contents($src); //$size = getimagesize($img); //var_dump($img); $file = File::find($filepath); if (!$file) { $file = new File(); $file->Filename = $filepath; } file_put_contents(Director::baseFolder() . "/" . $filepath, $img); //$file->Name = $a["FileName"]; //$file->setName($tempFileName); $file->write(); $file->setName($i); $file->setParentID($folder->ID); //$file->setName($filepath); $file->ClassName = "Image"; $file->write(); $e->src = "/" . $filepath; } $i = $i + 1; } //echo '<style>.c2 { font-weight:bold;}</style>'; //echo $contents->innertext; //echo "importing"; $import = new GoogleDocsPage_Import(); //$import->Imported = date("Y-m-d H:i:s"); $import->Content = $contents->innertext; $import->Css = $style; $import->CssParsed = GoogleDocsPage_Import::parsecss($style); $import->PageID = $page->ID; $import->write(); //this is not neccessary, as it is done already be referencing the PageID //$pageimports = $page->Imports(); //$pageimports->add($import); //writing content to the page //making sure the "real" page object is being used $page = SiteTree::get_by_id("Page", $page->ID); $page->Content = $import->Content; $page->writeToStage('Stage'); $page->Publish('Stage', 'Live'); $page->Status = "Published"; $page->flushCache(); return "import successful"; //return $import; }
/** * Update the folder that holds the photos to have the same file name as this page's title. * */ function updateAssociatedFolder($original) { $folder = $this->owner->AssociatedFolder(); if ($this->owner->AssociatedFolderID && $folder) { $folder->Title = $this->owner->Title; $folder->Name = $this->owner->URLSegment; if ($this->owner->parentID != $original->ParentID) { // The parent has changed move the folder if possible $parent = $this->owner->Parent(); if ($parent && $parent->hasExtension($this->class)) { // Move the folder to the new parent $folder->ParentId = $parent->AssociatedFolderID; } else { // Move the folder below the default root as its owner's parent is not folder associated $root = Folder::findOrMake(self::$defaultRootFolderName); $folder->ParentId = $root->ID; } } $folder->write(); } else { trigger_error("Associated folder does not exist", E_USER_ERROR); } }
/** * Generates a link to the file browser. * @see KickAssetAdmin * * @return string */ public function BrowseLink() { $folder = $this->defaultFolder ? $this->defaultFolder instanceof Folder ? $this->defaultFolder : Folder::findOrMake($this->defaultFolder) : singleton('Folder'); return Director::absoluteBaseURL() . "/admin/files/select/{$folder->ID}"; }
/** * Upload * @note handles a file upload to $uploadDirectory * @note saves the file and links it to the dataobject, returning the saved file ID * @todo handle has_one and has_many */ public final function Upload() { try { if (empty($_GET['record'])) { throw new Exception("The gallery has not been configured correctly."); } if (empty($_GET['record']['d'])) { throw new Exception("The related dataobject name was not provided."); } if (empty($_GET['record']['p']) || !is_array($_GET['record']['p'])) { throw new Exception("The related dataobject primary key fields were not provided. Upload failed. Hint: use AssociateWith() durng field setup"); } /** //set the related dataobject $conditional = array(); foreach($_GET['record']['p'] as $column=>$value) { $conditional[] = "\"" . Convert::raw2sql($_GET['record']['d']) . "\".\"" . Convert::raw2sql($column) . "\" = '" . Convert::raw2sql($value) . "'"; } //upload association target $dataobject = FALSE; try { if($this->IsSiteTree($_GET['record']['d'])) { $target = "SiteTree"; } else { $target = $_GET['record']['d'] } $dataobject = DataObject::get_one($target, implode(" AND ", $conditional)); } catch (Exception $e) { throw new Exception("Query failed with error: " . $e->getMessage()); } if(!$dataobject || empty($dataobject)) { throw new Exception("The related dataobject is not valid. This can happen if the gallery type has changed. Upload failed."); } */ //current member if they can upload $member = $this->CanUpload(); //set this->file to the correct handler $this->LoadUploadHandler(); //if not set, create a target location if ($this->target_location == "") { $this->target_location = "Uploads"; } //final location of file $targetDirectory = "/" . trim($this->target_location, "/ "); $uploadDirectory = "/" . trim(ASSETS_PATH, "/ ") . $targetDirectory; //print $uploadDirectory;exit; if (!is_writable($uploadDirectory)) { throw new Exception("Server error. Upload directory '{$uploadDirectory}' isn't writable."); } if (!$this->file) { throw new Exception('No file handler was defined for this upload.'); } $this->CheckAllowedType(); $this->CheckAllowedSize(); //now save the file $target = $this->SetUploadFileName($uploadDirectory, $this->replace_file); //saves the file to the target directory $this->file->save($target); //here ? then the file save to disk has worked //make a folder record (optionally makes it on the file system as well, although this is done in this->file->save() $folder = Folder::findOrMake($targetDirectory); //without ASSETS_PATH ! if (empty($folder->ID)) { $this->UnlinkFile($target); throw new Exception('No folder could be assigned to this file'); } try { $filename = $this->GetFileName(); $relation = $this->DataTypeRelation(); switch ($relation) { case "single": $file = new UploadAnythingFile(); //TODO - this should match the file type provided $file->Name = $filename; $file->Title = $filename; $file->Filename = $filename; $file->ShowInSearch = 0; $file->ParentID = $folder->ID; $file->OwnerID = $member->ID; //write the file $id = $file->write(); if ($id) { //the relationship: the related dataobject has one of this file $this->controller->{$this->name . 'ID'} = $id; $this->controller->write(); } else { throw new Exception("The file '{$filename}' could not be saved (1)."); } break; case "gallery": //add this file to the relation component //the type of file that is the relation $info = $this->GetComponentInfo(); if (!$info || !isset($info['childClass'])) { throw new Exception("Error: {invalid component info detected. This generally means the gallery association with the page is not correct."); } $file_class = $info['childClass']; $file = new $file_class(); if (!isset($info['joinField'])) { throw new Exception("Error: {$file_class} does not have a has_one relation linking it to {$item['ownerClass']}."); } else { if ($file instanceof File) { $file->Name = $filename; $file->Title = $filename; $file->Filename = $filename; $file->ShowInSearch = 0; $file->ParentID = $folder->ID; $file->OwnerID = $member->ID; $file->{$info['joinField']} = $this->controller->{$this->name}()->ID; //link it to the owner gallery //write the file $id = $file->write(); if (!$id) { throw new Exception("The file '{$filename}' could not be saved (2)."); } } else { throw new Exception("Error: {$file_class} is not child of 'File'. {$file_class} should extend 'File' or a child of 'File'"); } } break; default: throw new Exception("Unhandled relation: {$relation}. File could not be saved."); break; } } catch (Exception $e) { $this->UnlinkFile($target); throw new Exception("The file could not be uploaded. File save failed with error: " . $e->getMessage()); } //here ? no exceptions were thrown $this->returnValue = array('success' => true); } catch (Exception $e) { $this->returnValue = array('error' => $e->getMessage()); } $this->ShowReturnValue(); }
public function saveImportForm($data, $form) { if (isset($data['imported_files']) && is_array($data['imported_files'])) { $_POST['uploaded_files'] = array(); // If the user has set a custom upload folder, cut a new copy of the file when importing $custom_folder = $this->getUploadFolder() != "Uploads" ? Folder::findOrMake($this->getCleanUploadFolder()) : false; foreach ($data['imported_files'] as $file_id) { $file = DataObject::get_by_id("File", $file_id); if ($custom_folder && $file->ParentID != $custom_folder->ID) { $new_path = Director::baseFolder() . '/' . $custom_folder->Filename . $file->Name; copy($file->getFullPath(), $new_path); $new_file = new File(); $new_file->setFilename($custom_folder->Filename . $file->Name); $new_file->setName($file->Name); $new_file->setParentID($custom_folder->ID); $new_file->write(); $file = $new_file; $file_id = $new_file->ID; } // If something other than File has been specified as the linked file class, // we need to "upgrade" the imported file to the correct class. if ($this->fileClassName != "File" && $file->ClassName != $this->fileClassName) { $file = $file->newClassInstance($this->fileClassName); $file->write(); } $owner_id = $data['parentIDName']; if ($this->hasDataObject) { $do_class = $data['dataObjectClassName']; $idxfield = $data['fileFieldName'] . "ID"; $obj = new $do_class(); $obj->{$idxfield} = $file_id; $obj->{$owner_id} = $data['controllerID']; $obj->write(); $_POST['uploaded_files'][] = $obj->ID; } else { if ($file = DataObject::get_by_id($this->fileClassName, $file_id)) { $id_field = $this->controllerFieldName . "ID"; if ($file->hasField($owner_id)) { $file->{$owner_id} = $this->controllerID; $file->write(); } } } } $form = $this->EditUploadedForm(); return $this->customise(array('String' => is_string($form), 'DetailForm' => $form))->renderWith($this->templatePopup); } }
/** * Save the cleanup and redirect */ function uploadimages($data, $form) { //Check there is a member! IF not return false $member = Member::currentUser(); if (!$member) { $form->sessionMessage(_t("Create.CLEANUPCREATTIONERROR", "You Need to be logged in to Edit An Event"), 'bad'); Director::redirectBack(); } else { //$fri = (!empty($_REQUEST['Friday'])) ? $_REQUEST['Friday'] : null; //CLEANUP EVENT WE ARE ADDING IMAGES FO $cleanupID = !empty($_REQUEST['CleanUpID']) ? $_REQUEST['CleanUpID'] : null; $cleanupgroup = DataObject::get_one('CleanUpGroup', "CleanUpGroup.ID = '{$cleanupID}'"); if (!$cleanupgroup) { $form->sessionMessage(_t("Create.CLEANUPIMAGEUPLOADERROR", "You Need to have a Clean Up Event to add images "), 'bad'); Director::redirectBack(); } else { $curralbum = DataObject::get_one('ImageGalleryAlbum', "ImageGalleryAlbum.CleanUpGroupID = '{$cleanupgroup->ID}'"); //add image to flickr if (isset($data['ImageID'])) { //Debug::show($data); //Debug::show("Upload attempt: ImageID: " . $data['ImageID'] . " Title: " . "Photo from Love Your Coast event: " . $cleanupgroup->Title . " . <a href=\"http://www.loveyourcoast.org".$cleanupgroup->Link()."\">Visit this event on LoveYourCoast.org</a> Caption: " . $data['Caption'] . " MT: " . $cleanupgroup->machineTag()); $flickr = new FlickrService(); $flickr->uploadPhoto($data['ImageID'], "Love Your Coast Event - " . $cleanupgroup->Title, "- " . $data['Caption'] . " - Visit this event -> http://www.loveyourcoast.org" . $cleanupgroup->Link() . "", $cleanupgroup->machineTag()); } //1) Album Check Existing if ($curralbum) { //2) Add Images $imageitem = new ImageGalleryItem(); $imageitem->CleanUpGroupID = $cleanupgroup->ID; $form->saveInto($imageitem); $imageitem->ImageGalleryPageID = 13; $imageitem->AlbumID = $curralbum->ID; $imageitem->write(); //Should redirect to gallery $folderid = $curralbum->FolderID; $folder = DataObject::get_one('Folder', "ID = '{$folderid}'"); $gallerylink = '/lyc2010_live/gallery10/album/' . $folder->Name; Director::redirect($cleanupgroup->Link()); } else { //1a) Create Album & Folder $album = new ImageGalleryAlbum(); $album->AlbumName = $cleanupgroup->Title; $album->CleanUpGroupID = $cleanupgroup->ID; $album->ImageGalleryPageID = 13; $folder = Folder::findOrMake('image-gallery/Gallery10/' . $cleanupgroup->Title); $album->FolderID = $folder->ID; $album->write(); //2) Add Images $imageitem = new ImageGalleryItem(); $imageitem->CleanUpGroupID = $cleanupgroup->ID; $form->saveInto($imageitem); $imageitem->ImageGalleryPageID = 13; $imageitem->AlbumID = $album->ID; $imageitem->write(); //Should redirect to gallery $gallerylink = '/lyc2010_live/gallery10/album/' . $folder->Name; Director::redirect($cleanupgroup->Link()); } } } }
function testDeleteAlsoRemovesContainedFilesInDatabaseAndFilesystem() { $path = '/FolderTest/DeleteAlsoRemovesContainedFilesInDatabaseAndFilesystem'; $folder = Folder::findOrMake($path); $file = $this->objFromFixture('File', 'gif'); $file->ParentID = $folder->ID; $file->write(); $fileID = $file->ID; $fileAbsPath = $file->getFullPath(); $this->assertFileExists($fileAbsPath); $folder->delete(); $this->assertFileNotExists($fileAbsPath, 'Contained files removed from filesystem'); $this->assertFalse(DataObject::get_by_id('File', $fileID), 'Contained files removed from database'); }
function requireDefaultRecords() { parent::requireDefaultRecords(); $bt = defined('DB::USE_ANSI_SQL') ? '"' : '`'; $update = array(); $siteConfig = DataObject::get_one('SiteConfig'); $folder = Folder::findOrMake(self::get_folder_name()); if ($siteConfig && $folder) { $fullArray = self::get_images_to_replace(); //copying .... if ($fullArray) { foreach ($fullArray as $key => $array) { $className = $array["ClassName"]; $fieldName = $array["FieldName"] . "ID"; if (class_exists($className)) { $dataObject = singleton($className); $dbFieldName = $array["DBFieldName"]; $fileName = basename($array["CopyFromPath"]); $fromLocationLong = Director::baseFolder() . '/' . $array["CopyFromPath"]; $toLocationShort = "assets/" . self::get_folder_name() . "/{$fileName}"; $toLocationLong = Director::baseFolder() . '/' . $toLocationShort; $image = DataObject::get_one('Image', "Filename='{$toLocationShort}' AND ParentID = " . $folder->ID); if (!$image) { if (!file_exists($toLocationLong)) { copy($fromLocationLong, $toLocationLong); } $image = new Image(); $image->ParentID = $folder->ID; $image->FileName = $toLocationShort; $image->setName($fileName); $image->write(); } elseif (!$image && file_exists($toLocationLong)) { debug::show("need to update files"); } if ($image && $image->ID) { if (!$siteConfig->{$dbFieldName}) { $siteConfig->{$dbFieldName} = $image->ID; $update[] = "created placeholder image for {$key}"; } $updateSQL = " UPDATE {$bt}" . $className . "{$bt}"; if (isset($_GET["removeplaceholderimages"])) { $setSQL = " SET {$bt}" . $fieldName . "{$bt} = 0"; $whereSQL = " WHERE {$bt}" . $fieldName . "{$bt} = " . $image->ID; DB::alteration_message("removing " . $className . "." . $fieldName . " placeholder images", 'deleted'); } else { DB::alteration_message("adding " . $className . "." . $fieldName . " placeholder images", 'created'); $setSQL = " SET {$bt}" . $fieldName . "{$bt} = " . $image->ID; if (!isset($_GET["forceplaceholder"])) { $whereSQL = " WHERE {$bt}" . $fieldName . "{$bt} IS NULL OR {$bt}" . $fieldName . "{$bt} = 0"; } else { $whereSQL = ''; } } $sql = $updateSQL . $setSQL . $whereSQL; DB::query($sql); $versioningPresent = false; $array = $dataObject->stat('extensions'); if (is_array($array) && count($array)) { if (in_array("Versioned('Stage', 'Live')", $array)) { $versioningPresent = true; } } if ($dataObject->stat('versioning')) { $versioningPresent = true; } if ($versioningPresent) { $sql = str_replace("{$bt}{$className}{$bt}", "{$bt}{$className}_Live{$bt}", $sql); DB::query($sql); } } else { debug::show("could not create image!" . print_r($array)); } } else { debug::show("bad classname reference " . $className); } } } if (count($update)) { $siteConfig->write(); DB::alteration_message($siteConfig->ClassName . " created/updated: " . implode(" --- ", $update), 'created'); } } elseif (!$folder) { debug::show("COULD NOT CREATE FOLDER: " . self::get_folder_name()); } }