atk4 - simple apicli example - atk4

I'm trying to use Apicli to make a script that runs from command line.
This is my testing code (the script is in page/command)
include '../../atk4/loader.php';
$api=new ApiCLI('reportes');
$api->addLocation('atk4-addons',array(
'php'=>array(
'mvc',
'misc/lib',
)))->setParent($api->pathfinder->base_location);
$api->dbConnect();
$db = $this->api->db->dsql()
->table('test t')
->do_getAssoc();
The output of this is
PHP Fatal error: Uncaught exception 'ExceptionNotConfigured' with message 'You must specify $config['dsn'] in your config.php' in /var/www/ossec/atk4/lib/ApiCLI.php:238
Stack trace:
#0 /var/www/ossec/atk4/lib/ApiCLI.php(276): ApiCLI->getConfig('dsn')
#1 /var/www/ossec/page/crons/reportes.php(13): ApiCLI->dbConnect()
#2 {main}
thrown in /var/www/ossec/atk4/lib/ApiCLI.php on line 238
this do not reads config-default.php ? I've add
$config['dsn']='mysql://user:pass#localhost/test';
But it doesn't works.
Thanks all

You can solve the problem by changing current directory of cron execution. Add these lines to the beginning of the file, which is executed by cron:
$_SERVER['HTTP_HOST'] = 'site_name';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'GET';
chdir('/home/user/...path_to_directory');

looking at ApiCli.php and seen the db definition, I've passed the parameters via the method
$api->dbConnect('mysql://user:pass#localhost/test');
And now It's working fine.
Regards
Alejandro

ApiCLI reads config-default then config.php file (code from ApiCLI), so it should pick your config file. Most probably it's looking in the wrong directory, as it checks the current directory:
function getConfig($path, $default_value = undefined){
/**
* For given path such as 'dsn' or 'logger/log_dir' returns
* corresponding config value. Throws ExceptionNotConfigured if not set.
*/
if(is_null($this->config)){
$this->readConfig('config-default.php');
$this->readConfig();
}
......
}
function readConfig($file='config.php'){
$orig_file = $file;
if(is_null($this->config))$this->config=array();
$config=array();
if(strpos($file,'/')===false){
$file=getcwd().'/'.$file;
// ^^^^^^^
}
...
}

I had the same problem, but the above solution didn't work, so used setConfig like this:
$config['dsn']='mysql://root#localhost/databasename';
$api=new ApiCLI();
$api->setConfig($config);

Related

How to get the file name of the failed switch branch in libgit2?

I can call the switch branch interface normally, but when the switch branch fails, I cannot get the specific file of the current branch failure. Viewing error info only shows "one or more conflict prevents checkout", if I want to get the detailed error file name, How to get detailed error information from the callback function or return value? (also include:Merge态Reset...)
// code
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
opts.checkout_strategy = GIT_CHECKOUT_SAFE;
git_branch_lookup(&lookup, repo, branchname, GIT_BRANCH_LOCAL);
git_revparse_single(&treeish, repo, branchbane);
if(git_checkout_tree(repo, treeish, &opts)<0)
{
/*
just return "1 conflict prevents checkout",
But I want to know which files is wrong
*/
const git_error* error = giterr_last();
}
You'll need to set a notify_cb in your git_checkout_options, and set your notify_flags to include GIT_CHECKOUT_NOTIFY_CONFLICT .
Your notify callback that you provide will be invoked with the files that are changed in your working directory and preventing the checkout from occurring.
I am not so familiar with libgit2 but it looks like you'll have to solve the conflict manually. The error that you get :
1 conflict prevents checkout
Tells you that there is a file with a conflict, but you'll have to iterate through your tree to find which one and to solve it.
The status example from libgit2.org would certainly be a good starting point for you.

How can I find the path of the current gradle script?

We use some Gradle base scripts on an central point. This scripts are included with "apply from:" from a large count of scripts. This base scripts need access to files relative to the script. How can I find the location of the base scripts?
Sample for one build.gradle:
apply from: "../../gradlebase/base1.gradle"
Sample for base1.gradle
println getScriptLocation()
I'm not sure if this is considered an internal interface, but DefaultScriptHandler has a getSourceFile() method, and the current instance is accessible via the buildscript property, so you can just use buildscript.sourceFile. It's a File instance pointing at the current script
I'm still not sure if I understood the question well but You can find path of current gradle script using following piece of code:
println project.buildscript.sourceFile
It gives the full path of the script that is currently running. Is that what You're looking for?
I'm pulling it off the stack.
buildscript {
def root = file('.').toString();
// We have to seek through, since groovy/gradle introduces
// a lot of abstraction that we see in the trace as extra frames.
// Fortunately, the first frame in the build dir is always going
// to be this script.
buildscript.metaClass.__script__ = file(
Thread.currentThread().stackTrace.find { ste ->
ste.fileName?.startsWith root
}.fileName
)
// later, still in buildscript
def libDir = "${buildscript.__script__.parent}/lib"
classpath files("${libDir}/custom-plugin.jar")
}
// This is important to do if you intend to use this path outside of
// buildscript{}, since everything else is pretty asynchronous, and
// they all share the buildscript object.
def __buildscripts__ = buildscript.__script__.parent;
Compact version for those who don't like clutter:
String r = file('.').toString();
buildscript.metaClass.__script__ = file(Thread.currentThread().stackTrace*.fileName?.find { it.startsWith r })
Another solution is set a property for the location of A.gradle in your global gradle settings at: {userhome}/.gradle/gradle.properties
My current workaround is to inject the path from the calling script. This is ugly hack.
The caller script must know where the base script is located. I save this path in a property before calling:
ext.scriptPath = '../../gradlebase'
apply from: "${scriptPath}/base1.gradle"
In base1.gradle I can also access the property ${scriptPath}
You could search for this scripts in the relative path like:
if(new File(rootDir,'../path/A.gradle').exists ()){
apply from: '../path/A.gradle'
}
This solution has not been tested with 'apply from', but has been tested with settings.gradle
Gradle has a Script.file(String path) function. I solved my problem by doing
def outDir = file("out")
def releaseDir = new File(outDir, "release")
And the 'out' directory is always next to the build.gradle in which this line is called.

