Joomla Plugin not running (is installed) - joomla

I have "written" a plugin for Joomla! I say "written" because it is actually someone else's, but it was for Joomla 1.5, and I'm trying to upgrade it to run in Joomla 1.7. However, it's installed and it doesn't want to run. I have tried making it generate an error out of nothing, but it wouldn't give me anything.
I'm not even sure if it is Joomla 1.7 code or not, but I'm hoping you could help with that too.
<?php
// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
jimport('joomla.plugin.plugin');
class plgContentRegisteredTags extends JPlugin
{
function plgContentRegisteredTags (&$subject, $params)
{
parent::__construct($subject,$params);
}
function onPrepareContent ( $context, &$article, &$params, $page=0 )
{
global $mainframe;
//if ( !$published ) return true;
// define the regular expression for the bot
$regex1 = "#{reg}(.*?){/reg}#s";
$regex2 = "#{noreg}(.*?){/noreg}#s";
// perform the replacement
$article->text = preg_replace_callback(
$regex1,
create_function(
'$matches',
'global $my;
if($my->id) return $matches[1];
return "";'
),
$article->text
);
$article->text = preg_replace_callback(
$regex2,
create_function(
'$matches',
'global $my;
if(!$my->id) return $matches[1];
return "";'
),
$article->text
);
return true;
}
}
Note: it just doesn't want to run at all (no error, no code execution), even though it is enabled and installed.
Any help would be appreciated.

Plugin-ins in Joomla! are stored in plugins/plugin-type/plugin_name/ relative to the site root. Components are stored in the components/ directory.
eg. the pagebreak content plugin is found at 'plugins/content/pagebreak/' and contains the files:
plugins/content/pagebreak/pagebreak.php
plugins/content/pagebreak/pagebreak.xml
plugins/content/pagebreak/index.html // not an active file
You can read about creating a content plugin here.

Related

Server Migration fatal error on contact forms in CodeIgniter

I've been trying to pick my way through this error but I feel like I'm getting nowhere.
We're in the process of migrating a website from one server to another. All pages seem to work on the new site except for the contact form pages which appear to be trying to use 'form_helper.php'. These pages work correctly on the old server but not on the new one. I get an error of:
Fatal error: Call to undefined method CI_Loader::is_loaded() in C:\DATA\XXXX.com\www\application\helpers\form_helper.php on line 1038
Line 1038 of form_helper.php has the following on it:
if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
Any ideas would be GREATLY appreciated as I'm not that familiar with CodeIgniter.
Thanks in advance...
EDIT:
So I've worked out how to seemingly fix it... If I comment out the following code in the form_helper file, the page loads with no error:
/*if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
{
if ( ! isset($CI->$object) OR ! is_object($CI->$object))
{
return $return;
}
return $CI->$object;
}*/
Is this a bad idea? The full function now looks like this:
if ( ! function_exists('_get_validation_object'))
{
function &_get_validation_object()
{
$CI =& get_instance();
// We set this as a variable since we're returning by reference.
$return = FALSE;
/*if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
{
if ( ! isset($CI->$object) OR ! is_object($CI->$object))
{
return $return;
}
return $CI->$object;
}*/
return $return;
}
}
Make sure you have moved any array values in application/config/autoload.php from $autoload[‘plugins’] to $autoload[‘helpers’] or you will notice stuff break.
is_loaded() function is defined in Code/common.php Make sure the function is in right place.

add language constants to Joomla component javascript

