Suggested image rotator for use in Yii Framework App? - php

I have an extension that displays a basic user profile derived from the Yii widget class. My extension is defined as follows:
class BasicProfile extends CWidget
{
public $user_id;
private $userinfo = array();
private $userdetail = array();
private $availibility = array();
private $availabletime = array();
private $usereducation = array();
private $userlanguages = array();
private $userlivingplace = array();
public function init()
{
$this->userinfo = $users = Users::model()->findByPk($this->user_id);
$this->userdetail = $users->profile;
$this->availibility = $users->user_availibility;
$this->availabletime = $users->user_availabletime;
$this->usereducation = $users->user_education;
$this->userlanguages = $users->user_languagues;
$this->userlivingplace = $users->user_livingplaces;
}
public function run() {
$this->getUserDetail();
}
public function getUserDetail(){
$basic = $this->userinfo;
$detail = $this->userdetail;
$availibility = $this->availibility;
$availabletime = $this->availabletime;
$usereducation = $this->usereducation;
$userlanguages = $this->userlanguages;
$userlivingplaces = $this->userlivingplace;
$age = getAge(strtotime($detail['date_of_birth']));
$is_smoker = isSmoker($detail['is_smoker']);
$education = '';
foreach ($usereducation as $ue)
{
$e = $ue->educ;
$education .= $e['edu_name']. ', ';
}
$education = substr($education, 0, -2);
$languages = '';
foreach ($userlanguages as $ul)
{
$l = $ul->lang;
$languages .= $l['language_title']. ', ';
}
$languages = substr($languages, 0, -2);
$condition = array('where_condition'=>'up.user_id=:id AND up.is_currently_own=:own', 'where_data'=>array(':id'=>(int)$this->user_id, ':own'=>'Yes'));
$user_pets = Users::model()->getUserPets($condition);
$profile_images = UserProfileImages::model()->getProfileImages( array('select'=>'all'), $this->user_id );
foreach( $profile_images as $profile_img ) {
$images[] = $profile_img->profile_image;
}
$image = '';
if( $images ){
$main_image = HTTP_HOST . PROFILE_IMAGES_THUMB . $images[0];
$image = '<img src="'. $main_image .'" />';
}
$address1 = $basic['address1'];
if($basic['address2'] != "")
$address1 .= ", ".$basic['address2'];
$address2 = $basic['city']." ".$basic['state'].", ". $basic['zip'];
$editprofile = url('/users/account');
$editimglink = url('/images/icons/Modify.png');
}
}
My goal is to simply call this extension in my view as follwos:
$this->widget('ext.UserProfile.BasicProfile',array('user_id'=>$user_id));
However, I'm wondering if my extension is the proper place to encapsulate the image rotator? Should the rotator be included in the extension, or as part of the view? Should a generic JQuery image rotator be used, or is there one that plays well with Yii Framework?

