CakePHP reading Cookie with multiple dots - cookies

I am using CakePHP to develop a website and currently struggling with cookie.
The problem is that when I write cookie with multiple dots,like,
$this->Cookie->write("Figure.1.id",$figureId);
$this->Cookie->write("Figure.1.name",$figureName);`
and then read, cakePHP doesn't return nested array but it returns,
array(
'1.id' => '82',
'1.name' => '1'
)
I expected something like
array(
(int) 1 => array(
'id'=>'82',
'name'=>'1'
)
)
Actually I didn't see the result for the first time when I read after I write them. But from second time, result was like that. Do you know what is going on?

I'm afraid it doesn't look as if multiple dots are supported. If you look at the read() method of the CookieComponent (http://api.cakephp.org/2.4/source-class-CookieComponent.html#256-289), you see this:
277: if (strpos($key, '.') !== false) {
278: $names = explode('.', $key, 2);
279: $key = $names[0];
280: }
and that explode() method is being told to explode the name of your cookie into a maximum of two parts around the dot.
You might be best serializing the data you want to store before saving and then deserializing after reading as shown here: http://abakalidis.blogspot.co.uk/2011/11/cakephp-storing-multi-dimentional.html

Related

WP_Query meta_query REGEXP

I am pretty much below beginner level for REGEX/REGEXP and have hit a blocking point in a project I am working in, where I am trying to get the ids for posts that match the search criteria , but I want to restrict the search between 2 sub-strings. I am trying to figure out is how to write the REGEXP in the meta_query:
$args = array(
'post_type'=> 'custom',
'order' => 'DESC',
'posts_per_page' => 10,
'paged' => $page,
'meta_query' => array(
array(
'key' => 'key',
'value' => "title*".$search."*_title",
'compare' => 'REGEXP',
)
),
);
And an example of the field in the DB :
a:302:{s:5:"title";s:10:"Test title";s:6:"_title";s:19:"
Unfortunately none of the combinations I tried based on documentation of SQL REGEXP won't return any values and I am trying to understand how I can pull this off and would appreciate any input.
Also would rather stick to WP_Query for now even though an SQL LIKE "%title%{$search}%_title%" works perfectly , so an alternative solution would be how to set the compare to 'LIKE' and parse it '%' since that is not possible out of the box as the % get escaped I believe.

MongoDB findOne with regex (security flaw?)

Before i insert the email into the database -> i validate the adress with
if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
{
....
}
.. but is this maybe a security flaw?
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
Schould i do this? or is it not necessary?
$emailAdress= preg_replace("/\#/", '\#', $emailAdress);
$emailAdress= preg_replace("/\-/", '\-', $emailAdress);
$emailAdress= preg_replace("/\./", '\.', $emailAdress);
if (filter_var($emailAdress, FILTER_VALIDATE_EMAIL))
Is a good way to vlaidate an email address in PHP, however, it does use regexes but so far, those have proven to be the best.
$userAccObj = $db->user->findOne( array('email' => array('$regex' => '^'.$emailAdress.'$', '$options' => 'i') ));
The only real problem with that is the . which is a special character which will effect how the regex works, but do you really need to do a regex here? You have checked it is a full email address as such you just need to check for where that exact email address exists (or better yet make a unique index on the field).
As I such I think you can take out the regex and do an exact match.

CakePHP 1.3: Way to removed a specific string from a text - PHP Function or Regular Expression

I migrated a News database into a CakePHP news site I am creating. I have a problem with displaying the text from those migrated news because in the text that was imported to DB there were HTML tags that controls the text within them.
Could anyone help me find a way to remove these texts without compromising the layout of those same news?
Basically, I would like to accomplish the following:
Create a ONE-Time Use only function that I can include in my ArticlesController
For example the function name would be function fixtext(){...}
When I call this function from lets say http://mydomain.com/articles/fixtext, all the affected rows in the Article.body column would be scanned and fixed.
The section of text I want to remove is font-size: 12pt; line-height: 115%;, which in within the <span>...</span> tag.
I had something in mind like this, but I am not sure how to implement it
function fixtext(){
$this->autoRender = 'FALSE';
$articles = $this->Article->find(
'all',
array(
'fields' => array(
'Article.body',
'Article.id'
),
'recursive' => -1
)
);
foreach($articles as $article){
// Per Dunhamzzz suggestion
$text = str_replace('font-size: 12pt; line-height: 115%;', '', $article['Article']['body']);
$this->Article->id = $article['Article']['id'];
$this->Article->saveField('Article.body', $text);
}
$this->redirect('/');
}
I am not sure how to approach this, and what is the best way.
Firstly, I would personally create a shell to accomplish this as it is a batch job and (depending on the amount of records involved) you may hit Apache's request timeout limit. Also, it's a good (fun) learning experience and the shell can be extended to perform future maintenance tasks.
Secondly, it is a bad idea to parse HTML using (greedy) regular expressions due to the fact it may be malformed. It is safer to use an HTML parser or using simple string replacements instead but, if it is a small regular string that can be pattern matched safely (ie. your not trying to remove the closing </span> tags), regular expressions can work.
Something like this (untested):
// app/vendors/shells/article.php
<?php
/**
* Maintenance tasks for Articles
*/
class Article extends Shell {
/**
* Clean HTML in articles.
*/
public function cleanHtml(){
// safety kill switch (comment before running)
$this->quit('Backup the `articles` table before running this!');
// this query will time out if you have millions of records
$articles = $this->Article->find('all', array(
'fields' => array(
'Article.name',
'Article.body',
'Article.id'
),
'recursive' => -1,
));
// loop and do stuff
foreach ($articles as $article) {
$this->out('Processing ' . $article['Article']['name'] . ' ... ');
$article['Article']['body'] = $this->_removeInlineStyles($article['Article']['body']);
$this->Article->id = $article['Article']['id'];
$saved = $this->Article->saveField('body', $article['Article']['body']);
$status = ($saved) ? 'done' : 'fail';
$this->out($status);
}
}
/**
* Removes inline CSS styles added by naughty WYSIWYG editors (or pasting from Word!)
*/
protected function _removeInlineStyles($html) {
$html = preg_replace('/ style="[^"']+"/gi', '', $html);
return $html;
}
}
You can use a simple str_replace() to cut that piece of text out.
foreach($articles as $article){
$this->Article->saveField(
'Article.body' => str_replace('font-size: 12pt; line-height: 115%;', '', $article['Article']['body']),
'Article.id' => $article['Article']['id']
);
}
This is pending the text is the same in each case, otherwise you will need something a bit more complicated with regular expressions (or maybe multiple str_replace() calls to remove each bad property).

Symfony2, Doctrine 2: getResult Object

$posts = $em->find('Application\BlogBundle\Entity\Post',1);
print_r ($posts);
Why I got it?
Barii\BlogBundle\Entity\Post Object ( [id:Barii\BlogBundle\Entity\Post:private] => 1 [title:Application\BlogBundle\Entity\Post:private] => something [body:Application\BlogBundle\Entity\Post:private] => content )
instead of a simple array like this:
array ( [id] => 1,
[title] => "something",
[body] => "content" )
I use it with Symfony 2.
You have a couple options here. As far as I know, you can't find results as arrays from entity repositories by default. Instead, you can do one of two things:
First, you could implement a toArray() method on your entity object (perhaps through a mapped superclass) that simply returns an array of properties.
Second, you could use Doctrine Query Language to pull the information that you need using the getArrayResult() method, perhaps something like this:
$query = $em->createQuery('SELECT p FROM Application\BlogBundle\Entity\Post p WHERE p.id=:pid');
$query->setParameter('tid', $postId);
$result = $query->getArrayResult(); // shortcut for $query->getResult(Query::HYDRATE_ARRAY);
More in-depth documentation on DQL can be found here.

symfony form validation clean with regex before validate with regex

I'm using Symfony 1.4 and am a little stuck regarding form validation. I have a validator like the one below:
$this->setValidator('mobile_number', new sfValidatorAnd(array(
new sfValidatorString(array('max_length' => 13)),
new sfValidatorRegex(array('pattern' => '/^07\d{9}$/'),
array('invalid' => 'Invalid mobile number.')),
)
));
That is a simple regex for matching a UK mobile phone number.
However my problem is that if someone submitted a string like this: "07 90 44 65 48 1" the regex would fail but they have given a valid number if a the string was cleaned to remove whitespace first.
My problem is that I don't know where within the symfony form framework I would accomplish this.
I need to strip everything but numbers from the user input and then use my mobile_number validator.
Any ideas would be greatly appreciated. Thanks.
You may be able to do this with a combination of standard validators, but it might well be easiest to construct your own custom validator. There is a guide to this on the symfony website: http://www.symfony-project.org/more-with-symfony/1_4/en/05-Custom-Widgets-and-Validators#chapter_05_building_a_simple_widget_and_validator
I think it should probably look something like this:
class sfValidatorMobilePhone extends sfValidatorBase
{
protected function doClean($value)
{
$value = preg_replace('/\s/','',$value);
if (
(0 !== strpos($value, '07')) ||
(13 < strlen($value)) ||
(0 !== preg_match('/[^\d]/', $value))
)
{
throw new sfValidatorError($this, 'invalid', array('value' => $value));
}
else
{
return $value;
}
}
}
Save this as lib/validator/sfValidatorMobilePhone.class.php. You could then call it as
$this->setValidator('mobile_number', new sfValidatorMobilePhone());
I don't know Symfony, so I don't know how you would go about cleaning the input. If you can do a regex-based search-and-replace somehow, you can search for /\D+/ and replace that with nothing - this will remove everything except digits from your string. Careful, it would also remove a leading + which might be relevant (?).
If you can't do a "cleaning step" before the validation, you could try validating it like this:
/^\D*07(?:\d*\d){9}\D*$/
This will match any string that contains exactly 11 numbers (and arbitrarily many non-number characters), the first two of which need to be 07.