Symfony Zend Lucene Search Multiple Tables - zend-framework

I have a Symfony project and I used Zend Lucene Search framework to integrate a search on the site. It works beautifully but it's limited to searching 1 table.
I need my users to be able to search the whole site (8 select tables) and return the results all together. Each table has the same fields indexed. This is the code that specifies the table and calls the query.
Is there a way to make it look through all 8 tables for results?
public function getForLuceneQuery($query)
{
$hits = self::getLuceneIndex()->find($query);
$pks = array();
foreach ($hits as $hit)
{
$pks[] = $hit->pk;
}
if (empty($pks))
{
return array();
}
$alltables = Doctrine_Core::getTable('Car');
$q = $alltables->createQuery('j')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21);
return $q->execute();
}
To give a bit of background on the 8 tables, they are all basically similar. They all have title, make, model, etc so I need to run a single query on all of them and return all results (regardless of which table it is in) in Ascending order. The Doctrine_core::getTable command doesn't seem to like multiple tables or even arrays (unless I'm not doing it right). Thanks!
UPDATE (WORKING):
Here is the updated code. This is what I have in the SearchTable.class.php file:
public function getForLuceneQuery($query)
{
// sort search result by end time
$hits = self::getLuceneIndex()->find(
$query, 'endtime', SORT_NUMERIC, SORT_ASC
);
$result = array(
'index' => $hits,
'database' => array(),
);
// group search result by class
foreach ($hits as $hit)
{
if (!isset($result['database'][$hit->class]))
{
$result['database'][$hit->class] = array();
}
$result['database'][$hit->class][] = $hit->pk;
}
// replace primary keys with real results
foreach ($result['database'] as $class => $pks)
{
$result['database'][$class] = Doctrine_Query::create()
// important to INDEXBY the same field as $hit->pk
->from($class . ' j INDEXBY j.token')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21)
->execute();
}
return $result;
}
Here is what I have in the actions.class.php file for the Search Module:
public function executeIndex(sfWebRequest $request)
{
$this->forwardUnless($query = $request->getParameter('query'), 'home', 'index');
$this->results = Doctrine_Core::getTable('Search')
->getForLuceneQuery($query);
}
And finally this is my template file indexSuccess.php I have simplified it so it's easier to understand. My indexSuccess.php is more complicated but now that I can call the values, I can customize it further.
<div class="product_list"
<ul>
<?php foreach ($results['index'] as $hit): ?>
<li class="item">
<?php if (isset($results['database'][$hit->class][$hit->pk])) ?>
<span class="title">
<?php echo $results['database'][$hit->class][$hit->pk]->getTitle() ?>
</span>
</li>
<?php endforeach ?>
</ul>
</div>
This works beautifully. I was able to customize it by calling each of the fields in the search results and it works perfect. I added an item to each of the tables with the same title and the search result pulled them all. Thank you so much!

OK. I'll try to give you some hint, with code :)
First of all you should add these fields to the index:
$doc->addField(Zend_Search_Lucene_Field::Keyword('class', get_class($record)));
$doc->addField(Zend_Search_Lucene_Field::UnIndexed('endtime', strtotime($record->get('endtime'))));
Than you should use these new fields:
public function getForLuceneQuery($query)
{
// sort search result by end time
$hits = self::getLuceneIndex()->find(
$query, 'endtime', SORT_NUMERIC, SORT_ASC
);
$result = array(
'index' => $hits,
'database' => array(),
);
// group search result by class
foreach ($hits as $hit)
{
if (!isset($result['database'][$hit->class]))
{
$result['database'][$hit->class] = array();
}
$result['database'][$hit->class][] = $hit->pk;
}
// replace primary keys with real results
foreach ($result['database'] as $class => $pks)
{
$result['database'][$class] = Doctrine_Query::create()
// important to INDEXBY the same field as $hit->pk
->from($class . ' j INDEXBY j.token')
->whereIn('j.token', $pks)
->orderBy('j.endtime ASC')
->andwhere('j.endtime > ?', date('Y-m-d H:i:s', time()))
->andWhere('j.activated = ?', '1')
->limit(21)
->execute();
// if you want different query per table
// you should call a function which executes the query
//
// if (!method_exists($table = Doctrine_Core::getTable($class), 'getLuceneSearchResult'))
// {
// throw new RuntimeException(sprintf('"%s::%s" have to be exists to get the search results.', get_class($table), 'getLuceneSearchResult'));
// }
//
// $results[$class] = call_user_func(array($table, 'getLuceneSearchResult'), $pks);
}
return $result;
}
After that in the template you should iterate over $result['index'] and display results from $result['database']
foreach ($result['index'] as $hit)
{
if (isset($result['database'][$hit->class][$hit->pk]))
{
echo $result['database'][$hit->class][$hit->pk];
}
}
And there are same alternate (maybe better) solutions that I can think of:
Alternate solution #1:
You can store data in the index and this data will be accessible in the search result. If you not need too much data when displaying the results and can update the index frequently I think this is a good option. This way you can use pagination and no SQL queries needed at all.
$doc->addField(Zend_Search_Lucene_Field::Text('title', $content->get('title')));
...
$hit->title;
Alternate solution #2:
As you wrote, your tables are very similar, so you maybe could use column aggregation inheritance. In this way all data stored in one table so you can query them all together and can order and paginate as you want.

Related

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');

Array display issue

