OR condation in symfony find Query query - mongodb

Hi I am unable to use OR condation in my following Symfony findBy query.
$searchArrayTasks = array(
"name" => new \MongoRegex('/.*'.trim($_POST['keyword']).'.*/')
);
$documents = $dm->getRepository('WorkOrganisationBundle:Tasks')->findBy($searchArrayTasks)->sort($sortArray )->limit($limit)->skip($skip);
Can any one suggest please how to use OR condation in this query.Because i want to make a search basis on different parameters Like Name OR class OR Type.
Thanks Advance

This way (certainly in your Manager) is a bad practice.
Its purpose is for really dumb request.
2 things :
-Put your code in a Repository
-And code your query in sql or dql :
public function common($qb, $limit)
{
$qb->setMaxResults($limit)
->orderBy('task.id', 'DESC');
return $qb;
}
public function findByNameClassOrType($keyword, $limit)
{
$qb = $this->createQueryBuilder('task');
$qb->select('task')
->where('task.name LIKE ?', '%'.$keyword.'%')
->orWhere('task.class LIKE ?', '%'.$keyword.'%')
->orWhere('task.type LIKE ?', '%'.$keyword.'%');
$qb = $this->common($qb, $limit);
return $qb->getQuery()->getResult();
}
Use ? symbol to be sure that Doctrine escape your strings.
EDIT (mongodb) : with Mongo use addOr($expr)
$q = $doctrineOdm->createQueryBuilder('Work\OrganisationBundle\Document\Tasks');
$q->addOr($q->expr()->field('task.name')->equals($keyword));
$q->addOr($q->expr()->field('task.type')->equals($keyword));
$result = $q->getQuery()->execute();
For more informations see https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html

Related

How to write an extbase Repository-Method for Update in TYPO3?

