How to clear all cart items in magento cart (In all PCs from all over world) - magento-1.9

When i run a script then clear cart items from all PCs which already added a cart item(s).

try below code.
protected $quoteFactory;
public function __construct(
...
\Magento\Quote\Model\QuoteFactory $quoteFactory,
....
) {
....
$this->quoteFactory = $quoteFactory;
....
}
$quoteCollection = $this->quoteFactory->create()->getCollection()
->addFieldToFilter('is_active', 1);
foreach ($quoteCollection as $item) {
$item->delete();
}

Run the following Query :
Delete FROM quote WHERE is_active=1 AND reserved_order_id IS NULL
Now run following command from Your Magento Root directory :
Truncate persistent_session

Related

Delete all subdirectory except a subtree

I'm new.
I'm trying to create a gradle task that delete all directory except a subset of those.
this is my situation
src/main/java
test/package1
test/package2
com/package3
com/package4
it/package5
and here my code:
task deleteFolders(type: Delete){
group = 'build'
if(currentTask == "deleteFolders"){
def ftree=fileTree(dir: "$javaDir").exclude('test/package2')
ftree.exclude('test/package1')
ftree.visit { FileVisitDetails details ->
delete details.file
}
}
but this code delete everything, also the packages inside "exclude".
trying with this other code
task deleteFolders{//(type: Delete)
group = 'build'
if(currentTask == "deleteFolders"){
delete fileTree(dir: "$javaDir").matching {
exclude 'test/package1/**'
exclude 'test/package2/**'
}
}
everything work but the com folder is still there empty (i want to remove it).
so, can someone help me to reach this result ?
src/main/java
test/package1
test/package2
thanks a lot Leo
Maybe you can try the way as follows:
deleteTask = { dealFilePath, destFileName ->
file(dealFilePath).list().each {
f ->
if (!f.contains(destFileName)) {
delete "${dealFilePath}/${f}"
}
}
}

Event to track quote changes in magento

I want an observer to track changes in Quote like when removing products, updating, adding product from frontend and backend as well. This observer should run after magento native code.
There are many events like below which are executed during quote but I am not sure which observer will be fit for my requirement--
sales_quote_remove_item
sales_quote_add_item
sales_quote_product_add_after
sales_quote_item_collection_products_after_load
checkout_cart_add_product_complete
checkout_cart_save_before
checkout_cart_save_after
etc...
You may not be able to achieve this by using a single event , but instead you could write a single observer and call this observer for multiple events..
<sales_quote_product_add_after>
<observers>
<sales_quote_product_add>
<type>singleton</type>
<class>my_module/observer</class>
<method>myfunction</method>
</sales_quote_product_add>
</observers>
</sales_quote_product_add_after>
<checkout_cart_add_product_complete>
<observers>
<checkout_cart_add_product>
<type>singleton</type>
<class>my_module/observer</class>
<method>myfunction</method>
</checkout_cart_add_product>
</observers>
</checkout_cart_add_product_complete>
Events you can see
sales_quote_remove_item
sales_quote_item_qty_set_after
sales_quote_product_add_after
https://www.nicksays.co.uk/magento-events-cheat-sheet-1-9/
You can find events on your own
Modify Mage.php in app folder
public static function dispatchEvent($name, array $data = array())
{
Varien_Profiler::start('DISPATCH EVENT:'.$name);
$result = self::app()->dispatchEvent($name, $data);
Varien_Profiler::stop('DISPATCH EVENT:'.$name);
//log your event
Mage::log("Event name is $name",null,'event.log');
return $result;
}
Do your action, like add item to cart, remove / update quantity and then check event.log in var/log

MvxTabsFragmentActivity - Remove tabs

Is there any way to remove tabs from an MvxTabsFragmentActivity-inherited class? I mean, currently there's only AddTab<T>() method for adding tabs. But, what if I want to remove tabs?
TIA,
Pap
No - MvxTabsFragmentActivity doesn't provide any RemoveTab functionality currently.
The source for this activity is https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Droid.Fragging/MvxTabsFragmentActivity.cs - you should be able to use this as a starting point for your own needs.
UPDATE:
After following #Stuart's advice and-as I mentioned in my comment below-I added the source code for the MvxTabsFragmentActivity class to my project and added the following method-to remove all tabs-which was all I wanted:
public void RemoveAllTabs()
{
// First, detach the curent tab using SupportFragmentManager object.
if (_currentTab != null)
{
var tag = _currentTab.CachedFragment.Tag;
_currentTab.CachedFragment = SupportFragmentManager.FindFragmentByTag( tag );
if (_currentTab.CachedFragment != null && !_currentTab.CachedFragment.IsDetached)
{
var ft = SupportFragmentManager.BeginTransaction();
ft.Detach( _currentTab.CachedFragment );
ft.Commit();
SupportFragmentManager.ExecutePendingTransactions();
}
}
// Second remove all tabs from TabHost object
if (_tabHost != null)
_tabHost.ClearAllTabs();
// And lastly, empty our _lookup table(actually a Dictionary).
_lookup.Clear();
_currentTab = null; // Clear the current tab
}
I guess if someone wanted to have a specific tab removed he could use the SupportFragmentManager object and have something like this:
public void RemoveTab( string tag )
{
var fragment = SupportFragmentManager.FindFragmentByTag( tag );
if (fragment != null && ! fragment.IsDetached)
{
var ft = SupportFragmentManager.BeginTransaction();
ft.Detach( fragment );
ft.Commit();
SupportFragmentManager.ExecutePendingTransactions();
//_tabHost.TabWidget.RemoveView( fragment.View ); // Neither this..
//_tabHost.RemoveView( fragment.View ); // .. or this removed the tab from the Tabhost.
}
}
However, although the above code was successful at removing the fragment/view inside the tab, the tab itself remained-showing a blank/empty tab. I couldn't find a TabHost.RemoveTab() or TabHost.TabWidget.RemoveTab() methods and the TabHost.RemoveView()/TabHost.TabWidget.RemoveView() did not work.
Notes: I renamed the MvxTabsFragmentActivity to something else and included all copyright notices at the top of the class in my project. Thanks again to #Stuart.

Magento: Disable module for any particular store

Suppose, I have 3 stores.
I want to disable a module in Store 2. I only want it to be enabled in Store 1 and Store 3.
I see that I can do it by:-
Going to System -> Configuration -> Advanced
Selecting desired store from Current Configuration Scope dropdown list.
But this does not work fully.
And, I also don't want to check store in the module code itself or create system configuration field for the module to check/uncheck store to enable/disable.
What I am expecting is by adding some code in app/etc/modules/MyNamespace_MyModule.xml. Can we do it this way?
To disable a module on the store scope, I've found it's possible to do it like this:
Move app/code/core/Mage/Core/Model/Config.php to app/code/local/Mage/Core/Model/Config.php
Inside Config.php find the method "loadModulesConfiguration" Don't change anything, but add the following code to make the method look like this.
public function loadModulesConfiguration($fileName, $mergeToObject = null, $mergeModel=null)
{
$disableLocalModules = !$this->_canUseLocalModules();
if ($mergeToObject === null) {
$mergeToObject = clone $this->_prototype;
$mergeToObject->loadString('<config/>');
}
if ($mergeModel === null) {
$mergeModel = clone $this->_prototype;
}
$modules = $this->getNode('modules')->children();
foreach ($modules as $modName=>$module) {
if ($module->is('active')) {
// Begin additional code
if((bool)$module->restricted) {
$restricted = explode(',', (string)$module->restricted);
$runCode = (isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default');
if(in_array($runCode, $restricted)) {
continue;
}
}
// End additional code
if ($disableLocalModules && ('local' === (string)$module->codePool)) {
continue;
}
if (!is_array($fileName)) {
$fileName = array($fileName);
}
foreach ($fileName as $configFile) {
$configFile = $this->getModuleDir('etc', $modName).DS.$configFile;
if ($mergeModel->loadFile($configFile)) {
$mergeToObject->extend($mergeModel, true);
}
}
}
}
return $mergeToObject;
}
The new code will cause the method to also check for a new node in the module xml file, <restricted>. If the node exists, the value would be a comma separated list of store codes that you do NOT want the module to load on. If you have multiple stores, the $_SERVER variable "MAGE_RUN_CODE" should be set with the current store code. If it's not set, the script will fallback to assuming the store code is "default" which is what it is by default unless for some bizarre reason you decide to change that in the backend.
A modules xml file could then look like this:
<?xml version="1.0"?>
<config>
<modules>
<MyPackage_MyModule>
<active>false</active>
<restricted>mystore1,mystore4,mystore5</restricted>
<codePool>local</codePool>
</MyPackage_MyModule>
</modules>
</config>
With this, the module will not even load while on the stores with a store code of mystore1, mystore4, or mystore5. The <restricted> tag is entirely optional, if you omit it the module will load as it normally would.
This configuration just disables module output in layout for frontend, but module controllers, event observers, admin pages, etc still working.
Also don't forget to specify your module name in layout files definition, otherwise all the layout file content will be loaded for a particular store:
<config>
<layout>
<module_alias module="Module_Name">
<file>yourlayoutfile.xml</file>
</module_alias>
</layout>
</config>
If you are developing a module and want to disable full its functionality on the frontent for a particular store, then you should create a configuration field of "Yes/No" type and check its value via Mage::getStoreConfigFlag('config/field/path') in your module code.
I was using Eric solution for a while. In my case I disabled certain module responsible for Layered Navigation in one of my shops - thus returning to default Layered Navigation behaviour.
And it looked like its working, but after a while I've noticed that layered navigation options stopped to appear where they should. Soon I've noticed that in fact the module that should not work on this shop continued to work. Then I realized that when I disable configuration cache Eric's solution works, but after enabling it again it stops.
After a while I realized it had to work that way, with configuration cache enabled, because Eric's solution includes (or not) specified config files in global xml only while this xml is being generated. Then its cached and called from cache only. So when it was generated from site which should use some module it was included, and then used also on site which wasn't suppose to use it.
Anyway I worked out another solution, based on Eric's code (using restricted in modules config). I thought Magento should decide what to load when class is being requested. Then it could check what is current MAGE_RUN_CODE and use it dynamically.
There is a method in Mage_Core_Model_Config which is responsible for getting class name: getGroupedClassName.
Here is the code I used there:
if (strpos($className, 'Pneumatig_') !== false) {
$var = substr($className, 0, strpos($className, '_', strpos($className, '_') + 1));
if (isset($this->_xml->modules->$var)) {
if ((bool)$this->_xml->modules->$var->restricted === true) {
$code = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default';
if (strpos((string)$this->_xml->modules->$var->restricted, $code) !== false) {
$className = '';
}
}
}
}
This Pneumatig condition is because all my modules start from Company name, so i wanted to avoid not necessary processing, but its optional, code should work without it, or you can change it to anything else.
Then I get actual module name [Company]_[Module], and then check if its enabled in _xml (which is current configuration object). If it is restricted I clear $className so it force Magento to load the default in next line.
And this code is added just before is empty condition:
// Second - if entity is not rewritten then use class prefix to form class name
if (empty($className)) {
if (!empty($config)) {
$className = $config->getClassName();
}
if (empty($className)) {
$className = 'mage_'.$group.'_'.$groupType;
}
if (!empty($class)) {
$className .= '_'.$class;
}
$className = uc_words($className);
}
$this->_classNameCache[$groupRootNode][$group][$class] = $className;
return $className;
And for your convenience i paste whole getGroupedClassName code:
public function getGroupedClassName($groupType, $classId, $groupRootNode=null)
{
if (empty($groupRootNode)) {
$groupRootNode = 'global/'.$groupType.'s';
}
$classArr = explode('/', trim($classId));
$group = $classArr[0];
$class = !empty($classArr[1]) ? $classArr[1] : null;
if (isset($this->_classNameCache[$groupRootNode][$group][$class])) {
return $this->_classNameCache[$groupRootNode][$group][$class];
}
$config = $this->_xml->global->{$groupType.'s'}->{$group};
// First - check maybe the entity class was rewritten
$className = null;
if (isset($config->rewrite->$class)) {
$className = (string)$config->rewrite->$class;
} else {
/**
* Backwards compatibility for pre-MMDB extensions.
* In MMDB release resource nodes <..._mysql4> were renamed to <..._resource>. So <deprecatedNode> is left
* to keep name of previously used nodes, that still may be used by non-updated extensions.
*/
if (isset($config->deprecatedNode)) {
$deprecatedNode = $config->deprecatedNode;
$configOld = $this->_xml->global->{$groupType.'s'}->$deprecatedNode;
if (isset($configOld->rewrite->$class)) {
$className = (string) $configOld->rewrite->$class;
}
}
}
//START CHECKING IF CLASS MODULE IS ENABLED
if (strpos($className, 'Pneumatig_') !== false) {
$var = substr($className, 0, strpos($className, '_', strpos($className, '_') + 1));
if (isset($this->_xml->modules->$var)) {
if ((bool)$this->_xml->modules->$var->restricted === true) {
$code = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default';
if (strpos((string)$this->_xml->modules->$var->restricted, $code) !== false) {
$className = '';
}
}
}
}
//END CHECKING IF CLASS MODULE IS ENABLED
// Second - if entity is not rewritten then use class prefix to form class name
if (empty($className)) {
if (!empty($config)) {
$className = $config->getClassName();
}
if (empty($className)) {
$className = 'mage_'.$group.'_'.$groupType;
}
if (!empty($class)) {
$className .= '_'.$class;
}
$className = uc_words($className);
}
$this->_classNameCache[$groupRootNode][$group][$class] = $className;
return $className;
}
My clients install of Magento 1.8.1.0 has a problematic module that breaks another site's menu on a multi-store setup. The solution above posted by Eric Hainer didn't work for this install, so I altered it slightly:
Instead of using $_SERVER['MAGE_RUN_CODE'], I used $_SERVER['SERVER_NAME']. Worked like a charm. :)
So instead of:
$runCode = (isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'default');
use:
$runCode = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'www.site1.com');
and instead of:
<restricted>mystore1,mystore4,mystore5</restricted>
use:
<restricted>www.site2.com,www.site3.com</restricted>
obviously changing "www.site1.com", "www.site2.com", and "www.site3.com" with your own locations.
Thanks for the idea Eric :)
Also interesting solution ,
http://inchoo.net/ecommerce/magento/how-to-activatedeactivate-magento-module-per-a-website-level/