I like to use JQuery.Cycle as my image rotator. I suggest that you build an extension with assets to keep the code in one place. you can however put your css in your theme folder and build a basic css in your extension to keep it clean like the basic pager of yii.
You could call your widget like this:
$this->widget("application.extensions.rotator", array("images" => array("/path/to/image/1", "/path/to/image/2"), "prevBtn" => "/path/to/prev/button");

Related

How to Indent Laravel controller, view code?

One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach

Opencart foreach showing NULL in tpl file

Am creating a custom module in my store using Opencart, that file name called sales_performance.
Here am passing the values for selected customer id and name.
All working fine. when am using var_dump($data['customers']); in controller it showing some values in top of the sales_performance.tpl.
But in sales_performance.tpl am using var_dump($customers); it showing NULL.
sales_performance.php(controller)
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$data['text_list'] = $this->language->get('text_list');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['text_missing'] = $this->language->get('text_missing');
$data['column_order_id'] = $this->language->get('column_order_id');
$data['column_customer'] = $this->language->get('column_customer');
$data['column_status'] = $this->language->get('column_status');
$data['column_total'] = $this->language->get('column_total');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_date_modified'] = $this->language->get('column_date_modified');
$data['column_action'] = $this->language->get('column_action');
$data['entry_return_id'] = $this->language->get('entry_return_id');
$data['entry_order_id'] = $this->language->get('entry_order_id');
$data['entry_customer'] = $this->language->get('entry_customer');
$data['entry_order_status'] = $this->language->get('entry_order_status');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_date_added'] = $this->language->get('entry_date_added');
$data['entry_date_modified'] = $this->language->get('entry_date_modified');
$data['button_invoice_print'] = $this->language->get('button_invoice_print');
$data['button_shipping_print'] = $this->language->get('button_shipping_print');
$data['button_add'] = $this->language->get('button_add');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_filter'] = $this->language->get('button_filter');
$data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$data['sort'] = $sort;
$data['order'] = $order;
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($data['customers']); // this the code showing some value
//select customer
}
}
sales_performance.tpl
<?php var_dump($customers); ?>
<?php foreach ($customers as $customer) { ?>
<h3>Customer ID: <?php echo $customer['customer_id']; ?></h3>
<h3>Customer Name:</h3>
<?php } ?>
What am missed here...?
And Thanks for advance...
The data variable is a variable in your function, you are able to create a protected variable in your class and use that one.
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
private $data = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$this->getSelectedCustomer();
$this->data['text_list'] = $this->language->get('text_list');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_confirm'] = $this->language->get('text_confirm');
$this->data['text_missing'] = $this->language->get('text_missing');
$this->data['column_order_id'] = $this->language->get('column_order_id');
$this->data['column_customer'] = $this->language->get('column_customer');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['column_date_added'] = $this->language->get('column_date_added');
$this->data['column_date_modified'] = $this->language->get('column_date_modified');
$this->data['column_action'] = $this->language->get('column_action');
$this->data['entry_return_id'] = $this->language->get('entry_return_id');
$this->data['entry_order_id'] = $this->language->get('entry_order_id');
$this->data['entry_customer'] = $this->language->get('entry_customer');
$this->data['entry_order_status'] = $this->language->get('entry_order_status');
$this->data['entry_total'] = $this->language->get('entry_total');
$this->data['entry_date_added'] = $this->language->get('entry_date_added');
$this->data['entry_date_modified'] = $this->language->get('entry_date_modified');
$this->data['button_invoice_print'] = $this->language->get('button_invoice_print');
$this->data['button_shipping_print'] = $this->language->get('button_shipping_print');
$this->data['button_add'] = $this->language->get('button_add');
$this->data['button_edit'] = $this->language->get('button_edit');
$this->data['button_delete'] = $this->language->get('button_delete');
$this->data['button_filter'] = $this->language->get('button_filter');
$this->data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['header'] = $this->load->controller('common/header');
$this->data['column_left'] = $this->load->controller('common/column_left');
$this->data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $this->data));
}
public function getSelectedCustomer()
{
$isSalesPerson=$_COOKIE['isSalesPerson'];
if($isSalesPerson =='true')
{
$selectedCustomerId = $_GET['selectedCustomerId'];
$selectedCustomerName = $_GET['selectedCustomerName'];
}
//select customer
$customerId=$_COOKIE['customerId'];
$query = $this->db->query("select customer_id,CONCAT(c.firstname,' ', c.lastname) as name from " . DB_PREFIX . "customer c where c.sales_person_id=".$customerId." and customer_id=".$selectedCustomerId."");
$getcustomers=$query->rows;
foreach ($getcustomers as $customer) {
$this->data['customers'][] = array(
'customer_id' => $customer['customer_id'],
'name' => $customer['name']
);
}
var_dump($this->data['customers']); // this the code showing some value
//select customer
}
}
You are also able to let getSelectedCustomer() return an array with the customers, this would be the normal way to do it. I would recomment it to put it into a model as well.

Creating default object from empty value ( stdClass? )

