Joomla router new component - joomla

I have this url to display the properties:
index.php?option=com_jea&view=properties&city=2:citta&Itemid=164
with sef: sito.it/2-citta.html
This url display the property :
index.php?option=com_jea&view=property&city=2:citta&id=1:trivano&Itemid=164
with sef: sito/1-trivano/2-citta.html
but I would like
sito.it/2-citta/1-tivano.html
This is the router:
function JeaBuildRoute(&$query){
$segments = array();
if(isset($query['view'])) {
unset( $query['view'] );
}
if (isset($query['layout'])) {
$segments[] = $query['layout'];
unset( $query['layout'] );
}
if(isset($query['id'])) {
$segments[] = $query['id'];
unset( $query['id'] );
};
if(isset($query['city'])) {
$segments[] = $query['city'];
unset( $query['city'] );
};
return $segments;
function JeaParseRoute($segments)
{ $vars = array();
$app =& JFactory::getApplication();
$menu =& $app->getMenu();
$item =& $menu->getActive();
// Count segments
$count = count( $segments );
//Handle View and Identifier
switch( $item->query['view'] )
{
case 'properties':
if($count == 1) {
$vars['view'] = 'properties';
$id = explode( ':', $segments[$count-1] );
$vars['city'] = (int) $id[0];
}
if($count == 2) {
$vars['view'] = 'property';
}
$id = explode( ':', $segments[$count-1] );
$vars['id'] = (int) $id[0];
break;
case 'property':
$id = explode( ':', $segments[$count-1] );
$vars['id'] = (int) $id[0];
$vars['view'] = 'property';
break;
}
return $vars;}

Maybe you can try to reverse order of these two ifs
if(isset($query['city'])) {
$segments[] = $query['city'];
unset( $query['city'] );
};
if(isset($query['id'])) {
$segments[] = $query['id'];
unset( $query['id'] );
};

Related

Add to cart ajax custom product type options

I am trying to add custom product type to product like here wild card
and i succeeded but now i have to add this value to cart with ajax how i suppose to do this with drop-down and shortcode? i just added load_book.js but didn't added any script code because i don't know how to write ajax code for this. thanks.
My code:
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_filter("product_type_options", "woo_bookable_product");
function woo_bookable_product($product_type_options)
{
$product_type_options["Bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => "Bookable",
"description" => "Book Your Product",
"default" => "yes",
);
return $product_type_options;
}
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"] ? 'yes' : 'no';
update_post_meta($product->ID, "_bookable" ,$meta_value);
}
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts','woo_bookable_scripts');
add_action('wp_ajax_woo_bookable_shortcode', 'woo_bookable_shortcode');
add_action('wp_ajax_nopriv_woo_bookable_shortcode', 'woo_bookable_shortcode');
function woo_bookable_shortcode()
{
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable'
));
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
add_shortcode('bookable','woo_bookable_shortcode');
Finally find the solution
PHP:
<?php
/**
* Plugin Name: Bookable
* Description: Add shortcode [bookable] or in php - echo do_shortcode('[bookable]');
* Version: 0.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' ) ){
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter("product_type_options", "woo_bookable_product");
if(!function_exists('woo_bookable_product')):
function woo_bookable_product($product_type_options)
{
$product_type_options["bookable"] = array(
"id" => "_bookable",
"wrapper_class" => "show_if_simple",
"label" => __("Bookable",'woocommerce'),
"description" => __("Check if product is bookable or not",'woocommerce'),
"default" => "no",
);
return $product_type_options;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_add_cart_item_data', 'woo_bookable_custom_field', 10, 2 );
if(!function_exists('woo_bookable_custom_field')):
function woo_bookable_custom_field( $cart_item_data, $product_id )
{
$get_custom_meta = get_post_meta( $product_id , '_bookable', true );
if( $get_custom_meta == 'yes' )
{
$cart_item_data[ '_bookable' ] = $get_custom_meta;
$len = 10;
$word = array_merge(range('a', 'z'), range('A', 'Z'));
$name = shuffle($word);
$name = substr(implode($word), 0, $len);
$cart_item_data['unique_key'] = $name ;
}
return $cart_item_data;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_filter( 'woocommerce_get_item_data', 'render_woo_bookable_meta_data', 10, 2 );
if(!function_exists('render_woo_bookable_meta_data')):
function render_woo_bookable_meta_data( $cart_data, $cart_item )
{
global $woocommerce;
$custom_items = array();
if( !empty( $cart_data ) )
{
$custom_items = $cart_data;
}
if( isset( $cart_item['_bookable'] ) )
{
$custom_items[] = array(
"name" => __( "Bookable", "woocommerce" ),
"value" => $cart_item['_bookable'] );
$custom_items[] = array(
"name" => __( $cart_item['unique_key'], "woocommerce" ),
"value" => '$10' );
}
return $custom_items;
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
if(!function_exists('add_custom_price')):
function add_custom_price( $cart_object )
{
foreach ( $cart_object->get_cart() as $hash => $value )
{
if($value['_bookable'] && $value['data']->is_on_sale())
{
$newprice = $value['data']->get_sale_price()+10;
$value['data']->set_price( $newprice );
}
elseif($value['_bookable'])
{
$not_sell = $value['data']->get_regular_price()+10;
$value['data']->set_price( $not_sell );
}
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action( 'woocommerce_cart_calculate_fees', 'woo_bookable_cart_calculate_totals', 10, 1 );
if(!function_exists('woo_bookable_cart_calculate_totals')):
function woo_bookable_cart_calculate_totals( $cart_object )
{
$get_price = 0;
foreach ( $cart_object->get_cart() as $hash => $value )
{
if(!empty($value['_bookable']))
{
$percent = 10;
$get_price += $value['line_total'];
$fee = ($get_price * $percent) / 100;
}
}
$cart_object->add_fee( __("Bookable Charge($percent%)"),$fee ,false );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action("save_post_product",'woo_save_bookable_data', 10, 3);
if(!function_exists('woo_save_bookable_data')):
function woo_save_bookable_data($post_ID, $product, $update)
{
$meta_value = $_POST["_bookable"];
if(isset($meta_value))
{
$meta_value = 'yes';
update_post_meta( $product->ID, "_bookable" ,$meta_value );
wp_set_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
else
{
delete_post_meta($product->ID, "_bookable");
wp_remove_object_terms( $product->ID, 'Bookable', 'product_tag' );
}
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('woocommerce_add_order_item_meta','woo_bookable_add_order_meta', 9, 3 );
if(!function_exists('woo_bookable_add_order_meta')):
function woo_bookable_add_order_meta( $item_id, $item_values, $item_key )
{
if( ! empty( $item_values['_bookable'] ) )
wc_update_order_item_meta( $item_id, '_bookable', sanitize_text_field( $item_values['_bookable'] ) );
}
endif;
/////////////////////////////////////////////////////////////////////////////////////////////////
}
else
{
add_action( 'admin_notices', 'woo_bookable_active' );
if(!function_exists('woo_bookable_active')):
function woo_bookable_active()
{
$err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
?>
<div class="error notice">
<p><?php echo sprintf("Please Activate or <a href='%s'>Install Woocommerce</a> to use Bookable plugin",$err_text); ?></p>
</div>
<?php
//If woocommerce is not installed deactive plugin
if (is_plugin_active('bookable/bookable.php')) {
deactivate_plugins(plugin_basename(__FILE__));
}
unset($_GET['activate']);
}
endif;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_action('wp_enqueue_scripts','woo_bookable_scripts');
function woo_bookable_scripts()
{
wp_enqueue_script('load_book', plugin_dir_url( __FILE__ ).'js/load_book.js',array('jquery'));
wp_localize_script('load_book','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php')));
}
/////////////////////////////////////////////////////////////////////////////////////////////////
add_shortcode('bookable','woo_bookable_shortcode');
function woo_bookable_shortcode()
{
global $product;
$Data = '';
$query = new WP_Query(array(
'post_type' => 'product',
'meta_key' => '_bookable',
'meta_value' => 'yes'
) );
$Data.='<select name="woo_book_id" class="woo_book_pro">
<option value="0">Bookable Products</option>';
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$Data.='<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
endwhile;endif;
$Data.='</select>';
$Data.= woo_bookable_add_to_cart();
echo $Data;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$InArray = array('woo_bookable_product_id','woo_bookable_add_to_cart');
foreach($InArray as $SingleValue)
{
add_action('wp_ajax_'.$SingleValue,$SingleValue);
add_action('wp_ajax_nopriv_'.$SingleValue,$SingleValue);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_product_id()
{
$product_id = $_POST['product_id'];
if($product_id != null && $product_id!=0)
{
$add['id'] = 'success';
$add['msg'] = 'View Cart';
WC()->cart->add_to_cart( $product_id);
}
else
{
$add['id'] = 'fail';
$add['msg'] = 'Please Select Product From DropDown!!';
}
echo json_encode($add);
die();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function woo_bookable_add_to_cart()
{
return '<button type="submit" style="margin-left:10px" name="add-to-cart" value="" class="single_add_to_cart_button button alt">Add To Cart</button>
<div class="message"></div>';
die();
}
ajax Script:
jQuery(document).ready(function()
{
jQuery("select.woo_book_pro").change(function(e)
{
var id = jQuery('.woo_book_pro option:selected').val();
var action = 'woo_bookable_add_to_cart';
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"id":id
},
success: function(data)
{
jQuery('.single_add_to_cart_button').attr('value',id);
jQuery('.single_add_to_cart_button').attr("disabled", "disabled");
jQuery('.single_add_to_cart_button').text('WAIT...');
setTimeout(function() {
jQuery('.single_add_to_cart_button').removeAttr("disabled");
jQuery('.single_add_to_cart_button').text('Add To Cart');
}, 3000);
}
});
});
jQuery(".single_add_to_cart_button").click(function(e) {
e.preventDefault();
var product_id = jQuery(this).val();
var action = 'woo_bookable_product_id';
jQuery('.message').empty();
jQuery.ajax({
url:ajax_object.ajax_url,
type:"POST",
dataType:"json",
cache:false,
data:{
"action":action,
"product_id":product_id
},
success: function(data)
{
if(data.id == 'success')
{
jQuery('.message').prepend(data.msg);
return false;
}
if(data.id == 'fail')
{
jQuery('.message').prepend(data.msg).css('color','#F33')
return false;
}
}
});
});
});

Programmatically add multiple images to a single product in magento

The product id is given to which multiple images need to be added in magento.
$count = 0;
$imgArray = array($fpath.'configurable.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $image,$objectManager );
if ($count == 0){
$configProduct->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$configProduct->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load product object
$mediaAttribute = array ('thumbnail','small_image','image');
$mediaDir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList')->getPath('media');// Im Magento 2
$mediaDir = Mage::getBaseDir('media');// In Magento 1
//Case 1: When image files are alredy in your server
$fpath = 'product/images/';// path to your file
$count = 0;
$imgArray = array('image1.png','image2.png','image3.png','image4.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $fpath.$image,$objectManager,$mediaDir );// copies the file from your local storage to your-magento-root-path/pub/media
if ($count == 0){
$product->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$product->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}
function _save_image($img,$objectManager,$mediaDir) {
$imageFilename = basename($img);
$image_type = substr(strrchr($imageFilename,"."),1); //find the image extension
$filename = md5($img . strtotime('now')).'.'.$image_type; //give a new name, you can modify as per your requirement
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
$filepath = $mediaDir . '/'. $filename; //path for temp storage folder: pub/media
file_put_contents($filepath, file_get_contents(trim($img))); //store the image from external url to the temp storage folder
return $filepath;
}
//Case 2: When you have to browse images from a form. (Then save into your server and then )
if(!empty($imageFile)){
$count = 0;
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
foreach($imageFile['name'] as $k2=>$v2){
if($imageFile['error'][$k2] == 0 && file_exists($imageFile['tmp_name'][$k2])){
$ext[$k2] = pathinfo($imageFile['name'][$k2], PATHINFO_EXTENSION);
$filename[$k2] = md5(strtotime('now')).'.'.$ext[$k2];
$filepath[$k2] = $mediaDir .'/'. $filename[$k2];
$bin_string[$k2] = file_get_contents($imageFile['tmp_name'][$k2]);
file_put_contents($filepath[$k2], $bin_string[$k2]);
if ($count == 0) :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , $mediaAttribute, true, false );
else :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , null, true, false );
endif;
$count++;
}
}
}
The following code works for me.
https://www.pearlbells.co.uk/programmatically-add-multiple-images-magento-2/
if(sizeof($imgs) > 1) {
/* Assign additional images to existing products */
$product = $_objectManager->create('Magento\Catalog\Model\Product')->load($newProdId);
$productRepository = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$productRepository->save($product);
for ( $i=1; $i<sizeof($imgs); $i++ ) {
echo 'Add Images :' . $prdbasepath.basename(trim($imgs[$i])) . PHP_EOL;
$image_directory = $prdbasepath.'data'.DS.basename(trim($imgs[$i]));
if (file_exists($image_directory) && getimagesize($image_directory)) {
echo 'File exists'.PHP_EOL;
$product->addImageToMediaGallery($image_directory, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
}
}
}

