Add several records in moodle - moodle

I've been having trouble adding items in my table in moodle, this is what I've trying with no success.
$totalrec = array();
$rec2 = $DB->get_records('table1', null, '', '*', 0, 0);
$rec4 = $DB->get_records('table2', array('x' => 'y') , '', '*', 0, 0);
foreach ($rec2 as $records2) {
$rec3 = $DB->get_records('z', array('m' => 'n') , '', '*', 0, 0);
foreach ($rec3 as $records3) {
if (isset($_REQUEST['a']) && isset($_REQUEST['b'])) {
$ca = $_REQUEST['a'];
$co = $_REQUEST['b'];
$pi = $records2->idp;
$recorsh = new class ();
$recorsh->id = $records2->id;
$recorsh->te = $co;
$recorsh->idt = $ti;
$recorsh->res = $ca;
$recorsh->ida = $idaud;
$totalrec[$n] = array($recorsh);
$n++;
}
}
}
$lastinsertid2 = $DB->insert_records('table4', $totalrec);
and, this one:
$rec2 = $DB->get_records('table1', null, '', '*', 0, 0);
$rec4 = $DB->get_records('table2', array('x' => 'y') , '', '*', 0, 0);
foreach($rec2 as $records2) {
$rec3 = $DB->get_records('z', array('m' => 'n') , '', '*', 0, 0);
foreach($rec3 as $records3) {
if (isset($_REQUEST['a']) && isset($_REQUEST['b'])) {
$ca = $_REQUEST['a'];
$co = $_REQUEST['b'];
$pi = $records2->idp;
$recorsh = new class ();
$recorsh->id = $records2->id;
$recorsh->te = $co;
$recorsh->idt = $ti;
$recorsh->res = $ca;
$recorsh->ida = $idaud;
$lastinsertid = $DB->insert_record('table4', $recorsh, false);
}
}
}
Both of them gives me a "Error writing to database" but doesn't say anything specific, I know that I'm not doing the inserting "in the right way" but I don't know how to do it, what am I doing wrong?

It's probably because the ID is added to each object before inserting.
$recorsh->id = $records2->id;
Like davosmith says, during development always have debugging set to developer level.
In your config.php have this
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 0);
$CFG->debug = E_ALL | E_STRICT; // 32767;
$CFG->debugdisplay = true;
Also never ever use $_REQUEST or $_GET or $_POST directly. This can introduce SQL injection.
Use
$a = optional_param('a', null, PARAM_XXX);
$b = optional_param('b', null, PARAM_XXX);
or
$a = required_param('a', PARAM_XXX);
$b = required_param('b', PARAM_XXX);
Change PARAM_XXX to the type of parameter you are expecting. eg PARAM_INT, PARAM_BOOL etc.

Related

Magento 2 - Update Product stock and Price Programmatically for multiple stores

