Get Symfony URL relative to the index file - symfony1

I have a symfony project which, because of DNS issues, is http://<project-name>/ locally, but it needs to be http://<qa-host-name>/<project-name>;/ when hosted in a more QA level environment but it may be http://<domain-name>/ for production (so, I need this to work for both). Now, the images folder will always be relative to the <project-name> directory, so locally it will be http://<project-name>/my-smilie.png and on QA it will be http://<qa-host-name>/<project-name>/my-smilie.png
Since everything is relative to the URL of the index.php, I thought that Symfony would have something to create dynamic URLs which work even if the context is different so that my template.php could have something like
<?php echo image_url("my-smilie.png");
/*see below for potential implementation*/?>
and it would output http://<project-name>/my-smilie.png, http://<qa-host-name>/<project-name>/my-smilie.png, or http://<domain-name>/my-smilie.png. (Relative URLs are fine, but absolute would be better).
Below is an example of what I am looking for, but I feel like I am trying to re-invent the wheel and that Symfony has already accomplished this.
function image_url($img)
{
return get_base_url() . '/images/' . $img;
}
function get_base_url()
{
$par = dirname( $_SERVER[ 'SCRIPT_NAME' ] );
if($par == "/") $par = "";
return $par;
}

try public_path('images/smilie.jpg') function
public_path() manual

I just came across a situation where the public_path helper does not work terribly well, but there is an alternative:
// this populates $host with absolue URL of the parent directory
// of the Symfony script
$host = $request->isSecure()? 'http://':'https://';
$host .= $request->getHost() . $request->getRelativeUrlRoot();

Related

Using label path to check if file location exists

Is there an easy way to get hold of a path object so I can check if a given label path exists. Say for example if path.exists("#external_project_name//:filethatmightexist.txt"):. I can see that the repository context has this. But I need to have a wrapping repository rule. Is it possible to do this in a macro or Skylark native call instead?
Even with a repository_rule, I had a lot of trouble with this due to what you already pointed out:
if you create a Label with a path that doesn't exist, it will cause the build to fail
But if you're willing to do a repository rule, here's a possible solution...
In this example, my rule allows specification of a default configuration if a config file is not present. The configuration can be checked into .gitignore and overridden for individual developers, but work out of the box for most cases.
I think I understand why the ctx.actions have sibling arguments now, same idea here. The trick is config_file_location is a true label, and then config_file is a string attribute. I chose BUILD arbitrarily, but since all workspaces have a top level BUILD that's public seemed legit-ish.
WORKSPACE Definition
...
workspace(name="E02_mysql_database")
json_datasource_configuration(name="E02_datasources",
config_file_location="#E02_mysql_database//:BUILD",
config_file="database.json")
The definition for json_datasource_configuration looks like this:
json_datasource_configuration = repository_rule(
attrs = {
"config_file_location": attr.label(
doc="""
Path relative to the repository root for a datasource config file.
"""),
"config_file": attr.string(
doc="""
Config file, maybe absent
"""),
"default_config": attr.string(
# better way to do this?
default="None",
doc = """
If no config is at the path, then this will be the default config.
Should look something like:
{
"datasource_name": {
"host": "<host>"
"port": <port>
"password": "<password>"
"username": "<username>"
"jdbc_connection_string": "<optional>"
}
}
There can be more than datasource configured... maybe, eventually.
""",
),
},
local = True,
implementation = _json_config_impl,
)
Then in the rule I can test for the file existence, and if not present, do other logic.
def _json_config_impl(ctx):
"""
Allows you to specify a file on disk to use for data connection.
If you pass a default
"""
config_path = ctx.path(ctx.attr.config_file_location).dirname.get_child(ctx.attr.config_file)
config = ""
if config_path.exists:
config = ctx.read(config_path)
elif ctx.attr.default_config == "None":
fail("Could not find config at %s, you must supply a default_config if this is intentional" % ctx.attr.config_file)
else:
config = ctx.attr.default_config
...
probably too late to help, but your question is the only thing I found referencing this goal. If someone knows a better way I am looking for other options. It's complicated to explain to other developers why the rule has to work the way it does.
Also note, if you change the config file, you have to clean to get the workspace to re-read the config. I haven't been able to figure out any way to fix that. glob() does not work in the workspace.

How do I derive physical path of a relative directory inside Config.groovy?

