Template_searchpath gives TemplateNotFound error in Airflow and cannot find the SQL script - sql

I have a DAG described like this :
tmpl_search_path = '/home/airflow/gcs/sql_requests/'
with DAG(dag_id='pipeline', default_args=default_args, template_searchpath = [tmpl_search_path]) as dag:
create_table = bigquery_operator.BigQueryOperator(
task_id = 'create_table',
sql = 'create_table.sql',
use_legacy_sql = False,
destination_dataset_table = some_table)
)
The task create_table calls a SQL script create_table.sql. This SQL script is not in the same folder as the DAG folder : it is in a sql_requests folder at the same level as the DAG folder.
This is the architecture inside the bucket of the GCP Composer (which is the Google Airflow) is :
bucket_name
|- airflow.cfg
|- dags
|_ pipeline.py
|- ...
|_ sql_requests
|_ create_table.sql
What path do I need to set for template_searchpath to reference the folder sql_requests inside the Airflow bucket on GCP ?
I have tried template_searchpath= ['/home/airflow/gcs/sql_requests'], template_searchpath= ['../sql_requests'], template_searchpath= ['/sql_requests'] but none of these have worked.
The error message I get is 'jinja2.exceptions.TemplateNotFound'

According to https://cloud.google.com/composer/docs/concepts/cloud-storage it is not possible to store files that are needed to execute dags elsewhere than in the folders dags or plugins :
To avoid a workflow failure, store your DAGs, plugins, and Python modules in the dags/ or plugins/ folders—even if your Python modules do not contain DAGs or plugins.
This is the reason why I had the TemplateNotFound error.

You can store in mounted/known paths which are dags/plugins OR data
data folder has no capacity limits but it's easy to throw yourself off using it to store anything that the web server would need to read, because the web server can't access that folder (e.g if you put SQL files in /data folder, you would not be able to parse rendered template in the UI, but any tasks that need to access the file during run time would just run fine)

Change 'sql_requests' folder into the 'dag' folder so that your code will be like this:
tmpl_search_path = '/home/airflow/dags/sql_requests/'
with DAG(dag_id='pipeline', default_args=default_args, template_searchpath = [tmpl_search_path]) as dag:
create_table = bigquery_operator.BigQueryOperator(
task_id = 'create_table',
sql = 'create_table.sql',
use_legacy_sql = False,
destination_dataset_table = some_table
)
)
For me, it works!

I believe by default the operator looks for sql files in the DAG folder, so you could put your SQL into the folder
gs://composer-bucket-name/dags/sql/create_table.sql
And then reference it as
sql = '/sql/create_table.sql'
If that doesn't work, try it without the leading / (which I'm not sure you need)
Edit
If you want to put them in a folder at the root of the bucket, try
sql = '../sql/create_table.sql'

Related

can karate read files from outside the classpath with a relative path instead of absolute path

I'm trying to read a properties file for karate-config.js. It works when i provide the absolute path from my local but when i provide a relative path. it doesn't work. Any way around this? Thanks !
var config = karate.read("file:/repo/tests/utils/al_dev.json"); -- This doesn't work
var config = karate.read("file:~/repo/tests/utils/al_dev.json"); -- This doesn't work
var config = karate.read("file:/Users/user1/IdeaProjects/repo/tests/utils/al_dev.json"); -- This works
I was able to get it working. I had to update the path to reflect the project structure and it worked.
var config = karate.read("file:../../utils/al_dev.json");
Project structure:
project1 ->
tests ->
Utils ->
Services ->
client 1 ->
client 2 ->
I took advantage of answer wrote by Peter Thomas and it worked for me, I could read a json body from a file somewhere else in the project, not needed to be in the same folder as features. This is a sample of code I used:
Scenario: POST with json file reading from anywhere.
Given path "/api/apitesting/v1/transactions"
And def projectPath = karate.properties['user.home']
And def filePath = projectPath + "/IdeaProjects/01 Courses TM/karate/src/test/resources/data/TestBodyAnywhere.json"
And def requestBody = read('file:' + filePath)
And request requestBody
When method post
Then status 201
As you can see, I used user.home instead of user.dir, (which use to be recommended but this points directly to the same folder where you are calling it instead of pointing to outside that folder). User.home points directly to your root user, so it would be something like this C:/Users/MyUser. Then, from there you can start indicating the relative path in a new variable to your file. Finally, remember to use 'File:' keyword inside the read method and concatenate it with your path variable.
Hope it helps. ;)
Best regards!
Sorry, Karate (Java) can't resolve these special OS paths. I guess you know that this is not recommended, best practice is all test resources be kept under the project root. Anyway, here is a workaround:
* def home = java.lang.System.getProperty('user.home')
* def temp = read('file:' + home + '/repo/tests/utils/al_dev.json')