I'm getting data from the CSV file and according to SKU file load the product.
We are getting 30 products from the CSV file and update those product data in Magento.
We have set up cron every 5 minutes and after 5 minutes it will get the next 30 products and update.
The starting process script is working fine. But after the sometime script is going to be slow and it will take time to update the product.
So, the next cron is running at on the same time there are lots of scripts are running on the server, and the server load will increase.
After taking so much load on the server website going to be slow.
Can you please let me know the way so product updating process will be consistent and time will not so much vary.
public function execute()
{
$data = array of csv file data;
$sql = "Select value FROM " . $tableName . " where path='catalog/product/update_cron' and scope_id=0";
$result = $connection->fetchAll($sql);
$update_cron = $result[0]['value'];
$total_products = count($data);
if ($total_products == $update_cron) {
$this->configWriter->save('catalog/product/update_cron_status', '1', 'default', '0'); // inject Magento\Store\Model\ScopeInterface;
exit;
}
if ($update_cron != '' && $update_cron != 0) {
$data = array_slice($data, (int)$update_cron, 30);
} else {
$update_cron = 0;
$data = array_slice($data, 0, 30);
}
$current_date = date("m/d/Y");
$i = 0;
foreach ($data as $key => $value) {
/*********************************************Update Product Price********************************************************/
if ($value['Artikel'] != '') {
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product_id = $product->getIdBySku($value['Artikel']);
if (!empty($product_id)) {
/************************Update Product Price for all Stores**************************************/
$price_b2b = str_replace(',', '.', (string) $value['Verkoopprijs']);
$price_b2c = str_replace(',', '.', (string) $value['Numeriek1']);
$price_club = str_replace(',', '.', (string) $value['Numeriek2']);
//$special_price_b2b = str_replace(',', '.', (string) $value['Numeriek3']);
$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes(array($product_id),
array(
'name' => $value['Artikel'],
'ean_code'=>$value['Barcode'],
'price'=>$price_b2c,
'price_wholesale'=>$price_b2b,
'price_clubs'=>$price_club,
'description'=>$value['Omschrijving Engels'],
),0
);
/* if ($value['Boolean1'] == 'True') {
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => $special_price_b2b, 'special_from_date' => $current_date), 4);
} else { */
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => '', 'special_from_date' => ''), 4);
//}
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_club), 7);
/*********************************************Inventory Update********************************************************/
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$sku = $value['Artikel'];
if($sku != '')
{
$qty = round(str_replace(',', '', (string) $value['Stock']));
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($value['Stock']);
$stockItem->setIsInStock((int) ($qty > 0)); // this line
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
/*****************************************************************************************************/
}
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
else {
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
}
die('records completed');
}
}
die('stop');
}
Thanks in advance

How to add variable to header.php controller and use it in header.tpl

I am creating a custom theme for OpenCart 2.3 and I need to show some additional information in page header (header.tpl). So I added some variable to catalog/controller/common/header.php:
$data['some_var'] = 'some_value';
And then I am trying to use this data in the header.tpl:
<?php echo $this->data['some_var']; ?>
But I am always getting this error:
Notice: Undefined index: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
If I try to use this code:
<?php echo $some_var; ?>
Then I am getting another error:
Notice: Undefined variable: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
And even when I do echo print_r($this->data) in header.tpl I don't even see this variable in $data array.
What am I doing wrong? Please help.
EDIT
Here is the full code of my header.php controller file. I added my custom variable at the very end of the file.
class ControllerCommonHeader extends Controller {
public function index() {
// Analytics
$this->load->model('extension/extension');
$data['analytics'] = array();
$analytics = $this->model_extension_extension->getExtensions('analytics');
foreach ($analytics as $analytic) {
if ($this->config->get($analytic['code'] . '_status')) {
$data['analytics'][] = $this->load->controller('extension/analytics/' . $analytic['code'], $this->config->get($analytic['code'] . '_status'));
}
}
if ($this->request->server['HTTPS']) {
$server = $this->config->get('config_ssl');
} else {
$server = $this->config->get('config_url');
}
if (is_file(DIR_IMAGE . $this->config->get('config_icon'))) {
$this->document->addLink($server . 'image/' . $this->config->get('config_icon'), 'icon');
}
$data['title'] = $this->document->getTitle();
$data['base'] = $server;
$data['description'] = $this->document->getDescription();
$data['keywords'] = $this->document->getKeywords();
$data['links'] = $this->document->getLinks();
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['lang'] = $this->language->get('code');
$data['direction'] = $this->language->get('direction');
$data['name'] = $this->config->get('config_name');
if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
$data['logo'] = $server . 'image/' . $this->config->get('config_logo');
} else {
$data['logo'] = '';
}
$this->load->language('common/header');
$data['text_home'] = $this->language->get('text_home');
// Wishlist
if ($this->customer->isLogged()) {
$this->load->model('account/wishlist');
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), $this->model_account_wishlist->getTotalWishlist());
} else {
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
}
$data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
$data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', true), $this->customer->getFirstName(), $this->url->link('account/logout', '', true));
$data['text_account'] = $this->language->get('text_account');
$data['text_register'] = $this->language->get('text_register');
$data['text_login'] = $this->language->get('text_login');
$data['text_order'] = $this->language->get('text_order');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['text_download'] = $this->language->get('text_download');
$data['text_logout'] = $this->language->get('text_logout');
$data['text_checkout'] = $this->language->get('text_checkout');
$data['text_category'] = $this->language->get('text_category');
$data['text_all'] = $this->language->get('text_all');
$data['home'] = $this->url->link('common/home');
$data['wishlist'] = $this->url->link('account/wishlist', '', true);
$data['logged'] = $this->customer->isLogged();
$data['account'] = $this->url->link('account/account', '', true);
$data['register'] = $this->url->link('account/register', '', true);
$data['login'] = $this->url->link('account/login', '', true);
$data['order'] = $this->url->link('account/order', '', true);
$data['transaction'] = $this->url->link('account/transaction', '', true);
$data['download'] = $this->url->link('account/download', '', true);
$data['logout'] = $this->url->link('account/logout', '', true);
$data['shopping_cart'] = $this->url->link('checkout/cart');
$data['checkout'] = $this->url->link('checkout/checkout', '', true);
$data['contact'] = $this->url->link('information/contact');
$data['telephone'] = $this->config->get('config_telephone');
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
// Level 1
$data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$data['language'] = $this->load->controller('common/language');
$data['currency'] = $this->load->controller('common/currency');
$data['search'] = $this->load->controller('common/search');
$data['cart'] = $this->load->controller('common/cart');
// For page specific css
if (isset($this->request->get['route'])) {
if (isset($this->request->get['product_id'])) {
$class = '-' . $this->request->get['product_id'];
} elseif (isset($this->request->get['path'])) {
$class = '-' . $this->request->get['path'];
} elseif (isset($this->request->get['manufacturer_id'])) {
$class = '-' . $this->request->get['manufacturer_id'];
} elseif (isset($this->request->get['information_id'])) {
$class = '-' . $this->request->get['information_id'];
} else {
$class = '';
}
$data['class'] = str_replace('/', '-', $this->request->get['route']) . $class;
} else {
$data['class'] = 'common-home';
}
//CUSTOM THEME VARIABLES BEGIN
$data['some_var'] = 'some_value';
//CUSTOM THEME VARIABLES END
return $this->load->view('common/header', $data);
}
}
I need to see your controller to get the full picture and then i will give you the full answer, but take a look on your controller and make sure that you bind your data like the sample below:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
Thanks
I finally found the solution of my problem, but I am not sure if it is the right way to do this. I found that I need to make changes in system/storage/modification/catalog/controller/common/header‌​.php. It seems like after installing some extension via Vqmod the controller file have been copied to this folder. If I add my variables there then I can access them without any issues.