I have a database table ("buildings") in MySQL consisting of 3 columns:
Name
Place
Number
I have created a dropdown list in my view page which contains the names of the buildings and also a textarea.
Now, depending on which name the user selects, the textarea should be populated with the respective place and number of the name of the building. I’m able to get the result but I want the output to be more readable. Right now, the format of the output is as:
Array
(
[0] => Array
(
[Number] => 14
[Place] => Cambodia
)
)
Is there anyway I could get the output to be as simple as:
Number : 14
Place: Cambodia
Her's the model code:
<?php
class Application_Model_Building extends Zend_Db_Table_Abstract
{
public function getname($name)
{
$db = $this->getDefaultAdapter();
$auth = Zend_Auth::getInstance();
$select = "SELECT * FROM buildings where name = $name";
$stmt = $db->query($select);
$result = $stmt->fetchAll();
print_r ($result);
}
}
?>
instead of echoing the array dump, try:
foreach ($result as $vals) {
echo "Place: ".$vals["Place"]."<br>Number: ".$vals["Number"];
}
as other posters have commented, you should read about php arrays so you know why this makes sense

Zend_Form_Element_MultiCheckbox: How to display a long list of checkboxes as columns?

So I am using a Zend_Form_Element_MultiCheckbox to display a long list of checkboxes. If I simply echo the element, I get lots of checkboxes separated by <br /> tags. I would like to figure out a way to utilize the simplicity of the Zend_Form_Element_MultiCheckbox but also display as multiple columns (i.e. 10 checkboxes in a <div style="float:left">). I can do it manually if I had an array of single checkbox elements, but it isn't the cleanest solution:
<?php
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
?>
<div id="checkboxes">
<?php foreach ($columns as $columnOfCheckboxes): ?>
<div style="float:left;">
<?php foreach($columnOfCheckboxes as $checkbox): ?>
<?php echo $checkbox ?> <?php echo $checkbox->getLabel() ?><br />
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
How can I do this same sort of thing and still use the Zend_Form_Element_MultiCheckbox?
The best place to do this is using a view helper. Here is something I thought of really quickly that you could do. You can use this in your view scripts are attach it to a Zend_Form_Element.
I am going to assume you know how to use custom view helpers and how to add them to form elements.
class My_View_Helper_FormMultiCheckbox extends Zend_View_Helper_FormMultiCheckbox
{
public function formMultiCheckbox($name, $value = null, $attribs = null,
$options = null, $listsep = "<br />\n")
{
// zend_form_element attrib has higher precedence
if (isset($attribs['listsep'])) {
$listsep = $attribs['listsep'];
}
// Store original separator for later if changed
$origSep = $listsep;
// Don't allow whitespace as a seperator
$listsep = trim($listsep);
// Force a separator if empty
if (empty($listsep)) {
$listsep = $attribs['listsep'] = "<br />\n";
}
$string = $this->formRadio($name, $value, $attribs, $options, $listsep);
$checkboxes = explode($listsep, $string);
$html = '';
// Your code
if (count($checkboxes) > 5) {
$columns = array_chunk($checkboxes, count($checkboxes) / 2); //two columns
} else {
$columns = array($checkboxes);
}
foreach ($columns as $columnOfCheckboxes) {
$html .= '<div style="float:left;">';
$html .= implode($origSep, $columnOfCheckboxes);
$html .= '</div>';
}
return $html;
}
}
If you need further explanation just let me know. I did this fairly quickly.
EDIT
The reason I named it the same and placed in a different directory was only to override Zend's view helper. By naming it the same and adding my helper path:
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
My custom view helper gets precedence over Zend's helper. Doing this allowed me to test without changing any of my forms,elements, or views that used Zend's helper. Basically, that's how you replace one of Zend's view helpers with one of your own.
Only reason I mentioned the note on adding custom view helpers and adding to form elements was because I assumed you might rename the helper to better suit your needs.

How can I make a Zend Decorator to allow a default value?

I want a basic:
<input type="text" />
And I would like the default value to clear when the user puts in a value (kinda like this). It would be ideal if the default value returned onBlur.
I don't want the default value to be submitted if they leave it and click submit.
I'm generating the form using Zend, and imagine my solution can fit entirely into a Zend Form Decorator.
I can't find any existing ones, so I ask:
Do you have said decorator? Or something that will help me make one?
Just use corresponding jQuery plugins: defaultvalue
Ok, I've built a decorator which allows me to implement the jquery plugin Ololo posted.
It checks to see if the element has a Label set, and if it does, defaults to that:
require_once 'Zend/Form/Decorator/Abstract.php';
class Application_Form_Decorator_DefaultEnabledInput extends Zend_Form_Decorator_Abstract
{
private $attribs = array();
public function render($content)
{
$element = $this->getElement();
if(get_class($element) != 'Zend_Form_Element_Text') throw new Exception("Application_Form_Decorator_DefaultEnabledInput only works on text fields");
$element->setAttrib('type', 'text');
$element->setAttrib('name', htmlspecialchars($element->getName()));
$element->setAttrib('value', htmlspecialchars($element->getValue()));
$attribs = '';
$default = $element->getLabel();
if($default)
{
$element->setAttrib('rel', $default);
$element->setAttrib('title', $default);
$class = $element->getAttrib('class');
$element->setAttrib('class', "$class hasDefault");
$default = "";
}
foreach($element->getAttribs() as $key => $val) $attribs .= "$key='$val' ";
return "<input $attribs/>";
}
}
It allows me to define a default value in the form object (using setLabel).
$element = $this->createElement('text', 'suburb');
$element->setDecorators(array('DefaultEnabledInput'));
$element->setLabel('enter suburb here');
$this->addElement($element);
And all I need to do then is ensure that query and plugin are included on the page, and this piece of code:
$(document).ready(function() {
// default values
$('.hasDefault').each(function(){
$(this).defaultValue();
});
});
Then in the template, I can display the object like this:
<?= $this->form->getElement('suburb') ?>