Concrete5 - CMS :: Get all file inside a file manager folder programmatically - concrete5

I have a folder structure likes this:
folder1
subfolder1
file1.pdf
file2.pdf
subfolder2
file3.pdf
file4.pdf
is there any way to retrieve all the pdf file's(programmatically) using the "folder1" id?

There is but make sure you don't go insanely deep with your folder structure, you don't want to go through hundreds of folders, hundreds of levels deep.
Here's the code
<?php
use Concrete\Core\Tree\Node\Type\FileFolder;
use Concrete\Core\File\FolderItemList;
// First grab the folder object
$folder = FileFolder::getNodeByName('Testing Folder');
if (is_object($folder)) {
$files = [];
// if we have a folder we need to grab everything inside and then
// recursively go through the folder's content
// if what we get is a file we list it
// otherwise if it's another folder we go through it as well
$walk = function ($folder) use (&$files, &$walk) {
$list = new FolderItemList();
$list->filterByParentFolder($folder);
$list->sortByNodeName();
$nodes = $list->getResults();
foreach ($nodes as $node) {
if ($node->getTreeNodeTypeHandle() === 'file'){
$files[] = $node->getTreeNodeFileObject();
} elseif ($node->getTreeNodeTypeHandle() === 'file_folder'){
$walk($node);
}
}
};
$walk($folder);
// we are done going through all the folders, we now have our file nodes
foreach ($files as $file) {
echo sprintf('%sfile name is %s and URL is %s%s', '<p>', $file->getTitle(), $file->getURL(), '</p>');
}
}

Related

How to handle file upload in symfony?

im trying to upload diffrent types of files in symfony
$uploadedFile = $request->files->get('image');
Works good for handling with images, However i cannot use it with diffrent files than
$uploadedFile = $request->files->get('file');
dd($uploadedFile);
Whatever i send using this, dd method shows me null.
How can I upload files for example pdfs, docx etc. (diffrent than images)
I use vue on the frontend.
You should use createForm.
https://symfony.com/doc/current/controller/upload_file.html
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** #var UploadedFile $brochureFile */
$brochureFile = $form->get('brochure')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($brochureFile) {
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('brochures_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$product->setBrochureFilename($newFilename);
}

Download multiple images in zip in Wordpress

I am working on my personal wordpress site that distribute images.
In single post page, I registered several images via ACF(Advanced Custom Fields) and I know how to get image path/filename through get_field ACF function.
I just googled then found this page, but how can I apply this technique to wordpress site?
Download multiple images into zip
Now I am stuck...
On single post page, place the url of download_zip.php file, where you will place all your code for creating zip.
On single post page:
Download ZIP
In variable 'model_id', place the post id of the single post.
Now create a download_zip.php file on the root of your wordpress setup, where wp-config.php file exists.
Here is the code of download_zip.php file.
<?php
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id);
$destination = wp_upload_dir();
//var_dump($destination);
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
unlink ($destination_path."/".$DelFilePath);
}
if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
<?php
$explode = end(explode("uploads",$row));
$index_file = array($destination_path,$explode);
$index_file = implode("",$index_file);
$new_index_file = basename($index_file);
$zip->addFile($index_file,$new_index_file);
endforeach;
}
$zip->close();
if(file_exists($zip_destination_path)) {
send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u",filesize($file));
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$basename.'"');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_clean();
flush();
readfile($file); // "Outputs" the file.
unlink($file);
}
?>
Please modify this code according to your requirement such as get_field(), place your image field name inside it, & define your upload directory, so that you can break the url in $explode variable for defining path of image in $index_file variable.
And please also check your destination path stored in $destination_path variable is correct or not.
Hope, this may be helpful to you.

Adding images from an external gallery to a SilverStripe site via a BuildTask

I'm making a Silverstripe build task to get many images from an external gallery, and create/upload them into the /assets/images/gallery folder with the necessary database links to the GalleryPage.
So I load the list of Urls, display the images to the browser, now how do I save an image into the assets folder with the necessary GalleryPage database links?
class ImportGalleryTask extends BuildTask {
public function writeImage($data) {
//$data->Title
//$data->Filename
//$data->Url
//this is the external url that I can output as an image to the browser
//
// folder to save image is 'assets/images/gallery'
//
// ? save into folder and database and associate to PageImageBelongsToID ?
}
}
You can use copy to copy a remote file to your local filesystem. PHP must be configured to support allow_url_fopen though.
So, your resulting function might look like this:
/**
* #param $data
* #return null|Image return written Image object or `null` if failed
*/
public function writeImage($data)
{
// The target folder for the image
$folder = Folder::find_or_make('images/gallery');
// assuming that $data->Filename contains just the file-name without path
$targetPath = $folder->getFullPath() . $data->Filename;
// Check if an image with this name already exists
// ATTENTION: This will overwrite existing images!
// If you don't want this, you need to implement this differently
if(
file_exists($targetPath) &&
$image = Image::get()->where(array(
'"Name" = ?' => $data->Filename,
'"ParentID" = ?' => $folder->ID
))->first()
){
// just copy the new file over…
copy($data->Url, $targetPath);
// … and delete all cached images
$image->deleteFormattedImages();
// and we're done
return $image;
}
// Try to copy the file
if (!copy($data->Url, $targetPath)) {
return null;
}
// Write the file to the DB
$image = Image::create(array(
'Name' => $data->Filename,
'ParentID' => $folder->ID,
'Filename' => $folder->getRelativePath() . $data->Filename
));
$image->write();
return $image;
}