Uncaught exception 'MongoCursorException' with message .... duplicate key error index:

Here's my code:
When i try to work it, there's an error as it:
"Fatal error: Uncaught exception 'MongoCursorException' with message
'localhost:27017: E11000 duplicate key error index:
futbol_db.maclar.$kod_1_link_1 dup key:
{ : null, : null }' in /var/www/html/cagkansokmen/futbol/db/maclar.php:182
Stack trace: #0 /var/www/html/cagkansokmen/futbol/db/maclar.php(182):
MongoCollection->insert(Array) #1 {main} thrown in
/var/www/html/cagkansokmen/futbol/db/maclar.php on line 182"
The problem is about insert. Because, when i drop insert code, there's no problem about this code. But if i try to insert data, there's an error just as i said.
How can i fix it?
$collection1 = $db->lig_kod;
$collection_maclar = $db->maclar;
$collection1->ensureIndex(array("kod" => 1, "link" => 1), array("unique" => true, "dropDups" => true));
$a = $collection1->find(array())->limit(15)->skip(0);
foreach($a as $b){
$kod = $b["kod"];
$link = $b["link"];
$parc = explode(',', $link);
$ligkoduson = $parc[0].",".$parc[1];
$url2 = "http://www.stats.betradar.com/s4/gismo.php?&html=1&id=1424&language=tr&clientid=35&state=".$ligkoduson.",5_".$kod.",9_fixtures,231_fixtures,23_1,242_21&child=0";
$url2 = curl($url2);
$url2 = str_replace("\t","",$url2);
$url2 = str_replace("\n","",$url2);
$url2 = str_replace("\r","",$url2);
$bul = ara("<![CDATA[", "]]>", $url2);
$sonuc = ara("setState('", ",", $bul[0]);
$say = count($sonuc);
for($i = 0; $i<$say; $i++){
$sezonbul = $sonuc[$i];
$lonk = "http://www.stats.betradar.com/s4/gismo.php?&html=1&id=2127&language=tr&clientid=35&state=".$ligkoduson.",".$sezonbul.",9_fixtures,231_full,23_1&child=2";
$fiksturlink = curl("http://www.stats.betradar.com/s4/gismo.php?&html=1&id=2127&language=tr&clientid=35&state=".$ligkoduson.",".$sezonbul.",9_fixtures,231_full,23_1&child=2");
$fiksturlink = str_replace("\t","",$fiksturlink);
$fiksturlink = str_replace("\n","",$fiksturlink);
$fiksturlink = str_replace("\r","",$fiksturlink);
$kategori = ara('title="', '"', $fiksturlink);
$kategori_parcala = explode(' > ', $kategori[0]);
$tur = trim($kategori_parcala[0]);
$ulke = trim($kategori_parcala[1]);
$lig = $kategori_parcala[2];
$lig_parcala = explode(' ', $lig);
$lig_bosluk = count($lig_parcala)-1;
$sezon = trim($lig_parcala[$lig_bosluk]);
$lig_son = trim(str_replace($sezon, "", $lig));
$takimlar = ara('<span class="teams">', '</a>', $fiksturlink);
$timebul = ara('<td class="datetime">', '</td>', $fiksturlink);
$fhbul = ara('<td class="p1 ">', '</td>', $fiksturlink);
$ftbul = ara('<td class="nt ftx ">', '</td>', $fiksturlink);
$dongusay = count($takimlar);
echo $dongusay."<br>";
for($dongu = 0; $dongu<$dongusay; $dongu++){
$takimlarbul = ara('">', '</span>', $takimlar[$dongu]);
$home = trim($takimlarbul[0]);
$away = trim($takimlarbul[2]);
$time = trim($timebul[$dongu]);
$time_ayir = explode(' ', $time);
$yil_ayir = explode('/', $time_ayir[0]);
$gun = $yil_ayir[0];
$ay = $yil_ayir[1];
$yil = $yil_ayir[2];
$saat_ayir = explode(':', $time_ayir[1]);
$saat = $saat_ayir[0];
$dk = $saat_ayir[1];
$time_sonuc = mktime($saat, $dk, 0, $ay, $gun, $yil);
$fh = trim($fhbul[$dongu]);
if(empty($fh)){
$fh1 = null;
$fh2 = null;
}else{
$fh_ayir = explode(':', $fh);
$fh1 = $fh_ayir[0];
$fh2 = $fh_ayir[1];
}
$ft = trim($ftbul[$dongu]);
if(empty($ft)){
$ft1 = null;
$ft2 = null;
}else{
if(strpos($ft, '(')){
$parcala1 = explode('(', $ft);
$ft_ayir = explode(':', $parcala1[0]);
$ft1 = $ft_ayir[0];
$ft2 = $ft_ayir[1];
}else{
$ft_ayir = explode(':', $ft);
$ft1 = $ft_ayir[0];
$ft2 = $ft_ayir[1];
}
}
echo $ligkoduson."-".$sezonbul."-".$tur."-".$ulke."-".$lig_son."-".$sezon."-".$home."-".$away."-".$time_sonuc."-".$fh1."-".$fh2."-".$ft1."-".$ft2."<br>";
$collection_maclar->insert(array(
'ulke_kodu'=>$ligkoduson,
'sezon_kodu'=>$sezonbul,
'tur'=>$tur,
'ulke'=>$ulke,
'lig'=>$lig_son,
'sezon'=>$sezon,
'home'=>$home,
'away'=>$away,
'tarih'=>$time_sonuc,
'fh1'=>$fh1,
'fh2'=>$fh2,
'ft1'=>$ft1,
'ft2'=>$ft2
));
}
}
}
You have an unique index on "kod" and "link", but the document you are inserting doesn't include either of these fieldnames.
That means the first document you insert will have these values as null, and the second one will too.. but fails as it violoates the unique index you created.
Note that the "dropDupe" flag you provide with the ensureIndex() command only means "drop existing duplicates", not "if I try to use that key again, drop the previous document".
Your current code seems to be ensuring this index on the "lig_kod" collection, but I suspect you may have previously (maybe accidentally) used the $collection_maclar variable, rather then the $collection1 variable and executed the code, resulting in creating the index on the maclar collection.
-Hannes

