Pagination in CodeIgniter, need to disable query strings so we can cache - codeigniter

We have a CI installation that has the following setting in our config...
$config['enable_query_strings'] = TRUE;
We need this in order for another area of our application to run correctly with a third party API. What's happening, however, is that pagination is defaulting to a query string method of doing pagination, which doesn't play well with caching.
Right now, they look like this...
http://localhost/something/?&page=6
It's not playing well with caching, mainly because every page URL is the same page to CI. My goal is to get switched over to the below example without messing with global settings for the rest of my application.
I've been trying for hours to find a way to disable the above setting only within this single part of the application, so that we can properly have separate URLs for the pagination, like this...
http://localhost/something/1
http://localhost/something/2
http://localhost/something/3
So far, I have been unable to overide that setting for this controller, and honestly, I'm not sure there's even a way to actually do it. Any help is appreciated. There's got to be some method of disabling a feature for a single controller somehow.

Could you use routing?
$route['something/page/(:num)'] = "something?&page=$1";
edit: to turn off pagination query strings with $config['enable_query_strings'] = TRUE;
system/libraries/Pagination.php
~line 134
change
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != 0)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
to
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
~line 196
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
to
$this->base_url = rtrim($this->base_url, '/') .'/';
that might do it. Or maybe better form would be to hook into the page...

Simple solution...
$this->config->set_item('enable_query_strings',FALSE);
Just put this before you call your pagination logic in the controller. Thanks go to Taftse in the #codeigniter IRC channel for this simple override.

Related

Setting .SFUI-* fonts in Xamarin appears to correctly use the font extension to convert but still an warning error occurs

My code is setting to use the System font like this:
Current.Resources["Default-Light"] = Device.RuntimePlatform == Device.iOS ?
".SFUI-Light" :
"Roboto-Light.ttf#Roboto-Light";
Current.Resources["Default-Medium"] = Device.RuntimePlatform == Device.iOS ?
".SFUI-Medium" :
"Roboto-Medium.ttf#Roboto-Medium";
Current.Resources["Default-Light"] = Device.RuntimePlatform == Device.iOS ?
".SFUI-Light" :
"Roboto-Light.ttf#Roboto-Light";
Current.Resources["Default-Bold"] = Device.RuntimePlatform == Device.iOS ?
".SFUI-Bold" :
"Roboto-Bold.ttf#Roboto-Bold";
I understand that there's a concern when people use .SFUI-*.
However I also see this extension in the current XF code:
if (family.StartsWith(".SFUI", System.StringComparison.InvariantCultureIgnoreCase))
{
var fontWeight = family.Split('-').LastOrDefault();
if (!string.IsNullOrWhiteSpace(fontWeight) && System.Enum.TryParse<UIFontWeight>(fontWeight, true, out var uIFontWeight))
{
result = UIFont.SystemFontOfSize(size, uIFontWeight);
return result;
}
result = UIFont.SystemFontOfSize(size, UIFontWeight.Regular);
return result;
}
if(result == null)
result = UIFont.FromName(family, size);
if (result != null)
return result;
here:
https://github.com/xamarin/Xamarin.Forms/blob/main/Xamarin.Forms.Platform.iOS/Extensions/FontExtensions.cs
So, why does this message appear?
2020-07-03 00:30:19.911 J.iOS[5130:1664473] CoreText note: Client
requested name ".SFUI-Bold", it will get TimesNewRomanPSMT rather than
the intended font. All system UI font access should be through proper
APIs such as CTFontCreateUIFontForLanguage() or +[UIFont
systemFontOfSize:].
Should the XF iOS extension not have already done the conversion and if that's the case why is the message appearing in the logs?
Bonus question: how can I stop this happening? Can I make my own font extension for this that gets called first.
For reference:
Here is where I am using the fonts:
if(newValue != null && (bool)newValue)
{
DeckGridTemplate deckGridTemplate = bindable as DeckGridTemplate;
deckGridTemplate.TL.FontFamily = (string)Application.Current.Resources["Default-Medium"];
}
else
{
DeckGridTemplate deckGridTemplate = bindable as DeckGridTemplate;
deckGridTemplate.TL.FontFamily = (string)Application.Current.Resources["Default-Regular"];
}
This sounds like a warning that Apple is issuing just to "scary you". There is a similar comment on a GitHub issue about this topic. As you can see, user esenciadev is having the same question. I have tagged him to see if there's any movement on the subject and will reply back here when any. For now, I don't think that this should be an issue, since you are displaying the desired font.
As for the custom code to intersept this behaviour. Unfortunately, you can't write such middleware, since this is deep into Xamarin. You have chosen to not import any fonts and just use the system ones. You can only set the in your xaml/cs and the platform will do the rest - checks, warnings, etc.

How to prevent additional page requests after response sent