CakePHP - get last query run

I want to get the last query CakePHP ran. I can't turn debug on in core.php and I can't run the code locally. I need a way to get the last sql query and log it to the error log without effecting the live site. This query is failing but is being run.
something like this would be great:
$this->log($this->ModelName->lastQuery);
Thanks in advance.
For Cake 2.0, the query log is protected so this will work
function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
Tested in CakePHP v2.3.2
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
In CakePHP 1.x, the data you want is accessible in DataSource::_queriesLog. Cake doesn't really provide a getter method for this member, but the underlying language being PHP, nothing stops you from doing the following:
In app/app_model.php:
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
return end($logs);
}
You can use this inline.
$dbo = $this->Model->getDatasource();
// store old state
$oldStateFullDebug = $dbo->fullDebug;
// turn fullDebug on
$dbo->fullDebug = true;
// Your code here! eg.
$this->Model->find('all');
// write to logfile
// use print_r with second argument to return a dump of the array
Debugger::log(print_r($dbo->_queriesLog, true));
// restore fullDebug
$dbo->fullDebug = $oldStateFullDebug;
Simple you can use showLog() function
var_dump($this->YourModel->getDataSource()->showLog());
This is a very late answer, i know, but for whoever needs this in the future, you can always restrict setting debug to your IP, For example:
Configure::write('debug', 0);
if($_SERVER["REMOTE_ADDR"] == '192.168.0.100'){
Configure::write('debug', 2); //Enables debugging only for your IP.
}
Combination of Matt's and blavia's solution (works when debug is not 2):
$dbo = $this->Model->getDatasource();
$oldStateFullDebug = $dbo->fullDebug;
$dbo->fullDebug = true;
// find or whatever...
$this->Model->find("all");
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
CakeLog::write("DBLog", $lastLog['query']);
$dbo->fullDebug = $oldStateFullDebug;
Having a quick skim of the book, cakephp api getLog you could turn on logTransaction. Although having not used it, I'm not sure how it will perform.
Otherwise you could experiment with FirePHP and here is the a guide for it,
You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.
Hopefully something might give you a lead. :)
You can use this:
$log = $this->Model->getDataSource()->getLog(false, false);
pr($log);die;
There are two methods to view the query in CakePHP.
Both methods you have to add the below one line in app/Config/core.php
Configure::write('debug', 2);
First methods :
debug($this->getLastQuery());
where you want to get the query add above line and call this function getLastQuery() on same controller using below code
public function getLastQuery() {
$dbo = $this->TModel->getDatasource(); //Here TModel is a model.what table you want to print
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
second method :
add the below line in the any Elements files.
<?php echo $this->element('sql_dump'); ?>
This will help you.
echo '<pre>';
$log = $this->YOUR_MODEL->getDataSource();
print_r($log);
exit;