Zend for picture uploads needing to resize images

So, I am using Zend to handle my image uploads. This script works well, but I was wondering if there is a way to resize the image that is being uploaded no matter what the current size is. I've seen 2 similar posts, but their code was entirely different, thus would be difficult to translate into mine from theirs. If possible, I would really like to not have to use extensions, but I will if I have to. Any ideas?
if (isset($_POST['upload'])) {
require_once('scripter/lib.php');
//try {
$destination = 'C:\----';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '10000kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
//$pic = $filename;
if (!$uploader->isValid() || $errors) {
$messages = $uploader->getMessages();
} else {
//$pic = $filename;
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
//$pic = $no_spaces;
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$pic = "imgs/upld/" . $no_spaces;
$uploaded .= " and renamed $no_spaces";
//$pic = $no_spaces;
//$pic = $uploader->getFileName(NULL, FALSE);
} else {$pic = "imgs/upld/" . $filename;;}
$messages[] = "$uploaded";
//$pic = $no_spaces;
}
Zend Framework does not ship with a component for handling images.
Good News! PHP has several components that are really good at dealing with all kinds of image issues.
GD (one of those great PHP extensions) is currently shipped as a core extension for PHP, perhaps you will find it useful.
Maybe this will help: http://phpcodeforbeginner.blogspot.com/2013/04/resize-image-or-crop-image-using-gd.html
(not really trying to be too snarky ;)