store all the errors occurred on eval() in PHP

Stack community.
I'm using the eval() function in PHP so my users can execute his own code in my website (Yes, i know it is a dangerous function, but that's not the point).
I want to store all the PHP errors that occur during the interpretation of the code, is there a way to fetch all of them? i want to get and register them in a table of my database.
The error_get_last gets only the last error, but i want all of them.
Help me, please. It is even possible?
General
You cannot use eval() for this, as the evaled code will run in the current context, meaning that the evaled code can overwrite all vars in your context. Beside from security considerations this could / would break functionality. Check this imaginal example:
$mode = 'execute'
// here comes a common code example, it will overwrite `$mode`
eval('
$mode = 'test';
if(....) { ...
');
// here comes your code again, will fail
switch ( $mode) {
...
}
Error Tracking
You cannot track the errors this way. One method would be to use set_error_handler() to register a custom error handler which stores the errors to db. This would work, but what if the user uses the function in it's code? Check the following examples:
set_error_handler('my_handler');
function my_handler($errno, $errstr, $errfile, $errline) {
db_save($errstr, ...);
}
eval('
$a = 1 / 0; // will trigger a warning
echo $b; // variable not defined
'
);
This would work. But problems will arise if have an evaled code like this:
eval('
restore_error_handler();
$a = 1 / 0; // will trigger a warning
echo $b; // variable not defined
'
);
Solution
A common solution to make it possible that others can execute code on your servers is:
store user code into temporary file
disable critical functions like fopen() ... in the php.ini
execute the temporary php file by php-cli and display output (and errors) to the user
if you separate stdin from stdout when calling the php-cli, you can parse the error messages and store them in a DB
According to the documentation, you just can't :
If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().
EDIT: you can't do it with eval(), but you apparently can with php_check_syntax function. You have to write the code to a file in order to check its syntax.

How to verify contents of config file before running build in TeamCity

I would like to add a step to our TeamCity configuration that checks the contents of a web.config file.
If a key value isn't found, that means someone's checked it in with the wrong value and we shouldn't proceed with the build.
(TeamCity is running on a Windows server.)
I'm able to add a command line runner that executes the appropriate FIND command, but I can't capture the output from the FIND and use it within a subsequent IF statement.
Attempts to embed the FIND within a FOR statement have been unsuccessful.
Any suggestions?
You can use PowerShell runner:
$key = 'your-key'
[xml] $config = Get-Content path\to\web.config
$value = $config.SelectSingleNode("/configuration/appSettings/add[#key='$key']/#value")
if ($value.Value -ne 'your expected value') {
exit 1
}
You could create a simple nant script using xmlPeek to check the value

CakePHP Cakemenu plugin fails after global error due to incorrect string encoding

I am using CakePHP 2.1.2 with PHP 5.3.5 and a plugin called 'Cakemenu' which normally works fine. The plugin stores menus in a db table with the menu link stored as text like
array('plugin'=>null,'controller'=>'assets','action'=>'index');
The helper in the plugin gets those values, then executes this code to convert that text to an array:
//Try to evaluate the link (if starts with array)
if (eregi('^array', $value['Menu']['link'])) {
$code = "\$parse = " . $value['Menu']['link'] . ";";
$result = eval($code);
if (is_array($parse)) {
$value['Menu']['link'] = $parse;
}
}
Everything works fine unless CakePHP is handling an error. For example if I mistype the name of a controller in the browser I should get a menu and then the missing controller message. Instead I get a page full "Parse error: syntax error, unexpected $end in..." messages pointing to the line with the eval statement. If I printout the variable that is getting eval'ed I see that it has been (incorrectly) encoded with Html entities when it normally does not.
Good string to be eval'ed:
$parse = array('plugin'=>null,'controller'=>'assets','action'=>'index');
Bad string to be eval'ed:
$parse = array('plugin'=>null,'controller'=>'Parts','action'=>'add');
To temporarily fix the problem I added two statements to just replace the offending characters
$value['Menu']['link'] = str_replace( ''','\'',$value['Menu']['link']);
$value['Menu']['link'] = str_replace( '>','>',$value['Menu']['link']);
and everything works great again. Some other pieces of information that might be helpful is that the array of data used to generate the menu is read during the beforeFilter of the app and saved in a view variable and then the menu is generated as an element in the view.
I'm thinking that the error causes CakePHP (or PHP) to skip some loading or configuration process and that causes the string to be mishandled. Any help would be appreciated, thanks
Your beforeFilter() method won't be executed on error pages. You'll have to handle your errors yourself and manually call beforeFilter(). I wrote a blog post on how to use custom error pages - pay close attention to the Controller Callbacks section.

Resources