The script run good, but only when I fetching out the groups of the user, it's says:
SteamUser.php (132): Creating default object from empty value
function getProfileData() {
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userID}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$this->steamID64 = (string)$parsedData->steamID64;
$this->steamID = (string)$parsedData->steamID;
$this->stateMessage = (string)$parsedData->stateMessage;
$this->visibilityState = (int)$parsedData->visibilityState;
$this->privacyState = (string)$parsedData->privacyState;
$this->avatarIcon = (string)$parsedData->avatarIcon;
$this->avatarMedium = (string)$parsedData->avatarMedium;
$this->avatarFull = (string)$parsedData->avatarFull;
$this->vacBanned = (int)$parsedData->vacBanned;
$this->tradeBanState = (string)$parsedData->tradeBanState;
$this->isLimitedAccount = (string)$parsedData->isLimitedAccount;
$this->onlineState = (string)$parsedData->onlineState;
$this->inGameServerIP = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($this->privacyState == "public") {
$this->customURL = (string)$parsedData->customURL;
$this->memberSince = (string)$parsedData->memberSince;
$this->steamRating = (float)$parsedData->steamRating;
$this->hoursPlayed2Wk = (float)$parsedData->hoursPlayed2Wk;
$this->headline = (string)$parsedData->headline;
$this->location = (string)$parsedData->location;
$this->realname = (string)$parsedData->realname;
$this->summary = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($this->onlineState == "in-game") {
$this->inGameInfo = array();
$this->inGameInfo["gameName"] = (string)$parsedData->inGameInfo->gameName;
$this->inGameInfo["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$this->inGameInfo["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$this->inGameInfo["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$this->inGameInfo["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this->weblinks = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$this->weblinks[$i]->title = (string)$weblink->title;
$this->weblinks[$i]->link = (string)$weblink->link;
$i++;
}
}
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$this->groups[$i]->groupID64 = (string)$group->groupID64; // row 132 in script
$this->groups[$i]->groupName = (string)$group->groupName;
$this->groups[$i]->groupURL = (string)$group->groupURL;
$this->groups[$i]->headline = (string)$group->headline;
$this->groups[$i]->summary = (string)$group->summary;
$this->groups[$i]->avatarIcon = (string)$group->avatarIcon;
$this->groups[$i]->avatarMedium = (string)$group->avatarMedium;
$this->groups[$i]->avatarFull = (string)$group->avatarFull;
$this->groups[$i]->memberCount = (string)$group->memberCount;
$this->groups[$i]->membersInChat = (string)$group->membersInChat;
$this->groups[$i]->membersInGame = (string)$group->membersInGame;
$this->groups[$i]->membersOnline = (string)$group->membersOnline;
$i++;
}
}
}
}
.
.
.
I already tried to using associative arrays, but didn't work; maybe with doing it all new. -_-
So, I can't set error_reporting(0) or ini_set at all.
I also used new stdClass() as a try. But I didn't get this running too.
You create an array.
$this->groups = array();
But in this array you donot create any object. You just use this array's elements (thoes are not initialized) as objects. You should add this line before your 132. row.
$this->groups[$i] = new Group();
Or something similar.
If you do not have Group class you should try
$this->groups[$i] = new stdClass();

Prestrashop - how to add content for Tab in back-office

Hi i have an issue with prestashop module, I've just created module called TestModule and in install method I got following code:
public function install() {
$parent_tab = new Tab();
foreach (Language::getLanguages(true) as $lang) {
$parent_tab->name[$lang['id_lang']] = 'TestModule';
}
$parent_tab->class_name = 'TestModule';
$parent_tab->id_parent = 0;
#copy(_PS_MODULE_DIR_ . $this->name . '/logo.png', _PS_IMG_DIR_ . 't/TestModule.png');
$parent_tab->module = $this->name;
$parent_tab->add();
if (!parent::install()) {
return false;
}
return true;
}
And it created the Tab "TestModule", but when I'm clicking on it there is the information that "Controller not found". How can I set some content here?
See this bellow code , it will help you you made mistake
$langs = Language::getLanguages();
$id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$smarttab = new Tab();
$smarttab->class_name = "AdminSmartBlog";
$smarttab->module = "";
$smarttab->id_parent = 0;
foreach($langs as $l){
$smarttab->name[$l['id_lang']] = $this->l('Blog');
}
$smarttab->save();
$tab_id = $smarttab->id;
#copy(dirname(__FILE__)."/AdminSmartBlog.gif",_PS_ROOT_DIR_."/img/t/AdminSmartBlog.gif");

Pulling articles from specific category through Joomla! 3.0 Module