I have configured a listener on kernel.request which sets a new response with redirect when the session time has reached a certain value. The listener works fine and redirects to a certain page, on the next request, after the session has ended. But my problem is on the page I have many links and if I press multiple times the same link, the initial request with the redirect is cancelled/stopped and a new request is made with the last link pressed and so it passes my redirect even though the session has ended and is destroyed. So, my question is how to prevent additional requests/link presses after the firs request is made?
Here is my code:
public function onKernelRequestSession(GetResponseEvent $event)
{
$request = $event->getRequest();
$route = $request->get('_route');
$session = $request->getSession();
if ((false === strpos($route, '_wdt')) && ($route != null)) {
$session->start();
$time = time() - $session->getMetadataBag()->getCreated();
if ($route != 'main_route_for_idle_page') {
if (!$session->get("active") && $route == 'main_route_for_site_pages') {
$session->invalidate();
$session->set("active", "1");
} else {
if ($time >= $this->sessionTime) {
$session->clear();
$session->invalidate();
$event->setResponse(new RedirectResponse($this->router->generate('main_route_for_idle_page')));
}
}
} else {
if ($session->get("activ")) {
$session->clear();
$session->invalidate();
}
}
}
}
Thak you.
Idea #1: Simple incremental counter
Each request sends sequence number as param which is being verified as expected at the server.
Server increments the number and sends it back via response
the new number is used in future requests
Basically, if server expects the SEQUENCE number to be 2 and client sends 1 the request is to be rejected.
Idea #2: Unique hash each time
Similar to the idea above, but uses unique hashes to eliminate predictive nature of incremental sequence.
I resolved the issue using JQuery: when a link was pressed I disabled the other ones and so only one request is made from the page:
var isClicked = false;
$(".menu-link").click(function(e) {
if(!isClicked) {
isClicked = true;
} else {
e.preventDefault();
}
});
Thanks.

CI Route Issue Not Getting Variable