I have written an update query in TYPO3, Now I need to change it to query-object repository method. How to change the code below?
public function updatePaymentDetails($uid, $txnID, $amt, $stats)
{
$itemUID = $uid;
$transID = $txnID;
$amountPaid = $amt;
$txStatus = $stats;
$tableName = 'tx_paypalpayment_domain_model_transactions AS tpp';
$whereCondition = 'tpp.uid=' . '"' . $itemUID . '"';
$setValues = ['transactionid' => $transID, 'amount' => $amountPaid, 'txnstatus' => $txStatus];
$result = $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tableName, $whereCondition, $setValues);
return $result;
}
I created this much in my own idea (don't know it is correct or not), What should be the remaining portion?
public function paymentUpdate($uid, $txnID, $amt, $stats) {
$query = $this->createQuery();
$query->matching(
$query->logicalAnd(
$query->equals("transactionid", $txnID),
$query->equals("amount", $amt),
$query->equals("txnstatus", $stats)
)
);
/*--- Update Code ---*/
return $query->execute();
}
Is there any way to do that?
The TYPO3/Extbase way is to first fetch your transaction from the persistence layer then apply your changes to the domain object and then update it in your repository.
Something like below in your controller action:
$transaction = $this->transactionRepository->findByIdentifier($itemUid);
$transaction->setTransactionId($transID);
$transaction->setAmount($amountPaid);
$transaction->setStatus($txStatus);
$this->transactionRepository->update($transaction);
If you wants to do a direct update instead of first fetching the record then take a look at the \TYPO3\CMS\Core\Database\Query\QueryBuilder (Only exists in newer versions of TYPO3 - 8.7 and above). In older versions of TYPO3 you could take a look at $GLOBALS['TYPO3_DB']->exec_*.

MongoDB Symfony3 pagination From To limit results using QueryBuilder

I'm using mongoDB in my symfony3 application, and I need to use setMaxResults and setFirstResult in my repository to paginate my results in my listing action. But I'm more used to use MySql as a database and I don't find how to do it in my cas.
I tried to use it as this :
$qb = $this->createQueryBuilder('DemoBundle:Entity');
$qb ->select('u');
$qb ->setMaxResults($max)
->setFirstResult($first);
But I have an error as followed :
Attempted to call an undefined method named "setMaxResults" of class
"Doctrine\ODM\MongoDB\Query\Builder
The full function is as like this :
public function search($data, $page = 0, $max = NULL, $getResult = true)
{
$qb = $this->createQueryBuilder('AresAPITournamentBundle:Tournament');
$query = isset($data['query']) && $data['query']?$data['query']:null;
$qb ->select('u');
if ($query) {
$qb
->andWhere('u.name like :query')
->setParameter('query', "%".$query."%")
;
}
if ($max) {
$qb ->setMaxResults($max)
->setFirstResult($page * $max)
;
} else {
$preparedQuery = $qb->getQuery();
}
return $getResult?$preparedQuery->execute():$preparedQuery;
}
I found the ressource in this tutorial.
How can I achieve this ?
Response was :
$qb ->limit($to)
->skip($from);

Joomla: get all users in a usergroup

I am working on a component where I want to show all users of a specific usergroup. Right now I found two solutions for this but I'm not feeling comfortable with both of them.
Solution 1
$usersID = JAccess::getUsersByGroup(3);
$users = array();
foreach($usersID as $cUserID)
{
$users[] = JFactory::getUser($cUserID);
}
This one seems to produce two database queries every time JFactory::getUser($cUserID) is called. I really don't want this.
Solution 2
function inside model
function getUsers()
{
if(!isset($this->users))
{
$groupID = 3;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$select = array( 'users.id', 'users.name');
$where = $db->quoteName('map.group_id') . ' = ' . $groupID;
$query
->select($select)
->from( $db->quoteName('#__user_usergroup_map', 'map') )
->leftJoin( $db->quoteName('#__users', 'users') . ' ON (map.user_id = users.id)' )
->where($where);
$db->setQuery($query);
$this->users = $db->loadObjectList();
}
return $this->users;
}
This one works like a charm but I feel there should be a "more Joomla! way" of doing this. I don't like working on their tables.
Right now I'm going with solution 2 but i really wonder if there is some better way to do it.

How to prevent SQL injection in PhalconPHP when using sql in model?

Let's say I am building a search that finds all the teacher and got an input where the user can put in the search term. I tried reading the phalcon documentation but I only see things like binding parameters. I read the other thread about needing prepare statements do I need that in Phalcon as well?
And my function in the model would be something like this:
public function findTeachers($q, $userId, $isUser, $page, $limit, $sort)
{
$sql = 'SELECT id FROM tags WHERE name LIKE "%' . $q . '%"';
$result = new Resultset(null, $this,
$this->getReadConnection()->query($sql, array()));
$tagResult = $result->toArray();
$tagList = array();
foreach ($tagResult as $key => $value) {
$tagList[] = $value['id'];
....
}
}
My question is for the Phalcon framework is there any settings or formats I should code for this line $sql = 'SELECT id FROM tags WHERE name LIKE "%' . $q . '%"';
And also any general recommendation for preventing SQL Injection in PhalconPHP controllers and index would be appreciated.
For reference:
My controller:
public function searchAction()
{
$this->view->disable();
$q = $this->request->get("q");
$sort = $this->request->get("sort");
$searchUserModel = new SearchUsers();
$loginUser = $this->component->user->getSessionUser();
if (!$loginUser) {
$loginUser = new stdClass;
$loginUser->id = '';
}
$page = $this->request->get("page");
$limit = 2;
if (!$page){
$page = 1;
}
$list = $searchUserModel->findTeachers($q, $loginUser->id, ($loginUser->id)?true:false, $page, $limit, $sort);
if ($list){
$list['status'] = true;
}
echo json_encode($list);
}
My Ajax:
function(cb){
$.ajax({
url: '/search/search?q=' + mapObject.q + '&sort=<?php echo $sort;?>' + '&page=' + mapObject.page,
data:{},
success: function(res) {
//console.log(res);
var result = JSON.parse(res);
if (!result.status){
return cb(null, result.list);
}else{
return cb(null, []);
}
},
error: function(xhr, ajaxOptions, thrownError) {
cb(null, []);
}
});
with q being the user's search term.
You should bind the query parameter to avoid an SQL injection. From what I can remember Phalcon can be a bit funny with putting the '%' wildcard in the conditions value so I put them in the bind.
This would be better than just filtering the query.
$tags = Tags::find([
'conditions' => 'name LIKE :name:',
'bind' => [
'name' => "%" . $q . "%"
]
])
Phalcon\Filter is helpful when interacting with the database.
In your controller you can say, remove everything except letters and numbers from $q.
$q = $this->request->get("q");
$q = $this->filter->sanitize($q, 'alphanum');
The shortest way for requests:
$q = $this->request->get('q', 'alphanum');

Correct password_hash using

I am trying to make my own user-authorization php-script to login users which where created by other php-class (not mine).
So, I try to make hash-string from word admin to make it:
$2y$10$trJyrB8x2V/hKKeKJvNF0Otz6OqFgisd0fiLc7B1ssHzSvpE0ADYu
My PHP version is 5.4.4. And I am trying to code it like this:
echo (password_hash("admin", PASSWORD_DEFAULT));
but it outputs nothing.
I found this code in the third-party php-class:
public function make($value, array $options = array())
{
$cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
if ($hash === false) {
throw new \RuntimeException("Bcrypt hashing not supported.");
}
return $hash;
}
Does anybody know how to use password_hash correctly?
Your options array probably creates a problem try this:
$hash = password_hash($value, PASSWORD_BCRYPT, ['cost' => $cost]);