TFX root in TFX taxi example

What does the _tfx_root in the Chicago taxi example refer to and why is it needed?
I'm talking about this line: https://github.com/tensorflow/tfx/blob/master/examples/chicago_taxi_pipeline/taxi_pipeline_simple.py#L54
The metadata end pipelines end up in ~/tfx but without having a local copy of the tfx git repo it does not run in Airflow (locally).
The metadata directory is created when running airflow initdb, after you've manually copied the pipeline Python file to $AIRFLOW_HOME/dags/blabla directory. It would be nice to be able to configure the location of ~/tfx though. Any ideas how?
code:- _tfx_root = os.path.join(os.environ['HOME'], 'tfx');
It is used to define relative path to the directory called 'tfx' which is created at home directory(if it doesn't exist) of logged in user. in which HOME is an environment variable.
code:- _pipeline_root = os.path.join(_tfx_root, 'pipelines');
use relative path to create/append child directory "pipelines" to tfx_root path.
code:- _metadata_db_root = os.path.join(_tfx_root, 'metadata');
use relative path to create/append child directory "metadata" to tfx_root path.
code:- _log_root = os.path.join(_tfx_root, 'logs');
use relative path to create/append child directory "logs" to tfx_root path.
It is the path of the data directory. This variable is only used to build the path of the pipeline, metadata and root directories.
_tfx_root = os.path.join(os.environ['HOME'], 'tfx'); // Create location ~/tfx
_pipeline_root = os.path.join(_tfx_root, 'pipelines'); // Join ~/tfx/pipelines/
_metadata_db_root = os.path.join(_tfx_root, 'metadata'); // Join ~/tfx/metadata/
_log_root = os.path.join(_tfx_root, 'logs'); // Join ~/tfx/logs/
Just modify _tfx_root to change the location of ~/tfx. If you want the location to be C:/temp/tfx. Use this for example.
_tfx_root = 'C:/temp/tfx/';

Add folder in Amazon s3 bucket

I want to add Folder in my amazon s3 bucket using coding.
Can you please suggest me how to achieve this?
There are no folders in Amazon S3. It just that most of the S3 browser tools available show part of the key name separated by slash as a folder.
If you really need that you can create an empty object with the slash at the end. e.g. "folder/" It will looks like a folder if you open it with a GUI tool and AWS Console.
As everyone has told you, in AWS S3 there aren't any "folders", you're thinking of them incorrectly. AWS S3 has "objects", these objects can look like folders but they aren't really folders in the fullest sense of the word. If you look for creating folders on the Amazon AWS S3 you won't find a lot of good results.
There is a way to create "folders" in the sense that you can create a simulated folder structure on the S3, but again, wrap your head around the fact that you are creating objects in S3, not folders. Going along with that, you will need the command "put-object" to create this simulated folder structure. Now, in order to use this command, you need the AWS CLI tools installed, go here AWS CLI Installation for instructions to get them installed.
The command is this:
aws s3api put-object --bucket your-bucket-name --key path/to/file/yourfile.txt --body yourfile.txt
Now, the fun part about this command is, you do not need to have all of the "folders" (objects) created before you run this command. What this means is you can have a "folder" (object) to contain things, but then you can use this command to create the simulated folder structure within that "folder" (object) as I discussed earlier. For example, I have a "folder" (object) named "importer" within my S3 bucket, lets say I want to insert sample.txt within a "folder" (object) structure of the year, month, and then a sample "folder" (object) within all of that.
If I only have the "importer" object within my bucket, I do not need to go in beforehand to create the year, month, and sample objects ("folders") before running this command. I can run this command like so:
aws s3api put-object --bucket my-bucket-here --key importer/2016/01/sample/sample.txt --body sample.txt
The put-object command will then go in and create the path that I have specified in the --key flag. Here's a bit of a jewel: even if you don't have a file to upload to the S3, you can still create objects ("folders") within the S3 bucket, for example, I created a shell script to "create folders" within the bucket, by leaving off the --body flag, and not specifying a file name, and leaving a slash at the end of the path provided in the --key flag, the system creates the desired simulated folder structure within the S3 bucket without inserting a file in the process.
Hopefully this helps you understand the system a little better.
Note: once you have a "folder" structure created, you can use the S3's "sync" command to syncronize the descendant "folder" with a folder on your local machine, or even with another S3 bucket.
Java with AWS SDK:
There are no folders in s3, only key/value pairs. The key can contain slashes (/) and that will make it appear as a folder in management console, but programmatically it's not a folder it is a String value.
If you are trying to structure your s3 bucket, then your naming conventions (the keys you give your files) can simply follow normal directory patterns, i.e. folder/subfolder/file.txt.
When searching (depending on language you are using), you can search via prefix with a delimiter. In Java, it would be a listObjects(String storageBucket, String prefix, String delimiter) method call.
The storageBucket is the name of your bucket, the prefix is the key you want to search, and the delimiter is used to filter your search based off the prefix.
The AWS:S3 rails gem does this by itself:
AWS::S3::S3Object.store("teaser/images/troll.png", file, AWS_BUCKET)
Will automatically create the teaser and images "folders" if they don't already exist.
With AWS SDK .Net works perfectly, just add "/" at the end of the name folder:
var folderKey = folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);
Then refresh your AWS console, and you will see the folder
With aws cli, it is possible to copy an entire folder to a bucket.
aws s3 cp /path/to/folder s3://bucket/path/to/folder --recursive
There is also the option to sync a folder using aws s3 sync
This is a divisive topic, so here is a screenshot in 2019 of the AWS S3 console for adding folders and the note:
When you create a folder, S3 console creates an object with the above
name appended by suffix "/" and that object is displayed as a folder
in the S3 console.
Then 'using coding' you can simply adjust the object name by prepending a valid folder name string and a forward slash.
For Swift I created a method where you pass in a String for the folder name.
Swift 3:
import AWSS3
func createFolderWith(Name: String!) {
let folderRequest: AWSS3PutObjectRequest = AWSS3PutObjectRequest()
folderRequest.key = Name + "/"
folderRequest.bucket = bucket
AWSS3.default().putObject(folderRequest).continue({ (task) -> Any? in
if task.error != nil {
assertionFailure("* * * error: \(task.error?.localizedDescription)")
} else {
print("created \(Name) folder")
}
return nil
})
}
Then just call
createFolderWith(Name:"newFolder")
In iOS (Objective-C), I did following way
You can add below code to create a folder inside amazon s3 bucket programmatically. This is working code snippet. Any suggestion Welcome.
-(void)createFolder{
AWSS3PutObjectRequest *awsS3PutObjectRequest = [AWSS3PutObjectRequest new];
awsS3PutObjectRequest.key = [NSString stringWithFormat:#"%#/", #"FolderName"];
awsS3PutObjectRequest.bucket = #"Bucket_Name";
AWSS3 *awsS3 = [AWSS3 defaultS3];
[awsS3 putObject:awsS3PutObjectRequest completionHandler:^(AWSS3PutObjectOutput * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(#"error Creating folder");
}else{
NSLog(#"Folder Creating Sucessful");
}
}];
}
Here's how you can achieve what you're looking for (from code/cli):
--create/select the file (locally) which you want to move to the folder:
~/Desktop> touch file_to_move
--move the file to s3 folder by executing:
~/Desktop> aws s3 cp file_to_move s3://<path_to_your_bucket>/<new_folder_name>/
A new folder will be created on your s3 bucket and you'll now be able to execute cp, mv, rm ... statements i.e. manage the folder as usual.
If this new file created above is not required, simply delete it. You now have an s3 bucket created.
You can select language of your choice from available AWS SDK
Alternatively you can try minio client libraries available in Python, Go, .Net, Java, Javascript for your application development environment, it has example directory with all basic operations listed.
Disclaimer: I work for Minio
In swift 2.2 you can create folder using
func createFolderWith(Name: String!) {
let folderRequest: AWSS3PutObjectRequest = AWSS3PutObjectRequest()
folderRequest.key = Name + "/"
folderRequest.bucket = "Your Bucket Name"
AWSS3.defaultS3().putObject(folderRequest).continueWithBlock({ (task) -> AnyObject? in
if task.error != nil {
assertionFailure("* * * error: \(task.error?.localizedDescription)")
} else {
print("created \(Name) folder")
}
return nil
})
}
Below creates a empty directory called "mydir1".
Below is nodejs code, it should be similar for other languages.
The trick is to have slash (/) at the end of the name of object, as in "mydir1/", otherwise a file with name "mydir1" will be created.
let AWS = require('aws-sdk');
AWS.config.loadFromPath(__dirname + '\\my-aws-config.json');
let s3 = new AWS.S3();
var params = {
Bucket: "mybucket1",
Key: "mydir1/",
ServerSideEncryption: "AES256" };
s3.putObject(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
return;
} else {
console.log(data); // successful response
return;
/*
data = {
ETag: "\"6805f2cfc46c0f04559748bb039d69ae\"",
ServerSideEncryption: "AES256",
VersionId: "Ri.vC6qVlA4dEnjgRV4ZHsHoFIjqEMNt"
}
*/
} });
Source: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
in-order to create a directory inside s3 bucket and copy contents inside that is pretty simple.
S3 command can be used:
aws s3 cp abc/def.txt s3://mybucket/abc/
Note: / is must that makes the directory, otherwise it will become a file in s3.
I guess your query is just simply creating a folder inside folder(subfolder).
so while coping any directory data inside a bucket sub folder use command like this.
aws s3 cp mudit s3://mudit-bucket/Projects-folder/mudit-subfolder --recursive
It will create a subfolder and put ur directory contents in it. Also once your subfolder data gets empty. Your Subfolder will automatically gets deleted.
You can use copy command to create a folder while copy a file.
aws s3 cp test.xml s3://mybucket/myfolder/test.xml