I'm having an issue with this route and not sure what my problem is exactly.
My page is located at http://www.kansasoutlawwrestling.com/kowmanager/pmsystem/viewmessage/1 where 1 is the message id.
I set up a route to look like
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
and I'm still getting a error message like this
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Pmsystem::viewmessage()
Filename: controllers/pmsystem.php
Line Number: 76
// View A Message
function viewmessage($message_id)
{
//Config Defaults Start
$msgBoxMsgs = array();//msgType = dl, info, warn, note, msg
$cssPageAddons = '';//If you have extra CSS for this view append it here
$jsPageAddons = '<script src='.base_url().'../assets/js/cpanel/personalmessages.js></script><script src='.base_url().'assets/js/mylibs/jwysiwyg/jquery.wysiwyg.js></script>';//If you have extra JS for this view append it here
$metaAddons = '';//Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = '';//alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if( ! $this->uri->segment(3))
{
redirect('error', 'refresh');
}
}
else
{
redirect('login', 'refresh');
}
$bodyContent = 'viewpm';//which view file
$bodyType = "full";//type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if(count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show', 'msgs' =>$msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons;//if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons;//if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons;//if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags();//defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle;//defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->data['user_data'] = $this->users->getUserByUserId($this->session->userdata('user_id'));
$this->data['users'] = $this->loggedin->getUserList();
$this->data['personal_messages'] = array($this->pmmodel->getTotalMessages($this->session->userdata('user_id')), $this->pmmodel->getTotalUnreadMessages($this->session->userdata('user_id')), $this->pmmodel->getLast5Messages($this->session->userdata('user_id')));
$this->data['messages'] = array($this->pmmodel->getInboxMessages($this->session->userdata('user_id')), $this->pmmodel->getSentMessages($this->session->userdata('user_id')));
//$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
$this->load->view('cpanel/index', $this->data);
}
UPDATE
// Checks to see if a session is active for user and shows corresponding view page
if (!$this->loggedin->chkLoginStatus() === FALSE)
{
if (!is_numeric($this->uri->segment(3)))
{
$this->data['message_data'] = 'Invalid message id!';
}
else
{
$this->data['message_data'] = $this->pmmodel->getPmMessage($this->uri->segment(3));
}
$bodyContent = 'viewpm';//which view file
}
else
{
redirect('login', 'refresh');
}
$bodyType = "full";//type of template
This route is unnecessary - it doesn't change anything.
$route['pmsystem/viewmessage/(:num)'] = 'pmsystem/viewmessage/$1';
You can remove that route. The problem is here:
function viewmessage($message_id) // no default value means it's required
{
// your code
}
Your controller methods literally accept user input as arguments (whatever's in the address bar). You always have to account for those required arguments not being present in CI controller methods.
function viewmessage($message_id = NULL)
{
if ( ! $message_id) show_404();
// your code
}
This will silence the errors and show a 404 if the required $message_id is not there. Additionally, $this->uri->segment(3) is unnecessary because it should have the same value as $message_id.
I highly discourage redirecting to an error page when you really want a 404, but that's up to you. It sure doesn't help the user realize their mistake when the address is lost after the redirect, and you're sending the wrong HTTP headers by doing so.

Reopen a complete/closed order in Magento?

Is there a way to programmatically reopen an order in Magento that has already reached complete or closed status? I have the following code which works for changing the status of an order, but I can't get it to work for complete or closed orders.
// connect to magento
require_once('app/Mage.php');
umask(022);
Mage::app();
// check admin credentials
Mage::getSingleton('core/session', array('name' => 'adminhtml'));
$admin = Mage::getSingleton('admin/session');
if ( $admin->isLoggedIn() ) {
// update order status
$orderIncrementId = "100000001";
$order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
}
I got the current code here. On that page it says that it was tested with Magento 1.3.2.4, but I'm using Magento 1.6.x. Maybe that's the issue?
Let me know if I need to provide more detail, and thanks for any help you can offer.
I don't think that you're having a Magento version issue here.
Under specific circumstances Magento simply just does not allow to switch the state of an order back to Mage_Sales_Model_Order::STATE_PROCESSING.
For example, usually you cannot save a Mage_Sales_Model_Order::STATE_PROCESSING state to any order, which already has had refunds (creditmemos). Neither in 1.3.2.4, nor in 1.6.x.
This is by-design.
Look at Mage_Sales_Model_Order::_checkState() to see under which circumstances Magento forces resetting the order state to STATE_COMPLETE or STATE_CLOSED, respectively.
protected function _checkState()
{
if (!$this->getId()) {
return $this;
}
$userNotification = $this->hasCustomerNoteNotify() ? $this->getCustomerNoteNotify() : null;
if (!$this->isCanceled()
&& !$this->canUnhold()
&& !$this->canInvoice()
&& !$this->canShip()) {
if (0 == $this->getBaseGrandTotal() || $this->canCreditmemo()) {
if ($this->getState() !== self::STATE_COMPLETE) {
$this->_setState(self::STATE_COMPLETE, true, '', $userNotification);
}
}
/**
* Order can be closed just in case when we have refunded amount.
* In case of "0" grand total order checking ForcedCanCreditmemo flag
*/
elseif (floatval($this->getTotalRefunded()) || (!$this->getTotalRefunded()
&& $this->hasForcedCanCreditmemo())
) {
if ($this->getState() !== self::STATE_CLOSED) {
$this->_setState(self::STATE_CLOSED, true, '', $userNotification);
}
}
}
if ($this->getState() == self::STATE_NEW && $this->getIsInProcess()) {
$this->setState(self::STATE_PROCESSING, true, '', $userNotification);
}
return $this;
}
To answer your question: you could achieve what you're trying to do by overriding the _checkState() method with your own method, which allows to set STATE_PROCESSING.
Be aware though, that this most probably will cause the creation of new state contexts which Magento neither knows nor expects or can handle.
If your changes wreak havoc, don't blame me. You've been warned^^

Simple Login Attempt counter using MVC 3 and Ajax

Ok so this is driving me nuts. I am probably tired and the answer is looking at me.
public ActionResult _Login(LoginViewModel loginViewModel)
{
if (User.Identity.IsAuthenticated)
{
return JavaScript("window.location=" + "'" + loginViewModel.ReturntUrl + "'");
}
if (ModelState.IsValid)
{
if (Session["loginCount"] == null) //setup the session var with 0 count
{
Session.Add("loginCount", 0);
}
_loginStatus = _authenticationService.Authenticate(loginViewModel.SiteLoginViewModel.EmailAddress,
loginViewModel.SiteLoginViewModel.Password);
if(!_loginStatus.UserExists)
{
ModelState.AddModelError("SiteLoginViewModel.EmailAddress", _loginStatus.ErrorMessage);
return PartialView();
}
// This will only be true if the user types in the correct password
if(!_loginStatus.IsAuthenticated)
{
Session["loginCount"] = (int)Session["loginCount"] + 1;
Response.Write(Session["loginCount"]); // Counter is incremented twice!!!!
//_userService.SetInvalidLoginAttempts(loginViewModel.SiteLoginViewModel.EmailAddress, 1);
ModelState.AddModelError("SiteLoginViewModel.EmailAddress", _loginStatus.ErrorMessage);
return PartialView();
}
// DELETE ANY OPENID Cookies
var openidCookie = new HttpCookie("openid_provider");
if (openidCookie.Value != null)
{
openidCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(openidCookie);
}
_userService.SetInvalidLoginAttempts(loginViewModel.SiteLoginViewModel.EmailAddress, 0);
SetAuthTicket(loginViewModel.SiteLoginViewModel.EmailAddress, _userService.GetUserId(loginViewModel.SiteLoginViewModel.EmailAddress),
loginViewModel.SiteLoginViewModel.RemeberLogin);
if (!string.IsNullOrEmpty(loginViewModel.ReturntUrl))
{
return JavaScript("window.location=" + "'" + loginViewModel.ReturntUrl + "'");
}
return JavaScript("location.reload(true)");
}
return PartialView();
}
This almost seems that the request is being processed twice however when i step through with the debugger I only see it once. Please ignore the non important parts of the ActionMethod
This looks like you are tying to code for stuff that you automatically get with .Net's Membership provider.
Your first line "User.Identity.IsAuthenticated" looks like you are using part of membership provider but it would seem the rest is trying to code around it.
Also, why are you returning javascript to direct the user's browser to a new URL? Regarless of what .net platform you are on there are plenty of ways to redirect the user's browser without having to return raw javascript, which in my book is REALLY BAD.
##
This fixed the problem and will be removed rather than commented out. Including this twice is very bad obviously :)

Resources