I'm trying to integrate CKFinder(v.3) with CKEditor(v.4) in my Codeigniter project but getting error "Folder not found" when i tried to upload a file on to server. I hv googled this issue and tried various solutions like below but none had worked:
1) Changing permission for ckfinder folder to FULL for all users
2) Changing permission for data-content/page_assets folder to FULL for all users
3) Set baseURL path in config.php to "http://localhost:8080/project/cms/js/ckfinder/userfiles/"
Below are the editor setup in my view file
// filebrowserBrowseUrl & filebrowserUploadUrl will be different for each module but the base will
// same 'data-content'
CKEDITOR.replace( 'page_content', {
filebrowserBrowseUrl: '<?php echo base_url()?>js/ckfinder/ckfinder.html?Type=Images&rlf=0&start=Images:/project/data-content/page_assets/',
filebrowserUploadUrl: '<?php echo base_url()?>js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images¤tFolder=/project/data-content/page_assets/',
filebrowserWindowWidth: '1000',
filebrowserWindowHeight: '700'
});
Below are the config.php in CKFinder. Listing only what i had changed in this file
$config['authentication'] = function () {
return true;
};
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
//'baseUrl' => '/ckfinder/userfiles/',
'baseUrl' => 'http://localhost:8080/project/cms/js/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
$config['overwriteOnUpload'] = false;
$config['checkDoubleExtension'] = true;
$config['disallowUnsafeCharacters'] = true;
$config['secureImageUploads'] = true;
$config['checkSizeAfterScaling'] = true;
$config['htmlExtensions'] = array('html', 'htm', 'xml', 'js');
$config['hideFolders'] = array('.*', 'CVS', '__thumbs');
$config['hideFiles'] = array('.*');
$config['forceAscii'] = false;
$config['xSendfile'] = false;
// https://ckeditor.com/docs/ckfinder/ckfinder3-php/configuration.html#configuration_options_debug
$config['debug'] = true;
Detail error, after debugging on
Fatal error: Uncaught CKSource\CKFinder\Exception\FolderNotFoundException: Folder not found in C:\xampp\htdocs\project\cms\js\ckfinder\core\connector\php\vendor\cksource\ckfinder\src\CKSource\CKFinder\Filesystem\Folder\WorkingFolder.php:144
These are the concerned code block from WorkingFolder.php file
// Check if resource type folder exists - if not then create it
$currentCommand = (string) $request->query->get('command');
$omitForCommands = array('Thumbnail');
// DEBUGGING the value of EACH PROPERTY
// clientCurrentFolder => /noveltech/data-content/page_assets/
// $currentCommand => QuickUpload
// $resourceTypeDirectory => images
// $this->path => images/noveltech/data-content/page_assets/
if (!in_array($currentCommand, $omitForCommands) && !empty($resourceTypeDirectory) && !$backend->hasDirectory($this->path))
{
if ($this->clientCurrentFolder === '/') {
#$backend->createDir($resourceTypeDirectory);
if (!$backend->hasDirectory($resourceTypeDirectory))
{
throw new AccessDeniedException("Couldn't create resource type directory. Please check permissions.");
}
}
else {
throw new FolderNotFoundException(); // THIS IS LINE NO. 144
}
}
My development environment is XAMPP.
Can any one please help me in integrating CKFinder?
Much Regards,
Javed
Related
I have a following code in the Codeigniter controller to upload some files to "upload" folder in the remote ubuntu server. In this case there is created a new folder named as officer_id in the upload folder when upload files and should be applied 755 permissions to it. Otherwise rejected to upload the files.
public function addFiles()
{
$this->checkPermissions('add', 'officer');
$bc = array(array('link' => '#', 'page' => 'Attachments'));
$meta = array('page_title' => 'Officers - Files', 'bc' => $bc);
$this->data['officer'] = $this->Officer_model->getOfficer();
$this->form_validation->set_rules('officer', "Officer", 'required');
if ($this->form_validation->run() == true) {
$files = $this->multi_upload($_FILES['file'], './uploads/' . $this->input->post('officer'));
if (!empty($files)) {
foreach ($files as $fname) {
$fdata[] = array(
'officer' => $this->input->post('officer'),
'file_name' => $fname,
'status' => 1,
);
}
if ($this->db->insert_batch('tbl_officer_files', $fdata)) {
$this->session->set_flashdata('message', 'Officer Attachments Updated Successfully ..!!');
redirect('officer/addFiles');
} else {
$this->session->set_flashdata('message', 'Officer Attachments Updation Failed ..!!');
redirect('officer/addFiles');
}
}
}
$this->render('officer/addFiles', $meta, $this->data);
}
public function saveUpload()
{
$this->multi_upload($_FILES['file']);
if ($this->upload->do_upload('file')) {
$data = array('upload_data' => $this->upload->data());
$inputFileName = './uploads/' . $data['upload_data']['file_name'];
echo json_encode(array('success' => 'Files have been uploaded successfuly ..!!'));
} else {
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);//array('error' => 'You are not allowed to upload such a file.',
}
}
How can I modified my code to enable this (Like chmod ......) ? Can anyone help ?
You can use chmod("test.txt",0755); to update the permission on file after uploading.
You can do this step by step as follow.
//this function returns uploaded file path
$uploadedd_file = file_upload_function(...);
if(!file_exists($uploadedd_file)){
die('Error in uploading file');
}
// Setting file permission
$set_permission = chmod($uploadedd_file,0755);
if(!$set_permission){
// delete file if permission is not set
unlink($uploadedd_file);
}
// optional step to validate
$new_permission = substr(sprintf('%o', fileperms($uploadedd_file)), -4);
echo "all good goes here, file uploaded and permission is set to " . $new_permission;
Read more about chmod: https://www.w3schools.com/php/func_filesystem_chmod.asp
https://www.php.net/manual/en/function.chmod.php
I hope this works, let me know.
I'm using the Apache Chemistry CMIS PHP client to upload documents from a local folder to Alfresco Community Edition 5.1 via ATOM. Here's the script I'm using to do so:
require_once ('cmis_repository_wrapper.php');
require_once ('cmis_service.php');
$repo_url = "http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom";
$repo_username = "user";
$repo_password = "pass";
$client = new CMISService($repo_url, $repo_username, $repo_password);
$repo_folder = "/alfrescoFolder";
$source_folder = "localFolder/";
$source_files = array_diff(scandir("$source_folder", 1), array('..', '.'));
$myfolder = $client->getObjectByPath($repo_folder);
foreach($source_files as $file)
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file");
}
catch(Exception $e)
{
echo "Some error here.";
}
}
This script works fine and documents are uploaded without problem, provided that the document doesn't already exist in the Alfresco repository. For example, let's say I have a document in my Alfresco repository named example.txt, and so, if I try to upload a document from my local folder with the same name, I get a CMIS constraint exception. I dont't know how I can upload a new version of an existing document.
This is what I've tried so far, but it doesn't work:
$objs = $client->getChildren($myfolder->id);
foreach($source_files as $file)
{
foreach($objs->objectList as $obj)
{
if($obj->properties['cmis:name'] == $file)
{
try
{
$checkedout = $client->checkOut($obj->id);
$client->checkIn($checkedout->id);
}
catch(Exception $e)
{
echo "Some error here.";
}
}
else
{
try
{
$upload = $client->createDocumentFromSource($myfolder->id, $file, "$source_folder/$file", array('cmis:objectTypeId'=>'D:ex:document'));
}
catch(Exception $e)
{
echo "Some error here";
}
}
}
}
I get this error:
DEBUG: postEntry: myURL = http://127.0.0.1:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom/checkedoutDEBUG: postEntry: entry_template = {title} {SUMMARY} {CONTENT} {PROPERTIES} DEBUG: postEntry: properties_xml = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 DEBUG: postEntry: hash_values = Array ( [PROPERTIES] => b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0 [SUMMARY] => {summary} ) DEBUG: postEntry: post_value = b549c715-9a9d-427c-bd4b-c6ea29d222cb;1.0
What's funny is that the document is in fact locked for editing, so I don't really know what's going on. I also don't know if checking out and then checking in a document is how I'm supposed to version a document.
TL;DR
I want to be able to specify that the document I'm uploading is a new version of an existing document. Does anyone know how I can do that?
The function coverage page on the Apache Chemistry web site lists what the CMIS PHP client can and cannot do. Check out, check in, and cancel checkout are all unsupported at the present time. I know they would welcome contributions.
The underlying CMIS specification supports it, of course, so you can either update the library to support checkout/checkin or use the raw binding.
I'm not an expert on CMIS, but I think that this forum post answers the question. See the answer from "jevon" that provides an example and a link to this page (see the "Updating a document" section)
I've recently found out about an alternative CMIS PHP library that implements versioning services, including example usage. I've used it to successfully solve the problem I posted in my question.
Edit: additional information added.
So, to get versioning working, I used the example code provided in the library. The script I used can be used to create new documents and to update and version existing documents. So, here it is:
<?php
require_once(__DIR__ . '/../vendor/autoload.php');
if (!is_file(__DIR__ . '/conf/Configuration.php')) {
die("Please add your connection credentials to the file \"" . __DIR__ . "/conf/Configuration.php\".\n");
} else {
require_once(__DIR__ . '/conf/Configuration.php');
}
$major = (boolean) isset($argv[1]) ? $argv[1] : false;
$httpInvoker = new \GuzzleHttp\Client(
array(
'defaults' => array(
'auth' => array(
CMIS_BROWSER_USER,
CMIS_BROWSER_PASSWORD
)
)
)
);
$parameters = array(
\Dkd\PhpCmis\SessionParameter::BINDING_TYPE => \Dkd\PhpCmis\Enum\BindingType::BROWSER,
\Dkd\PhpCmis\SessionParameter::BROWSER_URL => CMIS_BROWSER_URL,
\Dkd\PhpCmis\SessionParameter::BROWSER_SUCCINCT => false,
\Dkd\PhpCmis\SessionParameter::HTTP_INVOKER_OBJECT => $httpInvoker,
);
$sessionFactory = new \Dkd\PhpCmis\SessionFactory();
// If no repository id is defined use the first repository
if (CMIS_REPOSITORY_ID === null) {
$repositories = $sessionFactory->getRepositories($parameters);
$repositoryId = $repositories[0]->getId();
} else {
$repositoryId = CMIS_REPOSITORY_ID;
}
$parameters[\Dkd\PhpCmis\SessionParameter::REPOSITORY_ID] = $repositoryId;
$session = $sessionFactory->createSession($parameters);
$rootFolder = $session->getObject($session->createObjectId($session->getRootFolder()->getId()));
try {
$document = null;
$stream = \GuzzleHttp\Stream\Stream::factory(fopen($filePath, 'r'));
foreach ($rootFolder->getChildren() as $child) {
if ($child->getName() === $fileName) {
$document = $child;
break;
}
}
if (!$document) {
$properties = array(
\Dkd\PhpCmis\PropertyIds::OBJECT_TYPE_ID => 'cmis:document',
\Dkd\PhpCmis\PropertyIds::NAME => $fileName
);
$document = $session->createDocument($properties, $rootFolder, $stream);
$document = $session->getObject($document);
}
$checkedOutDocumentId = $document->getVersionSeriesCheckedOutId();
if ($checkedOutDocumentId) {
$checkedOutDocumentId = $session->createObjectId($checkedOutDocumentId);
} else {
$checkedOutDocumentId = $document->checkOut();
}
$checkedInDocumentId = $session->getObject($checkedOutDocumentId)->checkIn(
$major,
array(
\Dkd\PhpCmis\PropertyIds::DESCRIPTION => 'New description'
),
$stream,
'Comments'
);
} catch (\Dkd\PhpCmis\Exception\CmisVersioningException $e) {
echo "********* ERROR **********\n";
echo $e->getMessage() . "\n";
echo "**************************\n";
exit();
}
I have one page where I can upload files. On my localhost everything work fine but on the shared host doesn't work and when I load the page it crashing and showing Error 500 - Internal Server Error.
The only different's between local configuration and configuration on the host is eAccelerator which is enabled by default on the shared host.
I have tried to create php.ini on the host and disable it but no luck so far. In the .htaccess i've put:
<IfModule mod_suphp.c>
suPHP_ConfigPath /home/myuser/public_html/php.ini
</IfModule>
note: myuser is not my real user.. I've changed it just for here.
Then in php.ini I put this but on the phpinfo() is still showing that is enabled.
eaccelerator.enable 0
eaccelerator.optimizer 0
Sadly but there is not errors anywhere so I don't know what exactly going on here. No errors in cPanel. No errors in the directory with the file. No errors when I try with error_reporting(E_ALL); and ini_set('display_errors', 'on');.
When I remove this portion of code the page is loaded and no errors. So the problem is in the code + eaccelator. Here is the code which is located above the HTML form in the same file.
if (array_key_exists("add", $_POST)) {
$pdo = Database::connect();
$allowedFileTypes = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp');
$uploadFolder = "uploads/";
$totalFiles = 0;
$files = (object)[
'file_1' => (object)['name' => ''],
'file_2' => (object)['name' => ''],
'file_3' => (object)['name' => '']
];
$query = "INSERT INTO file_upload (
`file_title`, `file_program`, `file_subject`, `file_1`, `file_2`, `file_3`, `uploaded_by`, `upload_date`
) VALUES (
:file_title, :file_program, :file_subject, :file_1, :file_2, :file_3, :uploaded_by, NOW()
)";
$queryPrepare = $pdo->prepare($query);
foreach (array_keys($_FILES) as $file) {
$filesInCurrentInput = count(array_filter($_FILES[$file]['tmp_name']));
if (!$filesInCurrentInput) {
continue;
}
$totalFiles += $filesInCurrentInput;
for ($i = 0; $i < $filesInCurrentInput; $i++) {
if ($_FILES[$file]['error'][$i]) {
continue;
}
$type = $_FILES[$file]['type'][$i];
if (!in_array($type, $allowedFileTypes)) {
throw new Exception("File type not allowed.");
}
$oldName = $_FILES[$file]['name'][$i];
$getEndOfFile = explode(".", $oldName);
$extension = end($getEndOfFile);
$name = hash("md5", uniqid(rand(), true)) . '.' . $extension;
$temporaryFile = $_FILES[$file]['tmp_name'][$i];
if (!move_uploaded_file($temporaryFile, $uploadFolder.$name)) {
throw new Exception("An error occured while trying to upload a file.");
} else {
$files->$file->name .= $name . ',';
}
}
}
if (!$totalFiles) {
throw new Exception("You must attach files to the lesson.");
}
$title = htmlspecialchars($_POST['file_title']);
$file_program = htmlspecialchars($_POST['file_program']);
$file_subject = htmlspecialchars($_POST['file_subject']);
$uploaded_by = htmlspecialchars($_SESSION['user_username']);
$queryPrepare->bindValue(":file_title", $title);
$queryPrepare->bindValue(":file_program", $upload_program);
$queryPrepare->bindValue(":file_subject", $upload_subject);
$queryPrepare->bindValue(":file_1", trim($files->file_1->name, ','));
$queryPrepare->bindValue(":file_2", $files->file_2->name);
$queryPrepare->bindValue(":file_3", $files->file_3->name);
$queryPrepare->bindValue(":uploaded_by", $uploaded_by);
$queryPrepare->execute();
echo "<p class='bg-success text-center'>File added successfully.</p>";
}
The form is simple form with few fields.. nothing special there. Any help on this?
Please change this:
$files = (object)[
'file_1' => (object)['name' => ''],
'file_2' => (object)['name' => ''],
'file_3' => (object)['name' => '']
];
To this and try to reload the page:
$files = (object)array(
'file_1' => (object)array('name' => ''),
'file_2' => (object)array('name' => ''),
'file_3' => (object)array('name' => '')
);
I would to retrieve from a path all sub (and sub-sub) directories and all files (only with .php and .css extensions) in (last sub) it.
The structre is the following:
my_path/sub-folder1/ // I want to get the sub folder name (and check if allowed)
sub-sub-folder1/file1.php // I want to get the file name and path
sub-sub-folder1/file1.css // I want to get the file name and path
sub-sub-folder2/file2.php // ....
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
my_path/sub-folder2/
sub-sub-folder1/file1.php
sub-sub-folder1/file1.css
sub-sub-folder2/file2.php
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
I know the my_pathdirectory name. About sub-folder, I only want to retrieve sub-folder which have the name (sub-folder1, sub-folder2 for example). And I would like to retrieve all sub-sub-folders and inside them and get the name and path of the .css and .php files inside it. I'm not sure if I'm clear with my explanations.
My aim is to store all this information in an array like this:
$data['sub-folder-1']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
$data['sub-folder-2']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
I have started with this code but I have some difficulties to make it works (and it's not finished), I don't use this kind of functionnality a lot...
$dirname = 'my_path';
$findphp = '*.php';
$findcss = '*.css';
$types = array('sub-folder1','sub-folder2');
$sub_dirs = glob($dirname.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_dirs)) {
foreach($sub_dirs as $sub_dir) {
$sub_dir_name = basename($sub_dir);
if (in_array($sub_dir_name,$types)) {
$sub_sub_dirs = glob($sub_dir.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_sub_dirs)) {
foreach($sub_sub_dirs as $sub_sub_dir) {
$php = glob($sub_sub_dir.'/'.$findphp);
$css = glob($sub_sub_dir.'/'.$findcss);
$sub_sub_dir_name = basename($sub_sub_dir);
$data[$sub_dir_name][$sub_sub_dir_name]['type'] = $sub_dir_name;
$data[$sub_dir_name][$sub_sub_dir_name]['name'] = basename($php[0], '.php');
$data[$sub_dir_name][$sub_sub_dir_name]['html'] = $php[0];
$data[$sub_dir_name][$sub_sub_dir_name]['css'] = $css[0];
}
}
}
}
} else {
echo "Nothing was found.";
}
print_r($data);
I like using the RecursiveDirectoryIterator class. I think it's more readable. This sample allow you to read all subfolders of a given source.
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source)); // Top source directory
$iterator->setFlags(\FilesystemIterator::SKIP_DOTS); // Skip folders with dot
$allowedExtension = array('php', 'css'); // And other if needed
$skin = array();
while ($iterator->valid()) {
$extension = $iterator->getExtension(); // >= PHP 5.3.6
if ($iterator->isFile() && in_array($extension, $allowedExtension)) {
// Complete this part or change it following your needs
switch ($extension) {
case 'php':
// All your logic here
$skin[$iterator->getPath()]['name'] = $iterator->getFileName(); //eg
break;
default:
break;
}
}
$iterator->next();
}
You can find the whole list of available functions at Directory Iterator.
Hope it's help.
I'm trying to do something very simple but I can't see to make it work. For what it's worth, I'm currently testing on my MAMP dev machine, but get the same results from staging server (GoDaddy GridHost).
Here's what I want to do:
Upload an image specified by the user from a form.
Create a thumbnail of the uploaded image.
There is some extra database code in my example, but the script "errors" at the if( ! $this->image_lib->resize()) call. However, it causes the entire application to exit, rendering a blank page. The code never actually enters the if{} block.
function _upload_image(&$location, &$image = NULL)
{
// Configure the initial full-sized image upload
$upload_config = array(
'upload_path' => "./uploads/users/{$this->viewer->id}/locations/{$location->id}/",
'allowed_types' => 'jpg|jpeg|gif|bmp|png',
'max_size' => 8192 // 8mb
);
$this->load->library('upload', $upload_config);
// Upload failed
if( ! $this->upload->do_upload('image'))
{
$this->errors = strip_tags($this->upload->display_errors());
return FALSE;
}
// Get the uploaded file's metadata
$data = $this->upload->data();
// Change permissions of the uploaded file so that the image library can copy and resize it
if(is_file($config['upload_path'] . $data['file_name']))
{
chmod($config['upload_path'] . $data['file_name'], 0777);
}
// If no existing image object was passed to this function, we are creating a brand new image
if(is_null($image))
{
$image = new Image();
$thumbnail = new Thumbnail();
}
else
{
$thumbnail = $image->thumbnail->get(); // Get the existing thumbnail
}
// Set the image object fields to save to the db
$image->name = $data['file_name'];
$image->mime_type = $data['file_type'];
$image->extension = $data['file_ext'];
$image->file_path = $data['file_path'];
$image->full_path = $data['full_path'];
$image->size = $data['file_size'];
$image->width = $data['image_width'];
$image->height = $data['image_height'];
// Failed to save the image to the db
if( ! $image->save())
{
$this->errors = array_merge($this->errors, array($image->error->string));
return FALSE;
}
// Failed to save the location/image relationship in the db
if( ! $location->save($image))
{
$this->errors = array_merge($this->errors, array($location->error->string));
return FALSE;
}
// Configure options for the thumbnail
$thumb_config = array(
'image_library' => 'GD2',
'source_image' => "./uploads/users/{$this->viewer->id}/locations/{$location->id}/{$image->name}",
'create_thumb' => TRUE,
'width' => 400,
'height' => 300
);
$this->load->library('image_lib');
$this->image_lib->initialize($thumb_config);
// Failed to create the image thumbnail
if( ! $this->image_lib->resize())
{
$this->errors = array_merge($this->errors, array($this->image_lib->display_errors()));
return FALSE;
}
// Set the thumbnail object fields to save to the db
$thumbnail->name = $data['raw_name'] . '_thumb' . $data['file_ext'];
$thumbnail->file_path = $image->file_path;
$thumbnail->full_path = $image->file_path . $thumbnail->name;
// Failed to save the thumbnail to the db
if( ! $thumbnail->save())
{
$this->errors = array_merge($this->errors, array($thumbnail->error->string));
return FALSE;
}
// Failed to save the image/thumbnail relationship in the db
if( ! $image->save($thumbnail))
{
$this->errors = array_merge($this->errors, array($image->error->string));
return FALSE;
}
// Everything worked
return TRUE;
}
The database interaction is handled by the DataMapper ORM, which I included for completeness, but I don't feel it is necessarily relevant to this issue. The function clearly fails at the call:
if( ! $this->image_lib->resize())
Have you set your application environment in the index.php bootstrap? It's worth setting it to development if you haven't already, this may make errors visible that would be hidden if set to testing/production.
define('ENVIRONMENT', 'development');
If that doesn't help diagnose the issue, in MAMP, go to the Server tab, click PHP and then View Log. This will open up the PHP error log file which will hopefully give you an idea of what's up.