I am trying to set up Weceem using the source from GitHub. It requires a physical path definition for the uploads directory, and for a directory for appears to be used for writing searchable indexes. The default setting for uploads is:
weceem.upload.dir = 'file:/var/www/weceem.org/uploads/'
I would like to define those using relative paths like WEB-INF/resources/uploads. I tried a methodology I have used previously for accessing directories with relative path like this:
File uploadDirectory = ApplicationHolder.application.parentContext.getResource("WEB-INF/resources/uploads").file
def absoluteUploadDirectory = uploadDirectory.absolutePath
weceem.upload.dir = 'file:'+absoluteUploadDirectory
However, 'parentContext' under ApplicationHolder.application is NULL. Can anyone offer a solution to this that would allow me to use relative paths?
look at your Config.groovy you should have (maybe it is commented)
// locations to search for config files that get merged into the main config
// config files can either be Java properties files or ConfigSlurper scripts
// "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy",
grails.config.locations = [
"file:${userHome}/.grails/${appName}-config.properties",
"file:${userHome}/.grails/${appName}-config.groovy"
]
Create Conig file in deployment server
"${userHome}/.grails/${appName}-config.properties"
And define your prop (even not relative path) in that config file.
To add to Aram Arabyan's response, which is correct, but lacks an explanation:
Grails apps don't have a "local" directory, like a PHP app would have. They should be (for production) deployed in a servlet container. The location of that content is should not be considered writable, as it can get wiped out on the next deployment.
In short: think of your deployed application as a compiled binary.
Instead, choose a specific location somewhere on your server for the uploads to live, preferably outside the web server's path, so they can't be accessed directly. That's why Weceem defaults to a custom folder under /var/www/weceem.org/.
If you configure a path using the externalized configuration technique, you can then have a path specific to the server, and include a different path on your development machine.
In both cases, however, you should use absolute paths, or at least paths relative to known directories.
i.e.
String base = System.properties['base.dir']
println "config: ${base}/web-app/config/HookConfig.grooy"
String str = new File("${base}/web-app/config/HookConfig.groovy").text
return new ConfigSlurper().parse(str)
or
def grailsApplication
private getConfig() {
String str = grailsApplication.parentContext.getResource("config/HookConfig.groovy").file.text
return new ConfigSlurper().parse(str)
}

load_plugin_textdomain not working

