Joomla >1.7 hide log messages from browser - joomla

I'm developing an extension for Joomla!; at the moment I'm trying to make it 3.0 compatible - as with 3.0 the logging changed a little (*). Building on the answer from this related question, my current code looks like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php'
));
JLog::add('blah blah log msg');
The problem is that the log also goes to the messages which are shown to the user - this I want to prevent, I want the log msg only to go to the log file. I think it has to do with the "category" that JLog::add takes as a 3rd (optional) parameter, but I have no idea what to pass there?
Can anybody tell me how to hide the messages / or tell me if I'm on the right way with the categories and what value I should use?
Thanks!
(*) It actually changed already with 1.7 as far as I gathered so far, but the old method of calling addEntry on the return of JLog::getInstance(...) seems to have been removed from 2.5 to 3.0.
Edit: Think I found a way now; using:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
'myplg'
));
JLog::add('blah blah log msg', JLog::INFO, 'myplg');
all my log entries go only into my log file (and not to the messages shown to the user). However, I also get a few deprecation warnings - one about my code, but also some unrelated ones:
WARNING deprecated JAccess::getActions is deprecated. Use JAccess::getActionsFromFile or JAcces::getActionsFromData instead.
WARNING deprecated JSubMenuHelper::getEntries() is deprecated. Use JHtmlSidebar::getEntries() instead.
WARNING deprecated JSubMenuHelper::getFilters() is deprecated. Use JHtmlSidebar::getFilters() instead.
WARNING deprecated JSubMenuHelper::getAction() is deprecated. Use JHtmlSidebar::getAction() instead.
Not sure what to make of those - why do they appear in my log file, shouldn't they go to the default error.log file instead of my file ?

This is what I am using, works for Joomla 1.5 - 3.2:
if(version_compare(JVERSION,'1.7.0','ge')) {
jimport('joomla.log.log'); // Include the log library (J1.7+)
$priorities = JLog::ALL ^ JLog::WARNING; // exclude warning (because of deprecated)
// In J3.0 we need to ensure that log messages only go to our file, thus use the categories (already supported in J2.5)
if(version_compare(JVERSION,'2.5.0','ge')) {
$logCategory = 'com_mycomponent';
JLog::addLogger(array('text_file' => $logFileName), $priorities, $logCategory);
JLog::add($msg, JLog::INFO, $logCategory);
}else{
JLog::addLogger(array('text_file' => $logFileName), $priorities);
JLog::add($msg, JLog::INFO);
}
} else {
// Joomla! 1.6 and 1.5
jimport('joomla.error.log'); // Include the log library
$log = &JLog::getInstance($logFileName);
$log->addEntry(array('comment' => $msg, 'level' => 'INFO'));
}
This shows the trick for gettring of the deprecated messages.
And yes, you have to include a category for your messages to ensure they are not showing up as system messages.

Use
new JException('Something happened');
This will only add it to debug log but will not show anything.

It seems, that Joomla 3.0 has no default logger enabled. The same in Joomla 3.0.3. Nothing turns logging on by default - even Debug mode.

Finally I think I have solved my issue with unrelated log entries showing up.
A close look at the API documentation of the addLogger function revealed that the third parameter, $categories, is supposed to be an array of categories for which this log will be used.
This is in contradiction to the version of http://docs.joomla.org/Using_JLog that is current at the time of this writing, where a single category is given instead of an array.
Changing my call to addLogger to use an array, like this:
JLog::addLogger(array(
'text_file' => 'plg_system_myplg.log.php',
JLog::ALL,
array('myplg')
));
And keeping my fingers crossed that this will fix the issue!
Edit: unfortunately even this still doesn't solve my issue - still got unrelated entries :(.