Here is the scenario, and let me start off saying any help would be a god-send, I have cloned the Article Category module inside Joomla! Basically changed all the articles_category to breed_articles (for my purpose). This worked fine, where I am stuck at is where in the module code can I define a specific category to pull articles from.
I know I can do this in the backend but I am working on a dynamic way to pull articles by categories and need to define the category in the module code. That being said, I will also need to pull the categoies by the slug not id.
Where I have been looking is the helper.php file in the module and I believe that I am on the right path there. I have tried replacing a few things and tracing the code but I am not very familiar with Joomla!
helper.php
$com_path = JPATH_SITE.'/components/com_content/';
require_once $com_path.'router.php';
require_once $com_path.'helpers/route.php';
JModelLegacy::addIncludePath($com_path . '/models', 'ContentModel');
abstract class modBreedArticlesHelper
{
public static function getList(&$params)
{
// Get an instance of the generic articles model
$articles = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$articles->setState('params', $appParams);
// Set the filters based on the module params
$articles->setState('list.start', 0);
$articles->setState('list.limit', (int) $params->get('count', 0));
$articles->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$articles->setState('filter.access', $access);
// Prep for Normal or Dynamic Modes
$mode = $params->get('mode', 'normal');
switch ($mode)
{
case 'dynamic':
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content') {
switch($view)
{
case 'category':
$catids = array($app->input->getInt('id'));
break;
case 'categories':
$catids = array($app->input->getInt('id'));
break;
case 'article':
if ($params->get('show_on_article_page', 1)) {
$article_id = $app->input->getInt('id');
$catid = $app->input->getInt('catid');
if (!$catid) {
// Get an instance of the generic article model
$article = JModelLegacy::getInstance('Article', 'ContentModel', array('ignore_request' => true));
$article->setState('params', $appParams);
$article->setState('filter.published', 1);
$article->setState('article.id', (int) $article_id);
$item = $article->getItem();
$catids = array($item->catid);
}
else {
$catids = array($catid);
}
}
else {
// Return right away if show_on_article_page option is off
return;
}
break;
case 'featured':
default:
// Return right away if not on the category or article views
return;
}
}
else {
// Return right away if not on a com_content page
return;
}
break;
case 'normal':
default:
$catids = $params->get('catid');
$articles->setState('filter.category_id.include', (bool) $params->get('category_filtering_type', 1));
break;
}
// Category filter
if ($catids) {
if ($params->get('show_child_category_articles', 0) && (int) $params->get('levels', 0) > 0) {
// Get an instance of the generic categories model
$categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true));
$categories->setState('params', $appParams);
$levels = $params->get('levels', 1) ? $params->get('levels', 1) : 9999;
$categories->setState('filter.get_children', $levels);
$categories->setState('filter.published', 1);
$categories->setState('filter.access', $access);
$additional_catids = array();
foreach($catids as $catid)
{
$categories->setState('filter.parentId', $catid);
$recursive = true;
$items = $categories->getItems($recursive);
if ($items)
{
foreach($items as $category)
{
$condition = (($category->level - $categories->getParent()->level) <= $levels);
if ($condition) {
$additional_catids[] = $category->id;
}
}
}
}
$catids = array_unique(array_merge($catids, $additional_catids));
}
$articles->setState('filter.category_id', $catids);
}
// Ordering
$articles->setState('list.ordering', $params->get('article_ordering', 'a.ordering'));
$articles->setState('list.direction', $params->get('article_ordering_direction', 'ASC'));
// New Parameters
$articles->setState('filter.featured', $params->get('show_front', 'show'));
$articles->setState('filter.author_id', $params->get('created_by', ""));
$articles->setState('filter.author_id.include', $params->get('author_filtering_type', 1));
$articles->setState('filter.author_alias', $params->get('created_by_alias', ""));
$articles->setState('filter.author_alias.include', $params->get('author_alias_filtering_type', 1));
$excluded_articles = $params->get('excluded_articles', '');
if ($excluded_articles) {
$excluded_articles = explode("\r\n", $excluded_articles);
$articles->setState('filter.article_id', $excluded_articles);
$articles->setState('filter.article_id.include', false); // Exclude
}
$date_filtering = $params->get('date_filtering', 'off');
if ($date_filtering !== 'off') {
$articles->setState('filter.date_filtering', $date_filtering);
$articles->setState('filter.date_field', $params->get('date_field', 'a.created'));
$articles->setState('filter.start_date_range', $params->get('start_date_range', '1000-01-01 00:00:00'));
$articles->setState('filter.end_date_range', $params->get('end_date_range', '9999-12-31 23:59:59'));
$articles->setState('filter.relative_date', $params->get('relative_date', 30));
}
// Filter by language
$articles->setState('filter.language', $app->getLanguageFilter());
$items = $articles->getItems();
// Display options
$show_date = $params->get('show_date', 0);
$show_date_field = $params->get('show_date_field', 'created');
$show_date_format = $params->get('show_date_format', 'Y-m-d H:i:s');
$show_category = $params->get('show_category', 0);
$show_hits = $params->get('show_hits', 0);
$show_author = $params->get('show_author', 0);
$show_introtext = $params->get('show_introtext', 0);
$introtext_limit = $params->get('introtext_limit', 100);
// Find current Article ID if on an article page
$option = $app->input->get('option');
$view = $app->input->get('view');
if ($option === 'com_content' && $view === 'article') {
$active_article_id = $app->input->getInt('id');
}
else {
$active_article_id = 0;
}
// Prepare data for display using display options
foreach ($items as &$item)
{
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid ? $item->catid .':'.$item->category_alias : $item->catid;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$menuitems = $menu->getItems('link', 'index.php?option=com_users&view=login');
if (isset($menuitems[0]))
{
$Itemid = $menuitems[0]->id;
}
elseif ($app->input->getInt('Itemid') > 0)
{
// Use Itemid from requesting page only if there is no existing menu
$Itemid = $app->input->getInt('Itemid');
}
$item->link = JRoute::_('index.php?option=com_users&view=login&Itemid='.$Itemid);
}
// Used for styling the active article
$item->active = $item->id == $active_article_id ? 'active' : '';
$item->displayDate = '';
if ($show_date) {
$item->displayDate = JHTML::_('date', $item->$show_date_field, $show_date_format);
}
if ($item->catid) {
$item->displayCategoryLink = JRoute::_(ContentHelperRoute::getCategoryRoute($item->catid));
$item->displayCategoryTitle = $show_category ? ''.$item->category_title.'' : '';
}
else {
$item->displayCategoryTitle = $show_category ? $item->category_title : '';
}
$item->displayHits = $show_hits ? $item->hits : '';
$item->displayAuthorName = $show_author ? $item->author : '';
if ($show_introtext) {
$item->introtext = JHtml::_('content.prepare', $item->introtext, '', 'mod_articles_category.content');
$item->introtext = self::_cleanIntrotext($item->introtext);
}
$item->displayIntrotext = $show_introtext ? self::truncate($item->introtext, $introtext_limit) : '';
$item->displayReadmore = $item->alternative_readmore;
}
return $items;
}
public static function _cleanIntrotext($introtext)
{
$introtext = str_replace('<p>', ' ', $introtext);
$introtext = str_replace('</p>', ' ', $introtext);
$introtext = strip_tags($introtext, '<a><em><strong>');
$introtext = trim($introtext);
return $introtext;
}
/**
* Method to truncate introtext
*
* The goal is to get the proper length plain text string with as much of
* the html intact as possible with all tags properly closed.
*
* #param string $html The content of the introtext to be truncated
* #param integer $maxLength The maximum number of charactes to render
*
* #return string The truncated string
*/
public static function truncate($html, $maxLength = 0)
{
$baseLength = strlen($html);
$diffLength = 0;
// First get the plain text string. This is the rendered text we want to end up with.
$ptString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = false);
for ($maxLength; $maxLength < $baseLength;)
{
// Now get the string if we allow html.
$htmlString = JHtml::_('string.truncate', $html, $maxLength, $noSplit = true, $allowHtml = true);
// Now get the plain text from the html string.
$htmlStringToPtString = JHtml::_('string.truncate', $htmlString, $maxLength, $noSplit = true, $allowHtml = false);
// If the new plain text string matches the original plain text string we are done.
if ($ptString == $htmlStringToPtString)
{
return $htmlString;
}
// Get the number of html tag characters in the first $maxlength characters
$diffLength = strlen($ptString) - strlen($htmlStringToPtString);
// Set new $maxlength that adjusts for the html tags
$maxLength += $diffLength;
if ($baseLength <= $maxLength || $diffLength <= 0)
{
return $htmlString;
}
}
return $html;
}
public static function groupBy($list, $fieldName, $article_grouping_direction, $fieldNameToKeep = null)
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
if (!isset($grouped[$item->$fieldName])) {
$grouped[$item->$fieldName] = array();
}
if (is_null($fieldNameToKeep)) {
$grouped[$item->$fieldName][$key] = $item;
}
else {
$grouped[$item->$fieldName][$key] = $item->$fieldNameToKeep;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
return $grouped;
}
public static function groupByDate($list, $type = 'year', $article_grouping_direction, $month_year_format = 'F Y')
{
$grouped = array();
if (!is_array($list)) {
if ($list == '') {
return $grouped;
}
$list = array($list);
}
foreach($list as $key => $item)
{
switch($type)
{
case 'month_year':
$month_year = JString::substr($item->created, 0, 7);
if (!isset($grouped[$month_year])) {
$grouped[$month_year] = array();
}
$grouped[$month_year][$key] = $item;
break;
case 'year':
default:
$year = JString::substr($item->created, 0, 4);
if (!isset($grouped[$year])) {
$grouped[$year] = array();
}
$grouped[$year][$key] = $item;
break;
}
unset($list[$key]);
}
$article_grouping_direction($grouped);
if ($type === 'month_year') {
foreach($grouped as $group => $items)
{
$date = new JDate($group);
$formatted_group = $date->format($month_year_format);
$grouped[$formatted_group] = $items;
unset($grouped[$group]);
}
}
return $grouped;
}
}
It looks like my issue was really specific to the project I am working on. If anyone happens to find this or wants to accomplish something similar, read on.
Decided to accomplish what I was doing using a JDatabase query. To retrieve the articles using the category alias, I queried the DB to match the alias I was giving the query to the category ID. Then joined the content table to get the article information.
All the information you need to make a proper JDatabase query can be found here: http://docs.joomla.org/Accessing_the_database_using_JDatabase

Categories