Hey i'm trying to localize a plugin called Donate Plus ( which locallized technicly).
the plugin came with en_CA and de_DE files, i've tried creating a he_IL file without success.
So i've tried with the de files came with the plugin but didn't work.
I've set the WPLANG in wp-config.php to de_DE yet that dosen't change the code.
this is the setting code :
load_plugin_textdomain( 'dplus', '/wp-content/plugins/donate-plus' );
And i did check that all the string are set to be localized.
Anyone has a clue?
I just was with a similar isue, did you try to rename your files from de_DE.po and de_DE.mo to name-of-plugin-de_DE.mo and name-of-plugin-de_DE.po (changing name-of-plugin with yours, of course)?
dplus-de_DE.mo and dplus-de_DE.po It must work ;)
load_plugin_textdomain takes three parameters.
In your case it would be something like this (assuming the .po and .mo files are located in a subdir called 'languages')
load_plugin_textdomain( 'dplus', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
I checked the source of DonatePlus Plugin and I found that the Plugin is doing localization wrongly.
The load_plugin_textdomain() call is made inside the DonatePlus classes constructor. But it should be present inside the 'init' hook. Trying adding the following code (which is at the of the file) inside the init function.
if( class_exists('DonatePlus') )
$donateplus = new DonatePlus();
Where are all the .po and .mo files stored? Are they inside the /wp-content/plugins/donate-plus folder itself? If not then change the path or move the files.
I had a similar issue where I was loading the translation files with the load_plugin_textdomain function from within a service class using PSR-4. This meant that the dirname( plugin_basename( __FILE__ ) ) string returned the wrong path.
The correct path is the relative path your-plugin/languages (assuming you are loading the translation files from the /languages directory).
Absolute paths such as /var/www/html/wp-content/plugins/my-plugin/languages won't work.
My plugins file structure looks something like this:
- my-plugin
- assets
- languages
- services
- Api
- Base
Translation.php
- ...
Plugin.php
- vendor
- views
composer.json
composer.lock
index.php
my-plugin.php
uninstall.php
Since my Translation service is placed in the /services/Base/ directory, this worked for me:
$root = plugin_basename(dirname(__FILE__, 3));
load_plugin_textdomain( 'my-plugin', false, "$root/languages/");
Also, I used no action hook at all instead of init or plugins_loaded and fired the load_plugin_textdomain function at the beginning of the plugin, since the hooks don't fire early enough for the admin menu and action links to get translated.
Use:
load_textdomain( TEXT_DOMAIN , WP_PLUGIN_DIR .'/'.dirname( plugin_basename( FILE ) ) . '/languages/'. get_locale() .'.mo' );

FitNesse SliM - root page references to .class files MANY different projects

I am developing some fixtures in Java to use with fitnesse slim. I run into problems (EXCEPTION:java.lang.NoClassDefFoundError:) when I must update my root page with paths like this:
!define TEST_SYSTEM {slim}
!path: C:\WORKSPACE\Projects\iperoom_67_workspace\acceptance_test_project\bin
!path: C:\WORKSPACE\Projects\iperoom_67_workspace\iperoom\BASE\common_util\target\classes
!path C:\WORKSPACE\Projects\iperoom_67_workspace\iperoom\BASE\dfc_util\target\classes
Where a class in i.e. ...BASE\dfc_util\target\classes; has the following imports:
import no.joint.iperoom.test.AbstractDfcTest;
code
.
.
.
Which gives the complete path in my local C drive workspace:
C:\WORKSPACE\Projects\iperoom_67_workspace\iperoom\BASE\dfc_util\target\classes\no\joint\iperoom\test
My question is could I say, on the root page:
classpath: C:\WORKSPACE\Projects\iperoom_67_workspace\iperoom\BASE*; as in take in all the .class files from here and up. Something more general?
and possibly import several pats to .class files on the fitnesse test page:
|import|
|dfc_util.target.classes.no.joint.iperoom.test.AbstractDfcTest|
Or is there any other and better way to solve this problem with a growing number of '!paths' in my root page due to calling one .class from another .class from antoher .class and so forth.
Or maybe my fixture code is not good enough:
public class SessionHelperTest /extends AbstractDfcTest/{
public boolean testNewSession() {
System.out.println("Hello Joint");
IDfSession session = SessionRegistry.getSuperUserSession("eRoomPCI_v_1_1");
try {
String si = session.getSessionId();
System.out.println("The sessionId is:\n" + si);
return true;
} catch (DfException e) {
e.printStackTrace();
return false;
}
}
}
Cheers
Magnus
I don't think path is going to work the way you want it to. If you define it at too low a level, I'm pretty sure it won't find your classes.
The !path works fine when you do any of the following:
This will get all of the class files under build/classes if it is under the folder fitnesse starts in:
!path build/classes
This will handle multiple jar files:
!path lib/*.jar
Important to note is that you can leverage environment variables for this. Assuming you have an environment variable called WORKSPACE defined that points to the base of your project, you can do this:
!path ${WORKSPACE}/acceptance_test_project/bin
!path ${WORKSPACE}/acceptance_test_project/common_util/target/classes
!path ${WORKSPACE}/acceptance_test_project/dfc_util/target/classes
The reality is that if your files are scattered across multiple folders, you will have to use multiple entries. If just to make sure you can control the order the path is processed. If you only do this on your FrontPage, then everything below it will inherit the same path. Then you only have to manage it in one location. So while the list might be longer than you prefer, the maintenance is managed.

system.io.directorynotfound -> But it works in Console

My files are referenced like so (it's all relative):
// WHERE YOU KEEP THE PAGE TITLE XML
public static string myPageTitleXML = "xml/pagetitles.xml";
and
using (StreamReader r = new StreamReader(myPageTitleXML))
{ //etc.. . .etc....etc..
}
I get system.io.directorynotfound, and "this problem needs to be shut down", when I double click the executable. But running it from the console works like a charm. What's wrong here?
I played around with attempting to set Environment.CurrentDirectory but couldn't get anything to work. Why should I have to do that anyway? It defeats the purpose of a relative path no?
responding.. .
"application" does not exist in the current context, i'll keep trying what people have mentioned, this is not a windows.form
testing
Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), myPageTitleXML); gives error URI formats are not supported, as does Path.GetFullPath(). Server.MapPath results in an error as well, this is currently offline
Well assuming this directory is somewhere under the directory in which your code is executing, it sounds like you can use ..
Application.ExecutablePath()
or
Application.StartUpPath()
.. to get an idea as to what your application is seeing when it goes in search of an 'xml' directory with the 'pagetitles.xml' file in it.
If the directory returned by one of these methods does not point where you thought it did, you'll need to move the location of your application or the location of this folder so that it is within the same directory as the app.
Hope this gets you on the right path.
So, when you run it from double clicking the executable, is there a file named pagetitles.xml in a folder named xml, where xml is a folder in the same location as the executable?
It's certainly possible to use relative paths like this, but I wouldn't really recommend it. Instead, maybe use something like:
string fileToOpen = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), myPageTitleXML);
using (StreamReader r = new StreamReader(fileToOpen))
{
//etc.. . .etc....etc..
}
Is this ASP.NET code? If so then you probably need to do MapPath("xml/pagetitles.xml")

Resources