Amazon S3 boto - how to create a folder?

How can I create a folder under a bucket using boto library for Amazon s3?
I followed the manual, and created the keys with permission, metadata etc, but no where in the boto's documentation it describes how to create folders under a bucket, or create a folder under folders in bucket.
There is no concept of folders or directories in S3. You can create file names like "abc/xys/uvw/123.jpg", which many S3 access tools like S3Fox show like a directory structure, but it's actually just a single file in a bucket.
Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto
k = bucket.new_key('abc/123/')
k.set_contents_from_string('')
Or use the console
Use this:
import boto3
s3 = boto3.client('s3')
bucket_name = "YOUR-BUCKET-NAME"
directory_name = "DIRECTORY/THAT/YOU/WANT/TO/CREATE" #it's name of your folders
s3.put_object(Bucket=bucket_name, Key=(directory_name+'/'))
With AWS SDK .Net works perfectly, just add "/" at the end of the folder name string:
var folderKey = folderName + "/"; //end the folder name with "/"
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(AWSAccessKey, AWSSecretKey);
var request = new PutObjectRequest();
request.WithBucketName(AWSBucket);
request.WithKey(folderKey);
request.WithContentBody(string.Empty);
S3Response response = client.PutObject(request);
Then refresh your AWS console, and you will see the folder
Tried many method above and adding forward slash / to the end of key name, to create directory didn't work for me:
client.put_object(Bucket="foo-bucket", Key="test-folder/")
You have to supply Body parameter in order to create directory:
client.put_object(Bucket='foo-bucket',Body='', Key='test-folder/')
Source: ryantuck in boto3 issue
Append "_$folder$" to your folder name and call put.
String extension = "_$folder$";
s3.putObject("MyBucket", "MyFolder"+ extension, new ByteArrayInputStream(new byte[0]), null);
see:
http://www.snowgiraffe.com/tech/147/creating-folders-programmatically-with-amazon-s3s-api-putting-babies-in-buckets/
Update for 2019, if you want to create a folder with path bucket_name/folder1/folder2 you can use this code:
from boto3 import client, resource
class S3Helper:
def __init__(self):
self.client = client("s3")
self.s3 = resource('s3')
def create_folder(self, path):
path_arr = path.rstrip("/").split("/")
if len(path_arr) == 1:
return self.client.create_bucket(Bucket=path_arr[0])
parent = path_arr[0]
bucket = self.s3.Bucket(parent)
status = bucket.put_object(Key="/".join(path_arr[1:]) + "/")
return status
s3 = S3Helper()
s3.create_folder("bucket_name/folder1/folder2)
It's really easy to create folders. Actually it's just creating keys.
You can see my below code i was creating a folder with utc_time as name.
Do remember ends the key with '/' like below, this indicates it's a key:
Key='folder1/' + utc_time + '/'
client = boto3.client('s3')
utc_timestamp = time.time()
def lambda_handler(event, context):
UTC_FORMAT = '%Y%m%d'
utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
utc_time = utc_time.strftime(UTC_FORMAT)
print 'start to create folder for => ' + utc_time
putResponse = client.put_object(Bucket='mybucketName',
Key='folder1/' + utc_time + '/')
print putResponse
Although you can create a folder by appending "/" to your folder_name. Under the hood, S3 maintains flat structure unlike your regular NFS.
var params = {
Bucket : bucketName,
Key : folderName + "/"
};
s3.putObject(params, function (err, data) {});
S3 doesn't have a folder structure, But there is something called as keys.
We can create /2013/11/xyz.xls and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.
Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects method and using the Prefix parameter.
Apparently you can now create folders in S3. I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown.
This question is more relevant to the future, so adding this update.
I am using the upload_file method as shown below.
fold ='/my/system/filePath/tabmcq/Tables/auto/18.tsv'
s3_client.upload_file(
Filename = full/file/path/filename.extension,
Bucket = "tab-mcq-de",
Key = f"{fold.split('/')[-3]}/{fold.split('/')[-2]}/{fold.split('/')[-1]}"
)
Ideas is the "Filename" parameter requires the absolute file path of your system.
The "Key" parameter requires the relative file path from the source directory where your files are located
In case of this example, Key parameter has to contain "Tables/auto/18.tsv" value, for client to create the folders.
Hope this helps.
The following works using Python boto3
s3 = boto3.client("s3")
s3.put_object(Bucket="dest_bucket", Key='folder_name/')

How to set image path for fckeditor?

I am using fckeditor for PHP. I have set an absolute path for image uploading. I can upload images, but I am unable to use images that were uploaded. Can anyone help me find my problem?
Here is the code I have changed in my config.php file:
// Path to user files relative to the document root.
$Config['UserFilesPath'] = '/userfiles/' ;
// Fill the following value it you prefer to specify the absolute path for the
// user files directory. Useful if you are using a virtual directory, symbolic
// link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
// Attention: The above 'UserFilesPath' must point to the same directory.
$Config['UserFilesAbsolutePath'] = '/var/www/host/mysite//userfiles/' ;
I just solved this frustrating problem after a full day of searching on Google.
The solution is here. Look for:
Returning Full URLs
You can configure the File Browser to return full URLs to FCKeditor, like "http://www.example.com/userfiles/", instead of absolute URLs, like "/userfiles/". To do that, you must configure the connector, combining the UserFilesPath and UserFilesAbsolutePath settings:
UserFilesPath: include here the full URL for the user files directory. For example, set it to "http://www.example.com/userfiles/".
UserFilesAbsolutePath: include here the server path to reach the above URL directory. For example, in a Windows environment, you could have something like "C:/inetpub/mysite/userfiles/", while on Linux, something like "/usr/me/public_html/mysite/userfiles/".
Just adjust the above settings to your installation values and the File Browser will start returning full URLs to the editor.
For your localhost :
$Config['UserFilesPath'] = 'http://localhost/mywebsite/userfiles/' ;
$Config['UserFilesAbsolutePath'] = 'C:\\wamp\www\\mywebsite\\userfiles\\' ;
and in order to get your images from there, use :
$path = 'http://localhost/mywebsite/userfiles/image/myimage.jpg';
Now, For your web server:
$Config['UserFilesPath'] = 'http://localhost/mywebsite/userfiles/' ; // if your webserver named localhost as mine
$Config['UserFilesAbsolutePath'] = '/var/www/vhosts/mywebsite.com/httpdocs/' ;
and the images path remains the same as above.
Check the permission of the folder
Full Subject: FCK editor 2.x: File/image/video upload in different folders for different applications using a single FCKeditor, by making $Config['UserFilesPath'] fully dynamic in a secure way
It can be done in many ways. I am explaining a process, which I applied as per my php applications' code structure. The same code structure/framework I followed for different applications, with each application as a sub-folder in my server. So, there is a logical need to use one single FCKeditor and configure it in some way, so that it work properly for all the applications. The content part of FCKeditor is ok. It can easily be reused by different applications or projects from a single FCKeditor component. But the problem arises with file upload, like image, video or any other document. To make it applicable for different project, the files must be uploaded in separe folders for different projects. And for that $Config['UserFilesPath'] must by configured with dynamic folder path, means different folder path for each project, but calling the the same FCKeditor component in the same location. I am explaning some differnt process together in a step-by-step way. Those worked for me fine with FCKeditor version 2.5.1 and VersionBuild 17566 and I hope they will work for others as well. If it does not work for other developrs, then may be they need to make some tweaks in those process as per their project code structure and folder write permission as well as per the FCKeditor version.
1) In fckeditor\editor\filemanager\connectors\phpconfig.php file
a) Go after global $Config ; and $Config['Enabled'] = false ;
i) There, if want a session dependent secure method: only for single site setting: i.e. one FCKeditor for each one project domain or subdomain, not one FCKeditor for multiple project then place this code:
if(!isset($_SESSION)){
session_start();
}
if(isset($_SESSION['SESSION_SERVER_RELATIVEPATH']) && $_SESSION['SESSION_SERVER_RELATIVEPATH']!="") {
$relative_path=$_SESSION['SESSION_SERVER_RELATIVEPATH'];
include_once($_SERVER['DOCUMENT_ROOT'].$relative_path."configurations/configuration.php");
}
N.B.: Here, $_SESSION['SESSION_SERVER_RELATIVEPATH']: relative folder path of the project corresponding to the webroot; should be like "/project/folder/path/" and set this session variable in a common file in your project where the session started. And there should be a configurations/configuration.php as the configuration file in your project. If it's name or path is different you have to place the corresponding path here instead of configurations/configuration.php
ii) If want to use a single FCKeditor component for different projects represented as different sub-folders and with a session dependent secure way (Assuming different session_name for different projects, to differentiate their sessions in a single server). But it will not work if projects represented as sub-domains or different domains, then have to use the session independent way (iii) provided bellow (though it is insecure). Place this code:
if(!isset($_SESSION)){
session_name($_REQUEST['param_project_to_fck']);
session_start();
}
if(isset($_SESSION['SESSION_SERVER_RELATIVEPATH']) && $_SESSION['SESSION_SERVER_RELATIVEPATH']!="") {
$relative_path=$_SESSION['SESSION_SERVER_RELATIVEPATH'];
include_once($_SERVER['DOCUMENT_ROOT'].$relative_path."configurations/configuration.php");
}
Please read N.B. at the end of previous point, i.e. point (i)
iii) If want to use a single FCKeditor component for different projects represented either different sub-folders as well as sub-domains or domains (though it is not fully secure). Place this code:
if(isset($_REQUEST['param_project_to_fck']) && $_REQUEST['param_project_to_fck']!=""){ //base64 encoded relative folder path of the project corresponding to the webroot; should be like "/project/folder/path/" before encoding
$relative_path=base64_decode($_REQUEST['param_project_to_fck']);
include_once($_SERVER['DOCUMENT_ROOT'].$relative_path."configurations/configuration.php");
}
Please read N.B. at the end of point (i)
b)Now after that for any case you selected, please find this code:
// Path to user files relative to the document root.
$Config['UserFilesPath'] = '/userfiles/' ;
and replace the following code:
if(isset($SERVER_RELATIVEPATH) && $SERVER_RELATIVEPATH==$relative_path) { //to make it relatively secure so that hackers can not create any upload folder automatcally in the server, using a direct link and can not upload files there
$Config['Enabled'] = true ;
$file_upload_relative_path=$SERVER_RELATIVEPATH;
}else{
$Config['Enabled'] = false ;
exit();
}
// Path to user files relative to the document root.
//$Config['UserFilesPath'] = '/userfiles/' ;
//$Config['UserFilesPath'] = $file_upload_relative_path.'userfiles/' ;
$Config['UserFilesPath'] = '/userfiles'.$file_upload_relative_path;
Here $SERVER_RELATIVEPATH is the relative path and it must be set in your project's configuration file included previously.
Here you can set the $Config['UserFilesPath'] with any other dynamic folder path using $file_upload_relative_path variable.In my bluehost linux server, as their was a folder user permission conflict between the project root folder (0755 permission) and the userfiles folder under it and subfolders under userfiles (should be 0777 as per FCKeditor coding), so it does not allow uploading files in those folders. So, I created a folder userfiles at the server webroot (beyond the project root folder), and set the permission to 0777 to it, use the code for the $config setting as :
$Config['UserFilesPath'] = '/userfiles'.$file_upload_relative_path;
But, if you have no problem with write permission in the project's subfolders in your case, then you can use the previous line (commented out in the previous code segment):
$Config['UserFilesPath'] = $file_upload_relative_path.'userfiles/' ;
Mind it, you mast comment out the existing $Config['UserFilesPath'] = '/userfiles/' ; in this file by either replacing or simply commenting out if it exist in other place of the file.
2) If you choose 1) (a) (ii) or (iii) method then open
(a) fckeditor\editor\filemanager\browser\default\browser.html file.
Search for this line: var sConnUrl = GetUrlParam( 'Connector' ) ;
Put these commands after that line:
var param_project_to_fck = GetUrlParam( 'param_project_to_fck' ) ;
Now, Search for this line: sUrl += '&CurrentFolder=' + encodeURIComponent( this.CurrentFolder ) ;
Put this command after that line:
sUrl += '&param_project_to_fck=' + param_project_to_fck ;
(b) Now, open ckeditor\editor\filemanager\browser\default\frmupload.html file.
Search for this line (it should be in the SetCurrentFolder() function):
sUrl += '&CurrentFolder=' + encodeURIComponent( folderPath ) ;
Put this command after that line:
sUrl += '&param_project_to_fck='+window.parent.param_project_to_fck;
3) Now where you want to show the FCKeditor in your project, you have to put those lines first in the corresponding php file/page:
include_once(Absolute/Folder/path/for/FCKeditor/."fckeditor/fckeditor.php") ;
$oFCKeditor = new FCKeditor(Field_name_for_editor_content_area) ;
$oFCKeditor->BasePath = http_full_path_for_FCKeditor_location.'fckeditor/' ;
$oFCKeditor->Height = 400;
$oFCKeditor->Width = 600;
$oFCKeditor->Value =Your_desired_content_to_show_in_editor;
$oFCKeditor->Create() ;
a) Now, if you choose 1) (a) (ii) or (iii) method then place the following code segment before that line: $oFCKeditor->Create() ;
$oFCKeditor->Config["LinkBrowserURL"] = ($oFCKeditor->BasePath)."editor/filemanager/browser/default/browser.html?Connector=../../connectors/php/connector.php&param_project_to_fck=".base64_encode($SERVER_RELATIVEPATH);
$oFCKeditor->Config["ImageBrowserURL"] = ($oFCKeditor->BasePath)."editor/filemanager/browser/default/browser.html?Type=Image&Connector=../../connectors/php/connector.php&param_project_to_fck=".base64_encode($SERVER_RELATIVEPATH);
$oFCKeditor->Config["FlashBrowserURL"] = ($oFCKeditor->BasePath)."editor/filemanager/browser/default/browser.html?Type=Flash&Connector=../../connectors/php/connector.php&param_project_to_fck=".base64_encode($SERVER_RELATIVEPATH);
b) if you chose 1) (a) (ii) method, then in the above code code segment, just replace all the texts: base64_encode($SERVER_RELATIVEPATH) with this one: base64_encode(session_name())
And you are done.
UserFilesPath: include here the full URL for the user files directory. For example, set it to "http://www.example.com/userfiles/".