Create a folder if it doesn't exist - magento-1.9

Create a folder if it doesn't exist in Magento, I don't want to use mkdir(). Is there any way to do this ? May be core_file_uploader can work out, but its throwing error.

Magento has Varien_Io_File class for quite many filesystem works.
So instead of using PHP's vanilla mkdir() function, you can use the Magento's way:
$io = new Varien_Io_File();
$io->mkdir(your_path_to_dir);
Or you can also check if the directory does not exist right before creating it
$io = new Varien_Io_File();
if (!$io->fileExists(your_path_to_dir, false)) {
$io->mkdir(your_path_to_dir);
}

Related

Error when rendering .tpl file from SQL query

I'm trying to get a result from a MySQL database and display selected values into a .tpl template file.
This is what I tried so far:
{php}
$clienthosting = $this->get_template_vars(service);//Here is where the exception is thrown
$dbid = $clienthosting['id'];
$query = mysql_query("SELECT dedicatedip FROM tblhosting WHERE id = $dbid");
$result = mysql_fetch_array($query);
$dedicatedip = $result["dedicatedip"];
$this->assign("dedicatedip", $dedicatedip);
{/php}
But it generated the following error:
Something went wrong and we couldn't process your request.
What am I doing wrong?
Thanks.
WHMCS recommends not use {php} inside tpl files, you can use hooks instead to add variables and use them in the TPL file.
But you can enable it in the settings: Setup > General Settings > Security > Allow Smarty PHP Tags.
Also, if you're running PHP 7 the mysql extension is removed, you can't use functions like mysql_query and mysql_fetch_array.
You should use Capsule and Eloquent as recommended at Interacting with the Database page

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hackā„¢ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

EF6 MySQL changing all table prefixes

I have a mysql db on a server where I've bought some space.
Now I want to add a new mvc application to my website to try out some stuff, without buggering up my existing application.
That puts me in a bit of a problem though as I only have one database available, I could just buy a new one, but I don't want to have to buy a new one every time I want to try stuff out.
So I figured, why not just pre-fix all my tables with some unique value for that application, that way I can keep the stored data separate while still using the same db.
That took me on a journey across countless articles both here on stackoverflow and other places on the web.
After about a day I stumbled upon this nugget
<!-- language: c# -->
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Types().Configure(entity => entity.ToTable("pf_" + entity.ClrType.Name));
base.OnModelCreating(modelBuilder);
}
Which does exactly what I want, as long as you either use a mssql database, or you drop your mysql database and create a new one.
However, the database I've been given is not an mssql database, and dropping it is not an option.
When, with an existing mysql db, I try to run
update-database
I get the following error
Can't find file: '.\mytestdb\dbo#002etestitems.frm' (errno: 2 - No such file or directory)
where "mytestdb" is my local db that I'm testing on, "testitems" is the current/previous tablename, .frm is ofcourse the db format, and I have no idea what this "dbo#002e" is, I tried googling it to no avail.
My stack trace can be found here.
http://pastebin.com/yF2dGkm6
Has anyone been in a similar situation, or has ideas as to how I can make it work? =)
dbo#002e stands for "dbo.", looking at your migration file you should discover rows like this one:
RenameTable(name: "dbo.Table", newName: "pf_Table");
Despite everything it's ok with CreateTable with table names prefixed by "dbo.", RenameTable origin the whole "dbo.Name" to be looked for and so the error comes.
My suggestion is to remove manually the "dbo." on the RenameTable's "name:" parameter.
EDIT:
After fixed the problem editing the migration file the best solution is to add this to the Configuration constructor:
public Configuration()
{
AutomaticMigrationsEnabled = false;
....
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
CodeGenerator = new MySql.Data.Entity.MySqlMigrationCodeGenerator();
....
}
It should work since the .Net Connector version 6.7.4 on.

Couchbase lite rename database

How can I rename an existing couchbase lite database (I'd like to avoid creating a new db and having to copy the contents over if possible). Is this the same as replicate to a database locally that has the same name?
Since you map your local database to a remote couchbase bucket using the CBLReplication classes, I can't see any reason why renaming the database shouldn't work.
Just make sure you close your CBLDatabase first:
database.close()
And use the NSFileManager to move the database mydb.cblite from within the CBLManager.sharedInstance().directory as you like:
let databaseManager = CBLManager.sharedInstance()
let fileManager = NSFileManager.defaultManager()
let sourceName = "\(database.name).cblite"
let targetName = "my-new-name.cblite"
if let sourcePath = NSURL(databaseManager.directory,isDirectory:true).URLbyAppendingURLComponent(sourceName).path,
let targetPath = NSURL(databaseManager.directory,isDirectory:true).URLbyAppendingURLComponent(targetName).path{
fileManager.moveItemAtPath(sourcePath,atPath: targetPath)
}
And afterwards reopen the connection to the database with the same CBLReplication settings as before:
let database = databaseManager.databaseNamed("my-new-name")
Please keep in mind you might also move the mydb attachments directory first. And after reopening the connection making sure all of your code is using the new reference for querying etc.
PS: The code used here is written from memory, so it may not work copied 1:1 - but you should get the idea.

Get Redmine custom field value to a file

I'm trying to create a text file that contains the value of a custom field I added on redmine. I tried to get it from an SQL query in the create method of the project_controller.rb (at line 80 on redmine 1.2.0) as follows :
sql = Mysql.new('localhost','root','pass','bitnami_redmine')
rq = sql.query("SELECT value
FROM custom_values
INNER JOIN projects
ON custom_values.customized_id=projects.id
WHERE custom_values.custom_field_id=7
AND projects.name='#{#project.name}'")
rq.each_hash { |h|
File.open('pleasework.txt', 'w') { |myfile|
myfile.write(h['value'])
}
}
sql.close
This works fine if I test it in a separate file (with an existing project name instead of #project.name) so it may be a syntax issue but I can't find what it is. I'd also be glad to hear any other solution to get that value.
Thanks !
(there's a very similar post here but none of the solutions actually worked)
First, you could use Project.connection.query instead of your own Mysql instance. Second, I would try to log the SQL RAILS_DEFAULT_LOGGER.info "SELECT ..." and check if it's ok... And the third, I would use identifier instead of name.
I ended up simply using params["project"]["custom_field_values"]["x"] where x is the custom field's id. I still don't know why the sql query didn't work but well, this is much simpler and faster.