My component includes a java script file:
$doc->addScript("/components/com_cam/js/cam.js");
I have several client side messages that I'd like to add with language constants, i.e.
<?php echo JText::_('COM_CAM_SEND_LABEL'); ?>
Easy enough in your front end php code like default.php but what about messages inside cam.js?
Such as my jquery validation:
messages: {
cam: {
required: "Enter a label",
minlength: jQuery.format("At least {0} characters required!"),
maxlength: jQuery.format("Maximum {0} characters allowed!")
}
}
What is the best practice for this?
In Joomla! 2.5 (since 1.6 I believe) there is JText::script() which adds support for adding language keys to a global array() so that your Javascript can access them.
First up, in your PHP you can call JText::script('COM_MYCOMPONENT_MSG1'); for each string you need translated in your Javascript.
The you can use the built-in Joomla.JText._('COM_MYCOMPONENT_MSG1') in your Javascript to retrieve it.
When you get to the point where there a lots of strings to be converted you may find it easier to just parse the javascript file at run time (in-efficient yada yada but for back-end admin screens not such a big deal).
/**
* Parses a javascript file looking for JText keys and then loads them ready for use.
*
* #param string $jsFile Path to the javascript file.
*
* #return bool
*/
public static function loadJSLanguageKeys($jsFile)
{
if (isset($jsFile))
{
$jsFile = JPATH_SITE . $jsFile;
}
else
{
return false;
}
if ($jsContents = file_get_contents($jsFile))
{
$languageKeys = array();
preg_match_all('/Joomla\.JText\._\(\'(.*?)\'\)\)?/', $jsContents, $languageKeys);
$languageKeys = $languageKeys[1];
foreach ($languageKeys as $lkey)
{
JText::script($lkey);
}
}
}
Make a helper function to build validation messages and add it to the head.
Something like bellow, just edit it to suit your needs
$messages = '(function ($) {
$.extend($.validator.messages, {
cam: {
required: "' . JText::_('COM_CAM_VALIDATION_REQUIRED') . '",
minlength: jQuery.format("' . JText::_('COM_CAM_VALIDATION_MINIMUM') . '"),
maxlength: jQuery.format("' . JText::_('COM_CAM_VALIDATION_MAXIMUM') . '")
}
});
}(jQuery));';
$doc = JFactory::getDocument();
$doc->addScriptDeclaration($messages);

Magento: ImageCdn bug? (long story)

