how to allow transform in htmlpurifier - php

********* Updated question **************
So I have tried to implement my own AttrDef to HTMLPurifier but it doesn't "take", and I can't debug using die() either.
Here's what I have:
I created Transform.php in the HTMLPurifier/AttrDef/CSS/ directory. The only contents so far is this (I'm only trying to hook it in for now, I will add validating logics once I see that it is in the loop and thus can test it):
<?php
/**
* Validates Transform as defined by CSS.
*/
class HTMLPurifier_AttrDef_CSS_Transform extends HTMLPurifier_AttrDef
{
//basing this off of the color definition so the var is $color for now, may change it to $transform later
public function validate($color, $config, $context) {
return $color;
}
}
I added my file to library/HTMLPurifier.includes.php like this:
require 'HTMLPurifier/AttrDef/CSS/Transform.php';
and to the library/HTMLPurifier.safe-includes.php
require_once $__dir . '/HTMLPurifier/AttrDef/CSS/Transform.php';
(not sure about the difference between these two include files above but all AttrDef files seemed to be in both so I added my file to both as well).
Then I try to make use of this new definition by adding this to library/HTMLPurifier/CSSDefinition.php:
// transform
$this->info['transform'] = new HTMLPurifier_AttrDef_CSS_Transform();
It is as if all of my additions were never made, and I can't debug it by putting a die() in my own file either, nothing happens.
So any advice on where I went wrong or how I can debug this is very much appreciated.
*********** addition *******
I also tried a simple bypass by applying the Color-AttrDef to any transform property, in the CSSDefinition.php:
$this->info['transform'] = new HTMLPurifier_AttrDef_CSS_Color();
And I hacked the original Color definition like this:
//TODO: testing ways to bypass
if (strpos($color, 'rotate(') !== false) {
return $color;
}
Not working. Please advice on what I am missing.

You'll need to define your own AttrDef which knows how to parse and validate such definitions. Color should serve as a decent model, since the rgb syntax is similar to matrix.

Related

Configuration File for Driving Selenium

I have about 500 possible paths to a particular page, and I need to test all of them. Each path to the that page looks similar to this (using PHP web driver; usually has about 10 steps):
// Navigate to form
$driver->get('http://www.domain.com');
$driver->get($driver->findElement(WebDriverBy::xpath("//a[contains(text(),'Foo 1')]"))->getAttribute('href'));
$driver->findElement(WebDriverBy::xpath("//div[#class='countryHeader']//a[contains(text(), 'Bar 1')]"))->click();
$driver->findElement(WebDriverBy::xpath("//form[#name='formDisclaimer']//input[contains(#class, 'button')]"))->click();
I don't want to have to write code for all the steps for all possible paths to the page. I do, however, have all the pertinent details of the steps (e.g. the XPath, the string the node may contain, etc.) in a database.
Is there a way for me to "dynamically" produce some sort of configuration file (either in XML or JSON) that I can feed to the driver as a set of instructions for it to follow?
A long time back at one of my project I had a similar requirement. I tried to create a Robot (or someone may call Web Crawler). As I started navigating through the pages I started maintaining the navigation paths in spreadsheet, so I don't have to click on the paths manually. Once I have the paths, next time whenever a Path changes I will be notified and if it is a valid change then make that change in s/s or raise it as a bug.
As you said you have all relevant details in the database then you just can simply read it and in a foreach loop pass to selenium driver.
or if you don't want to have a reference to the database in your test, just dump data to PHP array and add to your test class.
You just need to write a logic to transform your sql data into test. Don't need to write every test manually.
I don't know which testing framework you are using, but you can execute many tests from a single test for example in PHPUnit that would be something like:
class My_PathsTest extends PHPUnit_Framework_TestCase
{
public function setUp() {
// setup $this->tests here
}
public function testAll() {
// $this->tests would contain info about paths taken from database.
$failures = array();
foreach($this->tests as $paths_set) {
try {
/**
* $driver->get($paths_set['start_point']);
* foreach ($paths_set['paths'] as $path ) {
* $driver->findElement(WebDriverBy::xpath($path));
* }
*
* Important!!!
* If you didn't find something you expected
* just throw the PHPUnit_Framework_ExpectationFailedException exception
* throw new PHPUnit_Framework_ExpectationFailedException('Element missing add some info here about which is missing etc..');
*/
}
catch(PHPUnit_Framework_ExpectationFailedException $e) {
$failures[] = $e->getMessage();
}
}
if (!empty($failures)) {
throw new PHPUnit_Framework_ExpectationFailedException(count($failures) . " assertions failed:\n\t" . implode("\n\t", $failures));
}
}
}
best is to get data from db with odbc as a list (array) xpath locators and then loop over it.
If you don't have a direct access to the db, export the query results as a .csv file (MS db has an option save as, not sure about the others) and then read the file and loop over the array

How to call same name dynamic function from dynamically created files based database inputs

I'm creating a system that would work on call same function names from dynamic created php files.
The file structure is as bellow :
/root/caller.php //{uses pthreads & process multi simultaniously}
/root/rules/mode1.php
/root/rules/mode2.php
/root/rules/mode{n}.php // goes till n , so unlimited
Caller.php reads data from db and calls mode{n} accordingly. Sometimes there are chances to call multiple of rules at a point of time.
Sample of caller.php {written on OOPS}
foreach ($result as $row){
$mode = $rom->modeNum;
include 'rules/mode' . $mode . '.php';
call_fuction_inside_mode();
}
Sample of mode{n}.php {procedural programming}
function call_fuction_inside_mode(){
//..Custom function depending upon mode{n}
}
This won't function properly, because caller.php would include same function name again and again.
Please note :
I do not want to play with rename function with pecl, as all includes would be required
I have tried calling mode{n}.php by introducing another file "proxy.php"
And proxy.php works in below pattern
caller.php -> curl 127.0.0.1/proxy.php?mode={n} -> calls as defined
But this is not efficient way to do this when dealing with >500 requests per sec on micro server. I noticed many requests are killed and there's problem with order number. My target is to achieve this with least memory usage and 100% utilization of provided cpu resources.
I'm confused and so curious to find the solution I should be dealing here.
create an interface called Mode in Mode.php:
interface Mode{
public static function AcivateMode();
}
and include Mode.php into your code, then change the code in your mode{n}.php to encapsulate your function into classes that implements the interface Mode like so:
class Mode1 implements Mode {
public static function AcivateMode() {
//..Custom function depending upon mode{n}
}
}
then modify your foreach to activate the modes like:
foreach ($result as $row){
$mode = $rom->modeNum;
include 'rules/mode' . $mode . '.php';
call_user_func("Mode$mode::AcivateMode");
}
OR
you can use the namespaces approach by adding the namespace to each of your mode{n}.php files like so:
mode1.php
namespace Mode1;
function call_fuction_inside_mode(){....}
and calling the function using:
call_user_func("Mode$mode\call_fuction_inside_mode");
that worked for me, hope it's gonna be helpful :)
Regards,

How to Turn off Debugging Logs with Monolog

I'm using Monolog in a project, it's not Symfony, just my own application that uses the stand-alone Monolog composer package.
What I'd like to do is programmatically turn off debugging logs. I'm writing to a log file and I'm using the Monolog::StreamHandler. I'm controlling whether the application is in debug mode or not with a Configuration class that gets the debug value from a configuration file. So when someone changes that value to debugging is false, debug logging should turn off.
I felt like the easiest way to do this would be to extend StreamHandler and override StreamHandler's write method like this.
class DurpLogger extends StreamHandler {
protected function write(array $record) {
if ($this->getLevel() == Durp::Debug && !Configuration::debug()) {
return;
}
parent::write($record);
}
}
So if a log request comes in and the log level for the handler is set to DEBUG and the application's Configuration::debug() is FALSE then just return without writing the log message. Otherwise, StreamHandler will do its thing.
I'm wondering if this is the best way to use Monolog or if there's perhaps a cleaner way to do this.
I envision there being a handler in my application for DEBUG, INFO, ERROR and whatever levels I might need for my application. Perhaps it makes sense to not rely on a Configuration::debug() that can only be TRUE or FALSE, but rather a Configuration::logLevel() that will allow me to more granularly control logging output.
But even still, does extending StreamHandler make the most sense when controlling Monolog at the application level?
UPDATE
Now, I'm thinking something like this, that uses level rather than just boolean debug.
class DurpLogger extends StreamHandler {
public function __construct() {
parent::__construct(Configuration::logFile(), Configuration::logLevel());
}
protected function write(array $record) {
if (!($this->getLevel() >= Configuration::logLevel())) {
return;
}
parent::write($record);
}
}
Then I'd use it in the application like this.
class Durp {
private $logger;
public function __construct() {
$this->logger = new Logger('durp-service');
$this->logger->pushHandler(new DurpLogger());
$this->logger->addDebug('Debugging enabled');
$this->logger->addInfo('Starting Durp');
}
}
I figured the StreamHandler handles the file writing stuff, so that's why I'm extending it. And if I turn up the log level in Configuration to Logger::INFO, the "Debugging enabled" message doesn't get logged.
Open to suggestions to make this better.
A common alternative would be to use the NullHandler instead of the StreamHandler.
Maybe switch between them depending on your condition like follows:
if (!Configuration::debug()) {
$logger->pushHandler(new \Monolog\Handler\NullHandler());
}
I would like to give you an example that is more adapted to your usage,
but I need to see some code in order to know how you use it.
Update
For the question about default format, the empty [] at end represent the extra data that can be added with log entries.
From #Seldaek (Monolog's owner) :
The default format of the LineFormatter is:
"[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n". the username/age is the context, and extra that is typically empty results in this empty array [].
If you use processors to attach data to log records they typically write it to the extra key to avoid conflicts with context info. If it really is an issue for you you can change the default format and omit %extra%.
Edit: As of Monolog 1.11 the LineFormatter has a $ignoreEmptyContextAndExtra parameter in the constructor that lets you remove these, so you can use this:
// the last "true" here tells it to remove empty []'s
$formatter = new LineFormatter(null, null, false, true);
$handler->setFormatter($formatter);
See How not to show last bracket in a monolog log line? and Symfony2 : use Processors while logging in different files about the processors which #Seldaek is talking about.

Testing method with no output

I have the following method I want to test:
class SomeObject {
public function actionFromSomeController() {
$obj = new OtherObject();
$obj -> setAttributes();
$obj -> doAction();
}
}
class OtherObject {
private $_attr;
public function setAttributes() {
$this -> _attr = 'something';
Database :: execute('INSERT INTO table VALUES (' . $this -> _attr . ')');
$fileObj = new FileObj();
$content = $fileObj -> getSomeFileContent();
// do something else
}
public function doAction() {
echo $this -> _attr;
}
}
Now I want to test this method, its output depends on database content and one file on the server. It does a lot of things on the way, and the output is just one ID and success => 1.
How should I test it properly?
Some ideas on how to test small code pieces like this:
Generate test-data and pass it to your methods (also, fake database return data or file contents)
Use echo / var_dump() / die() to check property and variable content at different positions in your methods
Also use these commands to check whether execution reaches a certain point (for example to see whether a function got called or not)
If something doesn't work as expected without an error message: Check line by line with the above methods until you find the problem
Consider using interfaces and dependency injection if your code gets bigger - this is a bit over-the-top for this amount of code, but can be a tremendous time-saver when your application becomes big
Testing is never an automatic process and you will always have to think about what makes sense to do and what not. These things to do are never magic but basic PHP.
You should consider letting your scripts throw errors/exceptions if something goes wrong. Writing "silent" applications is almost never good since you can, if you really need a silent execution for production environments, just turn off error reporting and have the same effect. Many PHP functions return something special on failure and/or success and you can check for this. Database handlers do so, too. Do yourself a favor and use these return values!

unrequire a file once it's been required in PHP

Suppose I do
require('lol.php');
whereby lol.php contains the following function declaration
function lolfunc(){
}
is it possible to "unrequire" lol.php such that I can then require another file
require('lol2.php');
whereby lol2.php contains a function with the same name previously declared in lol.php:
function lolfunc(){
echo "this is lol2 biyotch";
}
and have lolfunc() be the one declared in lol2.php? eg if I call lolfunc() it'll echo "this is lol2 biyotch"??
My answer: don't do that.
Try to work with the original author to include the functions you need into a patched version of the old code and then use that patched version everywhere.
If you can't do that, find out how big a job it would actually be to update all the code to new version. Start with white-box analysis: see what's changed in terms of interfaces, data structures et al. Then examine the calling code to see whether the caller cares about any of the things that have changed.
If you can't even do that, use namespacing or some other form of wrapping so that you can include both libs. However, make sure any initialisaton or setup is done on both libs!
What you should do, is to include the required (sets) of files based on conditional clauses, instead of trying to "unrequire".
So:
if($flag_use_oldver)
{
include("oldver.php");
}
else
{
include("newver.php");
}
If you want a more sophisticated solution, of course you could try to have a wrapper class hierarchy that will extend/override as required, but I think that is a bit over-engineering for a pretty straightforward problem statement.

Categories