I found the answer.. hope this script make you understand.. I already built as function . this code work on joomla 3. hope work in joomla 2
<?php
function logWrite($level, $values, $file='%s.php',$path='',$showOnTop=0,
$option='',$component=''){
/****
jlog Joomla 3.4
created by:gundambison (2015.04.26).
THX: hbit#stackoverflow
****/
jimport('joomla.log.log');
$level=strtoupper($level);
//You can change this com_name
$component= $component==''? 'com_gundambison': $component;
$date= date("Ymd");
$filename= sprintf($file, $date);
$format= $option=='' ?"{TIME}\t{CLIENTIP}\t{CATEGORY}\t{MESSAGE}": $option;
// create options and text
$txt = is_array($values)? json_encode($values): $values;
$options = array('text_file' => $filename,'text_entry_format'=>$format );
$options['text_file_path']=$path==''?'logs': $path;
JLog::addLogger ($options);
/*
if you want the error to show in your page. just see the different
*/
if($showOnTop==1){
JLog::add("$txt");
}
else{
JLog::add("$level\t$txt",$level,$component);
}
}

Related

WordPress admin-ajax.php 400 error generated by Event Tickets plugin ... database related?

I have a WordPress website for a client that uses a custom theme and a number of plugins in combination to create an events calendar where logged in users can purchase tickets for paid events and register for free RSVP-required events. To accomplish this, I am using the following six plugins in combination:
The Events Calendar
Events Calendar Pro
Event Tickets
Event Tickets Plus
WooCommerce
WooCommerce Stripe Gateway
The website was established in 2015. In the last 4 years, those plugins have seen extensive updates, and as a result, at a certain point the custom site I built around those plugins started experiencing deprecation issues, and attempts to upgrade caused performance failure. After consulting with support, it became necessary to pull a duplicate copy of the site onto a development server so that I could do the work to upgrade the install so all the latest versions of all of these plugins can be running and working properly.
Everything was going well with the upgrade work until I noticed that one of the plugins seems to be generating the following error in the console in Chrome:
POST https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php 400 (Bad Request)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
n.<computed> # jquery.js?ver=1.12.4-wp:4
r.length.e.checkAvailability # frontend-ticket-form.min.js?ver=4.11.1:1
r.length.e.init # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
Loading the same page in Edge generated the following console error:
HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax
(XHR)POST - https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php
The error occurs only under very specific circumstances -- when a single event page displays the frontend form for a paid ticket. The error doesn't occur when the front end paid ticket form is not output, for example when there is a registered RSVP form with no payment component, when there is no ticket component to the event, or when a user who is not an active member views an affected page such that all information about details of the event and buying tickets is excluded from the output via theme template files. Despite the console error generated, it appears that ajax works fine and all of the functionality works exactly as expected. If you weren't looking at the console, you'd never know there was a problem.
In order to rule out an issue with my custom theme or a conflict with another plugin, I activated the default Twenty Twenty theme and deactivated all other plugins except the 6 I listed that are required to use ticketed event process. The error remained present under these circumstances
After going back and forth with Modern Tribe (the plugin developers) support desk, they report the error cannot be replicated. So I tried myself to install a clean copy of WordPress with a new database, then install only those 6 plugins while running the default Twenty Twenty theme. I did this on the same server under the same cPanel account as the dev site with the error, just at different subdomains. On the clean install, the error was NOT present. But when I then pointed the clean WordPress install to a duplicate copy of the database I'm using for the dev site I'm working on, the error shows up again. From that, I can only conclude there is something going on in my database that is making this error happen, but Modern Tribe support are telling me that since the error can't be reproduced by them, there isn't anything they can do to help.
Starting over with a clean install for this site isn't really an option, there is so much data collected over the last 4 years from ticket purchase and membership transactions that we really can't lose. I need to find the faulty data and clean it, but I feel out of my depth here. Any help or suggestions on how to resolve this are welcome.
Edited to add:
I found this code in the javascript file references by the error message in the console. Am I looking in the right place?
/**
* Check tickets availability.
*
* #since 4.9
*
* #return void
*/
obj.checkAvailability = function() {
// We're checking availability for all the tickets at once.
var params = {
action : 'ticket_availability_check',
tickets : obj.getTickets(),
};
$.post(
TribeTicketOptions.ajaxurl,
params,
function( response ) {
var success = response.success;
// Bail if we don't get a successful response.
if ( ! success ) {
return;
}
// Get the tickets response with availability.
var tickets = response.data.tickets;
// Make DOM updates.
obj.updateAvailability( tickets );
}
);
// Repeat every 60 (filterable via tribe_tickets_availability_check_interval ) seconds
if ( 0 < TribeTicketOptions.availability_check_interval ) {
setTimeout( obj.checkAvailability, TribeTicketOptions.availability_check_interval );
}
}
Edited to add:
Then I ran a string search for ticket_availability and found the following. It looks like it might be related, but I'm a bit over my head in interpreting. Am I on the right track yet?
public function ticket_availability( $tickets = array() ) {
$response = array( 'html' => '' );
$tickets = tribe_get_request_var( 'tickets', array() );
// Bail if we receive no tickets
if ( empty( $tickets ) ) {
wp_send_json_error( $response );
}
/** #var Tribe__Tickets__Tickets_Handler $tickets_handler */
$tickets_handler = tribe( 'tickets.handler' );
/** #var Tribe__Tickets__Editor__Template $tickets_editor */
$tickets_editor = tribe( 'tickets.editor.template' );
// Parse the tickets and create the array for the response
foreach ( $tickets as $ticket_id ) {
$ticket = Tribe__Tickets__Tickets::load_ticket_object( $ticket_id );
if (
! $ticket instanceof Tribe__Tickets__Ticket_Object
|| empty( $ticket->ID )
) {
continue;
}
$available = $tickets_handler->get_ticket_max_purchase( $ticket->ID );
$response['tickets'][ $ticket_id ]['available'] = $available;
// If there are no more available we will send the template part HTML to update the DOM
if ( 0 === $available ) {
$response['tickets'][ $ticket_id ]['unavailable_html'] = $tickets_editor->template( 'blocks/tickets/quantity-unavailable', $ticket, false );
}
}
wp_send_json_success( $response );
}
The weird thing is that this function is filed to a folder called Blocks, which implied it works with Gutenberg, which I have disabled via the Classic Editor plugin.
StackOverflow powers that be, forgive me but this was too much to fit in a comment.
I apologize, but this is more of a debug process than a strict answer.
The admin-ajax.php file only has 3 scenarios to return a 400 error.
If the user is logged in, and the ajax function hasn't been added to the wp_ajax_{function_name} action. (line #164)
The user is NOT logged in, and the ajax function hasn't been added to the wp_ajax_nopriv_{function_name} action. (line #179)
No action was sent in the request. (line #32)
You'll need to figure out which of these is causing your error. If you're not sure how to do this, an easy way is to temporarily edit your admin-ajax.php file. Before you see this:
// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
Add in the following (again, before the above lines)
ob_start();
print( '<pre>'. print_r($_REQUEST, true) .'</pre>' );
wp_mail( 'your-email#address.com', 'Debug Results', ob_get_clean() );
This will email you (semi-nicely) formatted dump of the $_REQUEST. If there's no action, you'll know that for some reason the "front end form for a paid ticket" function isn't being added, and Modern Tribe could probably help you out with that.
If the action is set, you can add a similar line down below at line 164 or 179 and repeat the above, but with print( '<pre>'. print_r($action, true) .'</pre>' ); instead. If either of these get emailed to you when you submit the form, you'll know which ajax hook isn't being added, and again Modern Tribe could probably help you from there.
Also note, that modifying core WP files is generally bad practice and you should revert these changes when you're done debugging. (There's ways to hook into file instead, but for ease/speed of diagnostics, go ahead and temporarily edit it, as these aren't permanent changes, and it's on a development site, so you shouldn't have to worry)
Beyond the above, you'll probably need to hire a developer look at it, there's not much more that someone on Stack Overflow can do without having direct access to your database and files.
I am having the same problem and I think the problem is Tribe__Editor::should_load_blocks when the classic editor plugin is active.
To bypass this error I add this code to my theme functions.php file
add_action( 'xxx', tribe_callback( 'tickets.editor.blocks.tickets', 'register' ) );
do_action( 'xxx' );
I hope this works for you.
The advice I received from the plugin developers after a great deal of back and forth was to add the following to my theme's functions.php file:
add_filter( 'tribe_tickets_availability_check_interval', function( $interval) {
return 0;
} );
This resolves the console issue, does not generate additional errors, and does not interfere with any expected functionality in all tests performed thus far.
Wanted to update everyone that with the release of Event Tickets 4.11.4 and Event Tickets Plus 4.11.3, this issue has been completely resolved on the plugin side. So apparently this was not just an issue with my site only. Thank you to everyone who contributed.

Tips on solving 'DevTools was disconnected from the page' and Electron Helper dies

I've a problem with Electron where the app goes blank. i.e. It becomes a white screen. If I open the dev tools it displays the following message.
In ActivityMonitor I can see the number of Electron Helper processes drops from 3 to 2 when this happens. Plus it seems I'm not the only person to come across it. e.g.
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
Electron dying without any information, what now?
But I've yet to find an answer that helps. In scenarios where Electron crashes are there any good approaches to identifying the problem?
For context I'm loading an sdk into Electron. Originally I was using browserify to package it which worked fine. But I want to move to the SDKs npm release. This version seems to have introduced the problem (though the code should be the same).
A good bit of time has passed since I originally posted this question. I'll answer it myself in case my mistake can assist anyone.
I never got a "solution" to the original problem. At a much later date I switched across to the npm release of the sdk and it worked.
But before that time I'd hit this issue again. Luckily, by then, I'd added a logger that also wrote console to file. With it I noticed that a JavaScript syntax error caused the crash. e.g. Missing closing bracket, etc.
I suspect that's what caused my original problem. But the Chrome dev tools do the worst thing by blanking the console rather than preserve it when the tools crash.
Code I used to setup a logger
/*global window */
const winston = require('winston');
const prettyMs = require('pretty-ms');
/**
* Proxy the standard 'console' object and redirect it toward a logger.
*/
class Logger {
constructor() {
// Retain a reference to the original console
this.originalConsole = window.console;
this.timers = new Map([]);
// Configure a logger
this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.File(
{
filename: `${require('electron').remote.app.getPath('userData')}/logs/downloader.log`, // Note: require('electron').remote is undefined when I include it in the normal imports
handleExceptions: true, // Log unhandled exceptions
maxsize: 1048576, // 10 MB
maxFiles: 10
}
)
]
});
const _this = this;
// Switch out the console with a proxied version
window.console = new Proxy(this.originalConsole, {
// Override the console functions
get(target, property) {
// Leverage the identical logger functions
if (['debug', 'info', 'warn', 'error'].includes(property)) return (...parameters) => {
_this.logger[property](parameters);
// Simple approach to logging to console. Initially considered
// using a custom logger. But this is much easier to implement.
// Downside is that the format differs but I can live with that
_this.originalConsole[property](...parameters);
}
// The log function differs in logger so map it to info
if ('log' === property) return (...parameters) => {
_this.logger.info(parameters);
_this.originalConsole.info(...parameters);
}
// Re-implement the time and timeEnd functions
if ('time' === property) return (label) => _this.timers.set(label, window.performance.now());
if ('timeEnd' === property) return (label) => {
const now = window.performance.now();
if (!_this.timers.has(label)) {
_this.logger.warn(`console.timeEnd('${label}') called without preceding console.time('${label}')! Or console.timeEnd('${label}') has been called more than once.`)
}
const timeTaken = prettyMs(now - _this.timers.get(label));
_this.timers.delete(label);
const message = `${label} ${timeTaken}`;
_this.logger.info(message);
_this.originalConsole.info(message);
}
// Any non-overriden functions are passed to console
return target[property];
}
});
}
}
/**
* Calling this function switches the window.console for a proxied version.
* The proxy allows us to redirect the call to a logger.
*/
function switchConsoleToLogger() { new Logger(); } // eslint-disable-line no-unused-vars
Then in index.html I load this script first
<script src="js/logger.js"></script>
<script>switchConsoleToLogger()</script>
I had installed Google Chrome version 79.0.3945.130 (64 bit). My app was going to crash every time when I was in debug mode. I try all the solutions I found on the web but no one was useful. I downgrade to all the previous version:
78.x Crashed
77.x Crashed
75.x Not Crashed
I had to re-install the version 75.0.3770.80 (64 bit). Problem has been solved. It can be a new versions of Chrome problem. I sent feedback to Chrome assistence.
My problem was that I was not loading a page such as index.html. Once I loaded problem went away.
parentWindow = new BrowserWindow({
title: 'parent'
});
parentWindow.loadURL(`file://${__dirname}/index.html`);
parentWindow.webContents.openDevTools();
The trick to debugging a crash like this, is to enable logging, which is apparently disabled by default. This is done by setting the environment variable ELECTRON_ENABLE_LOGGING=1, as mentioned in this GitHub issue.
With that enabled, you should see something along the lines of this in the console:
You can download Google Chrome Canary. I was facing this problem on Google Chrome where DevTools was crashing every time on the same spot. On Chrome Canary the debugger doesn't crash.
I also faced the exact same problem
I was trying to require sqlite3 module from renderer side
which was causing a problem but once i removed the request it was working just fine
const {app , BrowserWindow , ipcMain, ipcRenderer } = require('electron')
const { event } = require('jquery')
const sqlite3 = require('sqlite3').verbose(); // <<== problem
I think the best way to solve this (if your code is really really small) just try to remove functions and run it over and over again eventually you can narrow it down to the core problem
It is a really tedious , dumb and not a smart way of doing it , but hey it worked
I encountered this issue, and couldn't figure out why the the DevTool was constantly disconnecting. So on a whim I launched Firefox Developer edition and identified the cause as an undefined variable with a string length property.
if ( args.length > 1 ) {
$( this ).find( "option" ).each(function () {
$( $( this ).attr( "s-group" ) ).hide();
});
$( args ).show();
}
TL;DR Firefox Developer edition can identify these kinds of problems when Chrome's DevTool fails.
After reading the comments above it is clear to me that there is a problem at least in Chrome that consists of not showing any indication of what the fault comes from. In Firefox, the program works but with a long delay.
But, as Shane Gannon said, the origin of the problem is certainly not in a browser but it is in the code: in my case, I had opened a while loop without adding the corresponding incremental, which made the loop infinite. As in the example below:
var a = 0;
while (a < 10) {
...
a ++ // this is the part I was missing;
}
Once this was corrected, the problem disappeared.
I found that upgrading to
react 17.0.2
react-dom 17.0.2
react-scripts 4.0.3
but also as react-scripts start is being used to run electron maybe its just react scripts that needs updating.
Well I nearly went crazy but with electron the main problem I realized I commented out the code to fetch (index.html)
// and load the index.html of the app.
mainWindow.loadFile('index.html');
check this side and make sure you have included it. without this the page will go black or wont load. so check your index.js to see if there's something to load your index.html file :) feel free to mail : profnird#gmail.com if you need additional help
Downgrade from Electron 11 to Electron 8.2 worked for me in Angular 11 - Electron - Typeorm -sqlite3 app.
It is not a solution as such, but it is an assumption of why the problem.
In the angular 'ngOnInit' lifecycle I put too many 'for' and 'while' loops, one inside the other, after cleaning the code and making it more compact, the problem disappeared, I think maybe because it didn't finish the processes within a time limit I hope someone finds this comment helpful. :)
I have stumbled upon the similar problem, My approach is comment out some line that I just added to see if it works. And if that is the case, those problem is at those lines of code.
for(var i = 0;i<objLen; i+3 ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
The console works fine after i change the code to like this.
for(var i = 0;i<objLen; i=i+space ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
Open your google dev console (Ctrl + shift + i). Then press (fn + F1) or just F1, then scroll down and click on the Restore defaults and reload.

How to return CKEditorFuncNum?

$funcNum = $_GET['CKEditorFuncNum'] ; is not returning the number.
I tried creating the upload.php for ckeditor uploadimage plugin according to
https://stackoverflow.com/a/44553006/8719001 (sorry can't add comments yet)
which includes echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
However when I drop images it doesn't work and in the console I get the Response Text which doesn't show any funcNumber:
"<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(, 'https://example.com/upload/test.jpg', '');</script>"
I think this might be part of filebrowser plugin?
Which I have enabled and also declared $settings['filebrowserUploadUrl'] =
Try to setup config.js insert config.filebrowserUploadMethod = 'form';,if you got CKEditor additional arguments empty,(CKEditor,langCode,CKEditorFuncNum). There are some errors occur,
Incorrect server response. and [CKEDITOR] Error code: filetools-response-error..
please refer,https://github.com/ckeditor/ckeditor-dev/issues/1894
This is the version problem.
I tried 2 hours and couldn't get the parameter CKEditorFuncNum with java like you.
After I changed my 4.9.1 version to 4.7.3, it worked.

How to increase CakePHP Debugger maximum depth

I'm trying to debug my program by logging information from an ajax call. This is something that doesn't render a view, just runs asynchronously. The log will only display arrays to a depth of 3, and the documentation doesn't seem to have any notion that someone might want more information than that.
Please, how do I increase this depth so I can have access to this information without finding weird ways to render my ajax call? Or, if doing this isn't the "Cake" way, is there a better way to output info to a log or console for debugging?
I think this is not the case of CakePHP but an issue with XDebug or PHP configuration itself. You can try to add this line to your php.ini
xdebug.var_display_max_depth = 5
It works if you debug with var_dump(). You should write how do you try to debug, bacause different methods depends on different mechanisms.
If it doesn't work you can try to make the Cake to display original PHP error messages instead of its own error handler messages. In your core.php find code like this:
Configure::write('Error', array(
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
And change it into this:
Configure::write('Error', array(
//'handler' => 'ErrorHandler::handleError',
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
and add this line at the end of bootstrap.php :
function displayErrorWithoutCrap() {
return false;
}
I ended up submitting a ticket to the Git project for CakePHP and it was confirmed that the debug depth for arrays is hard-coded for log files. The response indicated that it would be considered for a change in the next version.
I ended up finding the number in the Debug class and changed it to a larger number which gave me more depth. Not the best fix, but it works for now until support is added to the next version.

Queued Events in Laravel 4: Event::flusher() method not found

According to the Laravel 4 Documentation on queued Events, I tried to register an event flusher this way:
Event::flusher('foo.bar', function($data)
{
Mail::send(array('emails.notification', 'emails.notification_text'), array('content' => $data), function($message)
{
$message
->to('email#example.com', 'My Name')
->bcc('test#example.com')
->subject('Message from Listener');
});
});
But I am getting the following error upon loading of the script:
Call to undefined method Illuminate\Events\Dispatcher::flusher()
I also couldn't find this method in the source codes of L4. But when I change this from Event::flusher() to Event::listen(), everything works as expected.
So my guess is, that the documentation isn't up to date and the Event::flusher() method has been dropped, since Event::listen() does the same work. Or are there any differences between those two methods and I have an error in my code?
You may need to update your libraries using:
$ composer update
If that doesn't work, let us know what your composer.json file looks like - you might be using a beta version if the framework. It was updated very often before the first stable release.

Resources