I have some question related with Magento's free extension OnePica ImageCdn.
A broken image appear in frontend when I uploaded "corrupt image".
Ok, let's start the long story:
I notice it is happened because of ImageCdn extension and "corrupt image".
In some part of ImageCdn's code:
OnePica_ImageCdn_Helper_Image
/**
* In older versions of Magento (<1.1.3) this method was used to get an image URL.
* However, 1.1.3 now uses the getUrl() method in the product > image model. This code
* was added for backwards compatibility.
*
* #return string
*/
public function __toString()
{
parent::__toString();
return $this->_getModel()->getUrl();
}
My question is, anybody know what is the purpose of that code?
I don't understand what is the meaning of their comment above.
I think it is a bug as it always return $this->_getModel()->getUrl();
Is is really a bug or it is just my wrong interpretation?
This is what I've done so far:
I have an image dummy.jpeg
After some investigation, I just realized that is a "corrupt image".
I tested using: <?php print_r(getimagesize('dummy.jpeg')); ?>
Result:
Array
(
[0] => 200
[1] => 200
[2] => 6
[3] => width="200" height="200"
[bits] => 24
[mime] => image/x-ms-bmp
)
Of course I was surprised by the result because it looks good when I open it using Preview (on Mac OSX)
Then I open it using hex editor, the first two bytes is : BM which is BMP's identifier
I tried to upload .bmp image for product -> failed, can not select the image
I asked my colleague to upload it too (on Ubuntu), he was able to change the choices for file type into "any files". When he click "Upload Files", error message shown state that that type of file is not allowed.
What crossed on my mind is: an admin tried to upload .bmp image and failed. Then he rename it into .jpeg and successful. Though I don't get it what kind of images can be renamed without showing broken image logo (out of topic).
Those scenarios trigger an Exception, I'll break down what I've traced.
Trace of the codes:
app/design/frontend/base/default/catalog/product/view/media.phtml
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')->init($_product, 'image').'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
From that code, I know that image url is generated using: $this->helper('catalog/image')->init($_product, 'image')
I did Mage::log((string)$this->helper('catalog/image')->init($_product, 'image'));
Result:
http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
.
Mage_Catalog_Helper_Image
public function __toString()
{
try {
if( $this->getImageFile() ) {
$this->_getModel()->setBaseFile( $this->getImageFile() );
} else {
$this->_getModel()->setBaseFile( $this->getProduct()->getData($this->_getModel()->getDestinationSubdir()) );
}
if( $this->_getModel()->isCached() ) {
return $this->_getModel()->getUrl();
} else {
if( $this->_scheduleRotate ) {
$this->_getModel()->rotate( $this->getAngle() );
}
if ($this->_scheduleResize) {
$this->_getModel()->resize();
}
if( $this->getWatermark() ) {
$this->_getModel()->setWatermark($this->getWatermark());
}
Mage::log('pass');
$url = $this->_getModel()->saveFile()->getUrl();
Mage::log('not pass');
}
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
The error triggered in $this->_getModel()->saveFile()->getUrl(). In some part of the code, it will eventually reach:
Varien_Image_Adapter_Gd2
private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
{
if (null === $fileType) {
$fileType = $this->_fileType;
}
if (empty(self::$_callbacks[$fileType])) {
//reach this line -> exception thrown
throw new Exception($unsupportedText);
}
if (empty(self::$_callbacks[$fileType][$callbackType])) {
throw new Exception('Callback not found.');
}
return self::$_callbacks[$fileType][$callbackType];
}
The exception was catched in the previous code:
Mage_Catalog_Helper_Image
public function __toString()
{
...
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
...
}
the $url became:
http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg
So, it should have generated placeholder image right?
(without ImageCdn extension)
No, because
Mage_Catalog_Helper_Image was rewritten by
OnePica_ImageCdn_Helper_Image
public function __toString()
{
parent::__toString(); //the result is http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg but no variable store/process its value
return $this->_getModel()->getUrl(); //in the end it will return http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
}
In case you all already forgot the question:
Anybody know what is the purpose of that code? I don't understand what is the meaning of their comment above.
Is it really a bug or it is just my wrong interpretation?
No it isn't a bug. It's just legacy support for older Magento systems. I'm wondering, have you ever got around to snoop around earlier versions of magento (as the inline documentation comment references to, < 1.1.3)?
The gist of the matter is before Mage 1.1.3, Mage_Catalog_Helper_Image instances happen to produce URL's from to-string casts e.g.
$image = (some instance of Mage_Catalog_Helper_Image).. ;
$imageUrl = (string) $image;
__toString is probably either protected or private, i'm not sure but what I'm sure is the usual practice is to always code up this Magic Method in order to use it in a class that you are meaning to rewrite something with that expects to use this kind data cast.

White Page of Death on submit [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this error mean in PHP?
I am having an issue with the following section of code:
I can get the error notices in the validation but the next step = valid code I just get a white page, Any Ideas?
I have checked the error settings and I have set it in the public_html php.ini file and I still don't get errors
function create_sale()
{
$this->template->append_metadata( js('debounce.js', 'sales') );
$this->template->append_metadata( js('new_sale.js', 'sales') );
// -------------------------------------
// Validation & Setup
// -------------------------------------
$this->load->library('form_validation');
$this->sale_rules[1]['rules'] .= '|callback__check_slug[insert]';
$this->form_validation->set_rules( $this->sale_rules );
foreach($this->sale_rules as $key => $rule)
{
$sale->{$rule['field']} = $this->input->post($rule['field'], TRUE);
}
// -------------------------------------
// Process Data
// -------------------------------------
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
$this->template->set('sale', $sale)
->build('admin/new');
}
You said that your code is valid but you get a white page.
Most of the time when you get a white page you will simply have an error in your code.
As is the case here:
You suddenly have an endif; in your code which you don't want there.
Enable error reporting please:
Include this code in your bootstrap file:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Remember to disable this in production!
To remove the error change:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
to:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) )
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
} else {
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
redirect('admin/sales');
}
You have too many closing curly braces, remove the 'endif' in your script and it should work.
CodeIgniter is notorious for the "white screen of death".
Generally when I've run into it, it's been because of the way they set up their database error handling (it's not good). Database errors aren't handled when $db['default']['db_debug'] is set to FALSE. Any query or connection attempt that fails just returns false. Execution continues after a bad query, which can result in a white screen of death. If you're lucky, you'll get an error message in the logs in some cases, but in most you won't, as the query() function just silently returns false without logging anything.
If you set it to TRUE, then you can be in an even worse position, because any database error will automatically result in CodeIgniter calling it's own show_error() function and generating a 500 HTTP response, and you have no chance of handling it on your own.
This is the most common way to get the WSOD that I'm aware of. I haven't used the 2.0 versions of CI, but it was the case in the 1.7 versions. You may want to try setting db_debug to true in your database.php config file until you find out what's going on.
I suspect that your redirect() is failing to redirect (instead just leaving a blank page sans redirect) for some reason or another. Toss a debug message before it to check.

Magento how to stop /checkout/onepage/success/ redirecting

I need to style Magento's order success page /checkout/onepage/success/, but because it redirects when there is no order session I can't refresh the page to check my changes!
Anyone know how I can temporarily stop this redirect for testing purposes?
You can change the /app/code/core/Mage/Checkout/controllers/OnepageController.php file. Modify the successAction, so it looks like this:
public function successAction()
{
/*
$session = $this->getOnepage()->getCheckout();
if (!$session->getLastSuccessQuoteId()) {
$this->_redirect('checkout/cart');
return;
}
$lastQuoteId = $session->getLastQuoteId();
$lastOrderId = $session->getLastOrderId();
$lastRecurringProfiles = $session->getLastRecurringProfileIds();
if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
$this->_redirect('checkout/cart');
return;
}
$session->clear();
*/
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
$this->renderLayout();
}
Remember to remove the comments when you're done!
You can stop checkout success page redirection after refresh page, for styling and testing purposes, with this below code:
Go to this file:
vendor/magento/module-checkout/Controller/Onepage/Success.php
and comment Out Line No : 22
//$session->clearQuote();
Now you will be able to refresh and debug success page without redirecting.
Don't forget to uncomment after working.
If anyone would be searching same solution for Magento 2 to stop redirecting from success page after page reload - here it is:
Quick and dirty solution for debug:
Open /vendor/magento/module-checkout/Controller/Onepage/Success.php
Comment out code
/* if (!$this->_objectManager->get('Magento\Checkout\Model\Session\SuccessValidator')->isValid()) {
return $this->resultRedirectFactory->create()->setPath('checkout/cart');
}
$session->clearQuote(); */
Right solution using module can be found here https://gielberkers.com/style-checkoutonepagesuccess-page-magento-2/
I suggest to replace your successAction with this code:
/**
* Order success action
*/
public function successAction()
{
$session = $this->getOnepage()->getCheckout();
$session->setLastSuccessQuoteId(20); // <<< add your order entity ID
$session->setLastQuoteId(20); // <<< add your order entity ID
$session->setLastOrderId(20); // <<< add your order entity ID
if (!$session->getLastSuccessQuoteId()) {
$this->_redirect('checkout/cart');
return;
}
$lastQuoteId = $session->getLastQuoteId();
$lastOrderId = $session->getLastOrderId();
$lastRecurringProfiles = $session->getLastRecurringProfileIds();
if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
$this->_redirect('checkout/cart');
return;
}
#$session->clear(); // <<< comment it
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
$this->renderLayout();
}
Regards
Whilst the code changes might be desirous, there is an extension specifically for this:
https://www.yireo.com/blog/1672-testing-the-magento-checkout-success-page
Disclosure: I am by no means a coder/dev, so the extension route appeals to me (even though I am comfortable making these changes).
Firefox would let you disable HTTP redirects, but you may have to temporarily hack a controller to let you stay on the page anyway.

Resources