Modify code to auto complete on taxonomies instead of title

I've been trying for hours to modify this plugin to work with custom taxonomies instead of post titles and/or post content
http://wordpress.org/extend/plugins/kau-boys-autocompleter/
Added the code / part of the plugin where I think the modification should be done. I could post some stuff I tried but I think it would just confuse people, I don't think I ever came close. Normally I can modify code perfectly but just can't seem to find it. I've tried this method posted here.
http://wordpress.org/support/topic/autocomplete-taxonomy-in-stead-of-title-or-content
But it doesn't work. I've tried searching for possible solutions around his suggestion but I'm starting to think his suggestion isn't even close to fixing it.
if(WP_DEBUG){
error_reporting(E_ALL);
} else {
error_reporting(0);
}
header('Content-Type: text/html; charset=utf-8');
// remove the filter functions from relevanssi
if(function_exists('relevanssi_kill')) remove_filter('posts_where', 'relevanssi_kill');
if(function_exists('relevanssi_query')) remove_filter('the_posts', 'relevanssi_query');
if(function_exists('relevanssi_kill')) remove_filter('post_limits', 'relevanssi_getLimit');
$choices = get_option('kau-boys_autocompleter_choices');
$framework = get_option('kau-boys_autocompleter_framework');
$encoding = get_option('kau-boys_autocompleter_encoding');
$searchfields = get_option('kau-boys_autocompleter_searchfields');
$resultfields = get_option('kau-boys_autocompleter_resultfields');
$titlelength = get_option('kau-boys_autocompleter_titlelength');
$contentlength = get_option('kau-boys_autocompleter_contentlength');
if(empty($choices)) $choices = 10;
if(empty($framework)) $framework = 'jQuery';
if(empty($encoding)) $encoding = 'UTF-8';
if(empty($searchfields)) $searchfields = 'both';
if(empty($resultfields)) $resultfields = 'both';
if(empty($titlelength)) $titlelength = 50;
if(empty($contentlength)) $contentlength = 120;
mb_internal_encoding($encoding);
mb_regex_encoding($encoding);
$words = '%'.$_REQUEST['q'].'%';
switch($searchfields){
case 'post_title' :
$where = 'post_title LIKE "'.$words.'"';
break;
case 'post_content' :
$where = 'post_content LIKE "'.$words.'"';
default :
$where = 'post_title LIKE "'.$words.'" OR post_content LIKE "'.$words.'"';
}
$wp_query = new WP_Query();
$wp_query->query(array(
's' => $_REQUEST['q'],
'showposts' => $choices,
'post_status' => 'publish'
));
$posts = $wp_query->posts;
$results = array();
foreach ($posts as $key => $post){
setup_postdata($post);
$title = strip_tags(html_entity_decode(get_the_title($post->ID), ENT_NOQUOTES, 'UTF-8'));
$content = strip_tags(strip_shortcodes(html_entity_decode(get_the_content($post->ID), ENT_NOQUOTES, 'UTF-8')));
if(mb_strpos(mb_strtolower(($searchfields == 'post_title')? $title : (($searchfields == 'post_content')? $content : $title.$content)), mb_strtolower($_REQUEST['q'])) !== false){
$results[] = array(
'url' => get_permalink($post->ID),
'title' => highlightSearchString(strtruncate($title, $titlelength, true), $_REQUEST['q']),
'content' => (($resultfields == 'both')? highlightSearchString(strtruncate($content, $contentlength, false, '[...]', $_REQUEST['q']), $_REQUEST['q']) : '')
);
}
}
printResults($results, $framework);
function highlightSearchString($value, $searchString){
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$value = utf8_encode(html_entity_decode(utf8_decode($value)));
}
$regex_chars = '\.+?(){}[]^$';
for ($i=0; $i<mb_strlen($regex_chars); $i++) {
$char = mb_substr($regex_chars, $i, 1);
$searchString = str_replace($char, '\\'.$char, $searchString);
}
$searchString = '(.*)('.$searchString.')(.*)';
return mb_eregi_replace($searchString, '\1<span class="ac_match">\2</span>\3', $value);
}
function strtruncate($str, $length = 50, $cutWord = false, $suffix = '...', $needle = ''){
$str = trim($str);
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$str = utf8_encode(html_entity_decode(utf8_decode($str)));
}else{
$str = html_entity_decode($str, ENT_NOQUOTES, mb_internal_encoding());
}
if(mb_strlen($str)>$length){
if(!empty($needle) && mb_strpos(mb_strtolower($str), mb_strtolower($needle)) > 0){
$pos = mb_strpos(mb_strtolower($str), mb_strtolower($needle)) + (mb_strlen($needle) / 2);
$startToShort = ($pos - ($length / 2)) < 0;
$endToShort = ($pos + ($length / 2)) > mb_strlen($str);
// build the prefix and suffix
$prefix = $suffix;
if($startToShort){
$prefix = '';
}
if($endToShort){
$suffix = '';
}
// set maximum length
$length = $length - mb_strlen($prefix) - mb_strlen($suffix);
// get the start
if($startToShort){
$start = 0;
} elseif($endToShort){
$start = mb_strlen($str) - $length;
} else {
$start = $pos - ($length / 2);
}
// shorten the string
$string = mb_substr($str, $start, $length);
if($cutWord){
return $prefix.$string.$suffix;
} else {
$firstWhitespace = ($startToShort)? 0 : mb_strpos($string, ' ');
$lastWhitespace =($endToShort)? mb_strlen($string) : mb_strrpos($string, ' ');
return $prefix.' '.(!empty($lastWhitespace)? mb_substr($string, $firstWhitespace, ($lastWhitespace - $firstWhitespace)) : $string).' '.$suffix;
}
} else {
$string = mb_substr($str, 0, $length - mb_strlen($suffix));
return (($cutWord) ? $string : mb_substr($string, 0, mb_strrpos($string, ' ')).' ').$suffix;
}
} else {
return $str;
}
}
function printResults($results, $framework){
if($framework == 'scriptaculous'){
echo '<ul>';
foreach($results as $result){
echo ' <li>
<a href="'.$result['url'].'">
<span class="title">'.$result['title'].'</span>
<span style="display: block;">'.$result['content'].'</span>
</a>
</li>';
}
echo '</ul>';
} else {
foreach($results as $result){
echo str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), '<span class="title">'.$result['title'].'</span><p>'.$result['content'].'</p>')
.'|'
.str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), $result['url'])
."\n";
}
}
}