Drupal Page Template based on url alias

I want to create an drupal page Template depending on the url alias.
Her my current situation:
I create a page named test, the url alias is test, too.
The page template, based on this docu - http://drupal.org/node/1089656 is: page--test.tpl.php.
I cleaned the drupal them cache, but there is still the default page template shown for this page.
What could be the error?
page--test.tpl.php doesn't work because Drupal is using the real path of page--node--#.tpl.php. To get Drupal to recognize aliased paths, you have to add the aliased path as part of the theme suggestions like so:
function MYMODULE_preprocess_page(&$vars, $hook) {
// only do this for page-type nodes and only if Path module exists
if (module_exists('path') && isset($vars['node']) && $vars['node']->type == 'page') {
// look up the alias from the url_alias table
$source = 'node/' .$vars['node']->nid;
$alias = db_query("SELECT alias FROM {url_alias} WHERE source = '$source'")->fetchField();
if ($alias != '') {
// build a suggestion for every possibility
$parts = explode('/', $alias);
$suggestion = '';
foreach ($parts as $part) {
if ($suggestion == '') {
// first suggestion gets prefaced with 'page--'
$suggestion .= "page--$part";
} else {
// subsequent suggestions get appended
$suggestion .= "__$part";
}
// add the suggestion to the array
$vars['theme_hook_suggestions'][] = $suggestion;
}
}
}
}
Source: http://groups.drupal.org/node/130944#comment-425189

Can Drupal change the template used based on a file extension in the url?

I am using Drupal 6.16 with a number of modules installed. I was trying to find out if there is a way to change the output of a node when a different file extension is added to the url. For example:
http://example.com/drupal?q=foo/bar - returns a normal drupal node
http://example.com/drupal?q=foo/bar.xml - returns xml output of the node
Is this even possible with Drupal? Do I have to hack the core code to get this working?
You should not need to hack the core code. There are probably several contributed modules that can do this for you.
To output an XML version of a node, check out the Views Bonus Pack module, which extends the Views module. It has basic export capabilities, including CSV, TXT, DOC, and XML. The documentation is brief, but there is a README.txt file in the views_bonus/export/ directory that gives the basic steps for creating a feed in a view that will output XML.
You can set the path for the feed, so while I don't believe the .xml extension will work, you could set up a path with an additional component like this:
http://example.com/drupal?q=foo/bar <-- normal output
http://example.com/drupal?q=foo/bar/xml <-- XML output
To change the template file that is used for a node based on the path, you can use a preprocess function in your template.php file to add a template suggestion based on the path. This takes a bit more understanding of how the template files work, but ultimately you'll have more control of the output than you will with a view.
Here is how I fixed this.
Add the custom_url_rewrite_inbound function to check for incoming request ending with .xml. If it finds a request ending with .xml it strips that off, so that the correct data can be located by the rest of the drupal machinery. It also sets 'subsite_xml_request' to true so that the appropriate theme template can be used later.
function custom_url_rewrite_inbound (&$result, $path, $path_language) {
if(preg_match('/\.xml$/', $path)) {
$search = preg_replace('/^(.*)\.xml$/', "$1", $path);
if ($src = drupal_lookup_path('source', $search, $path_language)) {
$_REQUEST['xml_request'] = true;
$result = $src;
}
}
Modify the phptemplate_preprocess_page function in your template.php to add additional '-xml' templates.
function phptemplate_preprocess_page(&$vars) {
if ($_REQUEST['xml_request']) {
if (module_exists('path')) {
$path = str_replace('/edit','',$_GET['q']);
$alias = drupal_get_path_alias($path);
if ($alias != $_GET['q']) {
$template_filename = 'page';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '-' . $path_part;
$vars['template_files'][] = $template_filename . '-xml';
}
$vars['template_files'][] = 'page-xml';
}
}
}
}
Create the required page-xml.tpl.php

Resources