laravel advanced wheres not working

my function with advanced wheres is not giving any syntax error but its not even working. Its displaying. i have written this function following this example http://laravel.com/docs/queries#advanced-wheres
public function getData($wheres1 = array(),$wheres2 = array(),$wheres3 = array(),$wheres4 = array(),$wheres5 = array(),$wheres6 = array(),$wheres7 = array())
{
$query = Listing::query();
$result = array();
$query = $query->where(function($q){
if(!empty($wheres1)){
$count=0;
foreach($wheres1 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres2)){
$count=0;
foreach($wheres2 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
})->where(function($q){
if(!empty($wheres3)){
$count=0;
foreach($wheres3 as $where){
if($count==0)
{ $q = $q->where($where['field'], $where['operator'], $where['value']);
$count++;
}
else
$q = $q->orWhere($where['field'], $where['operator'], $where['value']);
}
}
});
$result = $query->orderBy('id', 'desc')->paginate(3);
return $result;
}
You need to add use for each where
$query = $query->where(function($q) use ($wheres1) {
....
}
You may try this approach:
$query = Listing::query();
if(is_array($wheres1) && count($wheres1)) {
$first = array_shift($wheres1);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres1)) {
foreach($wheres1 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
Now repeat the same process for rest of the wheres, for example ($wheres2):
if(is_array($wheres2) && count($wheres2)) {
$first = array_shift($wheres2);
$query->where($first['field'], $first['operator'], $first['value']);
if(count($wheres2)) {
foreach($wheres2 as $where) {
$query->orWhere($wheres['field'], $wheres['operator'], $wheres['value']);
}
}
}
At last:
return $query->orderBy('id', 'desc')->paginate(3);

How to remove article ID from url in Joomla 1.5?

Using standard SEF in Joomla 1.5 I have links like: mysite.com/news/36-good-news-tooday.
I need to remove article ID from url and get something like this: mysite.com/news/good-news-today.
Note: It means I don't want use any plugins (like HP Router etc.)
I want edit Joomla own SEF.
UPD: Finally I found desicion. Here is full listing of router.php, wich you can find in components/com_content
<?php
/**
* #version $Id: router.php 14401 2010-01-26 14:10:00Z louis $
* #package Joomla
* #copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* #license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
function ContentBuildRoute(&$query)
{
$segments = array();
$menu = &JSite::getMenu();
if (empty($query['Itemid'])) {
$menuItem = &$menu->getActive();
} else {
$menuItem = &$menu->getItem($query['Itemid']);
}
$mView = (empty($menuItem->query['view']))? null : $menuItem->query['view'];
$mCatid = (empty($menuItem->query['catid']))? null : $menuItem->query['catid'];
$mId = (empty($menuItem->query['id']))? null : $menuItem->query['id'];
if(isset($query['task'])) {
return $segments;
}
if(isset($query['view']))
{
$view = $query['view'];
if(empty($query['Itemid'])) {
$segments[] = $query['view'];
}
unset($query['view']);
};
if (($mView == 'article') and (isset($query['id'])) and ($mId == intval($query['id']))) {
unset($query['view']);
unset($query['catid']);
unset($query['id']);
}
if (isset($view) and ($view == 'section' && !empty($query['Itemid']))) {
if (($mView != 'section') or ($mView == 'section' and $mId != intval($query['id']))) {
$segments[] = 'section';
unset($query['Itemid']);
}
}
if (isset($view) and $view == 'category') {
if ($mId != intval($query['id']) || $mView != $view) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
unset($query['id']);
}
if (isset($query['catid'])) {
if ((($view == 'article') and ($mView != 'category') and ($mView != 'article') and ($mCatid != intval($query['catid'])))) {
$temp = explode(':',$query['catid']);
if(count($temp) > 1)
{
$query['catid'] = $temp[1];
}
$segments[] = $query['catid'];
}
unset($query['catid']);
};
if(isset($query['id'])) {
if (empty($query['Itemid'])) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
} else {
if (isset($menuItem->query['id'])) {
if($query['id'] != $mId) {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
} else {
$temp = explode(':',$query['id']);
if(count($temp) > 1)
{
$query['id'] = $temp[1];
}
$segments[] = $query['id'];
}
}
unset($query['id']);
};
if(isset($query['year'])) {
if(!empty($query['Itemid'])) {
$segments[] = $query['year'];
unset($query['year']);
}
};
if(isset($query['month'])) {
if(!empty($query['Itemid'])) {
$segments[] = $query['month'];
unset($query['month']);
}
};
if(isset($query['layout']))
{
if(!empty($query['Itemid']) && isset($menuItem->query['layout'])) {
if ($query['layout'] == $menuItem->query['layout']) {
unset($query['layout']);
}
} else {
if($query['layout'] == 'default') {
unset($query['layout']);
}
}
};
return $segments;
}
function ContentParseRoute($segments)
{
$vars = array();
$menu =& JSite::getMenu();
$item =& $menu->getActive();
$db =& JFactory::getDBO();
$count = count($segments);
if(!isset($item))
{
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
if($vars['view'] == 'article')
{
$query = 'SELECT id FROM #__content WHERE alias = '.$db->Quote($vars['id']);
} elseif($vars['view'] == 'category') {
$query = 'SELECT id FROM #__categories WHERE section > 0 && alias = '.$db->Quote($vars['id']);
}
$db->setQuery($query);
$vars['id'] = $db->loadResult();
return $vars;
}
switch($item->query['view'])
{
case 'section' :
{
if($count == 1) {
$vars['view'] = 'category';
if(isset($item->query['layout']) && $item->query['layout'] == 'blog') {
$vars['layout'] = 'blog';
}
}
if($count == 2) {
$vars['view'] = 'article';
$vars['catid'] = $segments[$count-2];
}
$vars['id'] = $segments[$count-1];
} break;
case 'category' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'frontpage' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'article' :
{
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
} break;
case 'archive' :
{
if($count != 1)
{
$vars['year'] = $count >= 2 ? $segments[$count-2] : null;
$vars['month'] = $segments[$count-1];
$vars['view'] = 'archive';
} else {
$vars['id'] = $segments[$count-1];
$vars['view'] = 'article';
}
}
}
$alias = explode(':', $vars['id']);
if((int) $alias[0] > 0)
{
$vars['id'] = $alias[0];
} else {
if(count($alias) > 1)
{
$vars['id'] = $alias[0].'-'.$alias[1];
}
if($vars['view'] == 'article')
{
$query = 'SELECT id FROM #__content WHERE alias = '.$db->Quote($vars['id']);
} elseif($vars['view'] == 'category') {
$query = 'SELECT id FROM #__categories WHERE section > 0 && alias = '.$db->Quote($vars['id']);
}
$db->setQuery($query);
$vars['id'] = $db->loadResult();
}
return $vars;
}
I'm not an author! Router code was modified by Marvin Ryan.
This code works perfect in most of cases!
But I have some problems with JoomFish language toggle.
It have links like www.mysite.com/news/22
So I get only article ID, not article alias. This problem is still actual!
Create menu items for every article.

how to use this simple acl library into codeigniter

i used cakephp before and now use codeigniter but Unfortunately hasn't any authentication or ACL built-in library ..after more search i have found a good library, but I do not know how to use it..it is no example to use it..any one have create controller and model as sample...thanks for helping
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class acl {
/* Actions::::
* Create 1
* Read 2
* Update 4
* Delete 8
* The allowance is made by a sum of the actions allowed.
* Ex.: user can read and update (2+4)=6 … so ill put 6 instead of 1 or 0.
*
* if(!$this->acl->hasPermission(‘entries_complete_access')) {
echo “No no”;
} else
* echo “yeah”;
}
*
*
*/
var $perms = array(); //Array : Stores the permissions for the user
var $userID; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
var $ci;
function __construct($config = array()) {
$this->ci = &get_instance();
$this->userID = floatval($this->ci->session->userdata('account_id'));
$this->userRoles = $this->getUserRoles();
$this->buildACL();
}
function buildACL() {
//first, get the rules for the user's role
if (count($this->userRoles) > 0) {
$this->perms = array_merge($this->perms, $this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms, $this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID) {
//$strSQL = “SELECT `permKey` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permKey');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permKey;
}
function getPermNameFromID($permID) {
//$strSQL = “SELECT `permName` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permName');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permName;
}
function getRoleNameFromID($roleID) {
//$strSQL = “SELECT `roleName` FROM `”.DB_PREFIX.”roles` WHERE `ID` = ” . floatval($roleID) . ” LIMIT 1″;
$this->ci->db->select('roleName');
$this->ci->db->where('id', floatval($roleID), 1);
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
return $data[0]->roleName;
}
function getUserRoles() {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_roles` WHERE `userID` = ” . floatval($this->userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where(array('userID' => floatval($this->userID)));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_roles');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
$resp[] = $row->roleID;
}
return $resp;
}
function getAllRoles($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”roles` ORDER BY `roleName` ASC”;
$this->ci->db->order_by('roleName', 'asc');
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[] = array('id' => $row->ID, 'name' => $row->roleName);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getAllPerms($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”permissions` ORDER BY `permKey` ASC”;
$this->ci->db->order_by('permKey', 'asc');
$sql = $this->ci->db->get('perm_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[$row->permKey] = array('id' => $row->ID, 'name' => $row->permName, 'key' => $row->permKey);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getRolePerms($role) {
if (is_array($role)) {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` IN (” . implode(“,”,$role) . “) ORDER BY `ID` ASC”;
$this->ci->db->where_in('roleID', $role);
} else {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` = ” . floatval($role) . ” ORDER BY `ID` ASC”;
$this->ci->db->where(array('roleID' => floatval($role)));
}
$this->ci->db->order_by('id', 'asc');
$sql = $this->ci->db->get('role_perms'); //$this->db->select($roleSQL);
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '1inheritted' => true, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function getUserPerms($userID) {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_perms` WHERE `userID` = ” . floatval($userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where('userID', floatval($userID));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_perms');
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '2inheritted' => false, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function hasRole($roleID) {
foreach ($this->userRoles as $k => $v) {
if (floatval($v) === floatval($roleID)) {
return true;
}
}
return false;
}
function actionPerm($value, $wanted) {
/* Actions::::
* Create 1
* Read, 2
* Update, 4
* Delete 8
*/
$action['create'] = array('1', '3', '5', '9', '11', '13', '15'); //1
$action['read'] = array('2', '3', '6', '10', '14', '15'); //2
$action['update'] = array('4', '5', '6', '7', '12', '13', '14', '15'); //4
$action['delete'] = array('8', '9', '10', '11', '12', '13', '14', '15'); //8
$action['all'] = array('15');
if (in_array($value, $action[$wanted], true)) {
return true;
} else {
return false;
}
}
function hasPermission($permKey, $action = 'all') {
$permKey = strtolower($permKey);
if (array_key_exists($permKey, $this->perms)) {
if ($this->actionPerm($this->perms[$permKey]['value'], $action)) {
return true;
} else {
return false;
}
} else {
return false;
}
/* OLD METHOD
if ($this->perms[$permKey]['value'] === '1′ || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
*/
}
}
and this is the url
sample ACL Class for codeigniter
This is simple
Load it first in your controller
$this->load->library('acl');
Now call its method
$this->acl->buildACL();
EDIT
Use these for menuall assigning
$this->acl->perms = array('your values');
$this->acl->userID= 'user id';
$this->acl->userRoles = array('your values');
Note that you should have db table userRoles which will be invoked when the library is initialized getUserRoles method will be called and $userRoles parameter will have values.
I'm Brian from Tastybytes. My best solution would be to step through the tutorial that the code igniter ACL library is based on. It is a 100% straight port from the base php files to CI Library.
http://net.tutsplus.com/tutorials/php/a-better-login-system/
And possibly look at the very bottom of the page where I go through "Installation" and what not.

Resources