how to log different clients separately using log4php - php

I am new to log4php and I am trying to implement this on my custom framework. I have managed to get all db queries to file. what I want to do now is log it in a way so i can identify each client so that I can view debug my browser without seeing all the other clients in the same file.
xml
<configuration xmlns="http://logging.apache.org/log4php/">
<appender name="default" class="LoggerAppenderConsole" />
<appender name="default" class="LoggerAppenderFile">
<layout class="LoggerLayoutSimple" />
<param name="file" value="/var/SP/oiadm/docroot/cache/my.log" />
<param name="append" value="true" />
</appender>
<root>
<level value="debug" />
<appender_ref ref="default" />
</root>
</configuration>
php db class
if (defined ( 'OI_ENV' ) && OI_ENV == 'DEVELOPMENT') {
$debugtoolbar = array (
"stacktrace" => $stacktrace,
"sql" => $debug_sql,
"start" => $debug_sql_start,
"end" => $debug_sql_end
);
/*
if ( isset($_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database']) && count ( $_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] ) > 9) {
$_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] = null;
}
$_SESSION ['OI_DEBUG'] ['debugtoolbar'] ['database'] [] = $debugtoolbar;
*/
$log = $_SESSION['OI_DEBUG']['log'];
if(empty($log)){
// Create the logger
// Include and configure log4php
\Logger::configure(BASE_DIR . 'config.xml');
// The __CLASS__ constant holds the class name, in our case "Foo".
// Therefore this creates a logger named "Foo" (which we configured in the config file)
$log = \Logger::getLogger(__CLASS__);
}
$log->debug(json_encode($debugtoolbar));
}
UPDATE
I am using session id now, but this only works if user is logged in
if($_COOKIE['PHPSESSID']){
$log = $_SESSION['OI_DEBUG']['log'];
if(empty($log)){
// Create the logger
// Include and configure log4php
\Logger::configure(BASE_DIR . 'config.xml');
// The __CLASS__ constant holds the class name, in our case "Foo".
// Therefore this creates a logger named "Foo" (which we configured in the config file)
$log = \Logger::getLogger(__CLASS__);
}
$appender = new \LoggerAppenderRollingFile("default");
$appender->setFile(BASE_DIR . "cache/log4php_".$_COOKIE['PHPSESSID'].".log", true);
$appender->activateOptions();
$log->removeAllAppenders();
$log->addAppender($appender);
$log->debug(json_encode($debugtoolbar));
}

Related

Magento 2 : Add custom script just after head tag

i want to add custom script just after the start of head tag.
like.
<head>
<script>console.log("I'm loaded!");</script>
i tried to add code in default_head_blocks.xml
<referenceContainer name="head.additional">
<block class="Custom\Module\Block\Success" template="Custom_Module::success/head.phtml"/>
</referenceContainer>
=> output :
<script>console.log("I'm loaded!");</script>
</head>
this code are using add script before the end of head tag.
Please check Below code
Block => Custom/Module/Block/Onepage/Success.php
namespace Custom\Module\Block\Onepage;
use Magento\Framework\View\Element\Template;
class Success extends \Magento\Checkout\Block\Onepage\Success {
public function getOrder()
{
$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
$helper = $objectManager->get('Custom\Module\Helper\Data');
$lastOrderId = $this->getOrderId();
if (empty($lastOrderId))
{
return null;
}
$orderData = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($this->getOrderId());
return $orderData;
}
}
Helper => Custom\Module\Helper\Data.php
namespace Custom\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* #param \Magento\Framework\App\Helper\Context $context
*/
protected $_request;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\Request\Http $request
) {
$this->_request = $request;
parent::__construct($context);
}
public function getConfigValue($value = '') {
return $this->scopeConfig
->getValue($value,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
}
public function getTemplate()
{
if ($this->getConfigValue('custom_general/general/active') == 1) {
$template = 'Custom_Module::checkout/success.phtml';
} else {
$template = 'Magento_Checkout::success.phtml';
}
return $template;
}
}
di.xml => etc\di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../vendor/magento/framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Block\Onepage\Success" type="Custom\Module\Block\Onepage\Success"/>
</config>
Layout Xml => Custom/Module/view/frontend/layout/default.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="require.js">
<action method="setTemplate">
<argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
</action>
</referenceBlock>
</body>
</page>
Template => Custom/Module/view/frontend/templates/success/head.phtml
<script>
console.log("I'm loaded!");
</script>
Please help me and solve this issue
Thanks in advance.
I am not sure if this is the correct way or not, but I have got a lead.
By default magento 2 usees the root.phtml file to setup head content accordingly, which is located in vendor/magento/module-theme/view/base/templates/root.phtml (if it has not been overridden).
Here, the $requireJs variable is loaded first in the head block. The $requireJs variable is defined in the render method inside Page class -which is located in vendor/magento/framework/view/Result/Page.php.
In this file, $requireJs contains the require.js block. And the require.js block is defined in vendor/Magento/module-theme/view/frontend/layout/default.xml :
<block name="require.js" class="Magento\Framework\View\Element\Template" template="Magento_Theme::page/js/require_js.phtml" />
Solution
1) Copy require_js.phtml from vendor/magento/module-theme/view/frontend/templates/page/js to your theme app/design/frontend/{VENDOR}/{THEME_NAME}/Magento_Theme/templates/page/js/
2) Now you can add your script like this:
<script>
console.log("I'm loaded!");
var require = {
"baseUrl": "<?php /* #escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
};
</script>
UPDATE (Using Module)
Overriding the require.js block is not an elegant solution. if anyone has a good solution please answer. For now edit your layout xml:
<referenceBlock name="require.js">
<action method="setTemplate">
<argument name="template" xsi:type="string">Custom_Module::success/head.phtml</argument>
</action>
</referenceBlock>
and inside success/head.phtml add your code:
<script>
console.log("I'm loaded!");
var require = {
"baseUrl": "<?php /* #escapeNotVerified */ echo $block->getViewFileUrl('/') ?>"
};
</script>
I found a simple way of doing it that seems very reasonable, because it uses existing features in the adminhtml theme without any need to override/intercept anything.
Background
Like #sanchit-gupta mentioned, the root.phtml template is used as the basis to render both the frontend and adminhtml areas, and so is the associated class \Magento\Framework\View\Result\Page, which always looks for a block named head.additional before rendering.
This block exists in the frontend layouts by default, but unfortunately it doesn't exist in the adminhtml layout.
Solution
With that in mind, the current best way (as of 2.3.x) to add inline <scripts> to the adminhtml's <head> section is to add any head.additional block: it will be automatically rendered by the framework. It either has to be a ListText block so that it renders all it's children automatically, or a Template with a specified template file. I actually chose too nest my actual block inside the ListText block just to keep the same mechanism available as in the frontend area (i.e. for compatibility with other plugins that might be doing the same).
Example
In your custom module or theme, add a layout update that inserts the following block into the body of the page layout (which is just to do it the same way as it's done in Magento 2 core for the frontend area):
<body>
<block class="Magento\Framework\View\Element\Text\ListText" name="head.additional">
<block name="your_block" class="Magento\Framework\View\Element\Template" template="Your_Module::your/template.phtml" />
</block>
</body>
Done! Your template will render inside <head></head> – without any awkward overrides or "hacks".
What's more, if other modules also reference head.additional in the adminhtml area, they will be compatible with your code.

Joomla Component: View: Get values from field

I'm new to Joomla, especially to component development. Anyway, here's my question:
site\views\plaingallery\tmpl\default.xml
<?xml version="1.0" encoding="utf-8"?>
<metadata>
<layout title="COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_TITLE">
<message>
<![CDATA[COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_DESC]]>
</message>
</layout>
<fields name="request"
addfieldpath="/administrator/components/com_plaingallery/models/fields">
<fieldset name="request">
<field name="galleryFolder" type="folderlist" default="" recursive="true"
label="Select a folder" directory="images" filter="" exclude="" width="300"
hide_none="true" hide_default="true" stripext="" />
</fieldset>
</fields>
</metadata>
site\views\plaingallery\view.html.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the PlainGallery Component
*/
class PlainGalleryViewPlainGallery extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$this->msg = 'I am new to Joomla';
// Display the view
parent::display($tpl);
}
}
My question is: How do I access the value from the field[name="galleryFolder"] the user provided in the menu configuration?
Thanks for your help! I really do appreciate it.
This parameter is located in the query variable of the menu item.
You can try this for example:
$app = JFactory::getApplication();
/* Default Page fallback*/
$active = $app->getMenu()->getActive();
if (NULL == $active) {
$active = $app->getMenu()->getDefault();
}
if ( isset($active->query['galleryFolder']) ) {
$galleryFolder = $active->query['galleryFolder'];
}

onSave method for Editor Plugin in Joomla 3.6

I try to create a plugin which will display some text after creation of article in the editor.
/editors/materialwords/materialwords.xml:
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="editors">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
/editors/materialwords/materialwords.php:
<?php
defined('_JEXEC') or die;
class PlgEditorMaterialwords extends JPlugin
{
public function onSave($id)
{
return 'alert("' . $id . '");';
}
}
I install plugin and enable it. But something wrong (nothing when I save article in editor).
Please, help.
Best regards, Aleksandr.
if you want a plugin before save or after save event
onExtensionBeforeSave
onExtensionAfterSave
Actually editors plugins are type of editors that you can use in joomla back office, if you go in system - configuration in back office, for default editor you'll can choose your plugin because it is an editors plugin.
If you want to perform some action after save an article you'll have to write a content plugin with method onContentAfterSave(). This method takes 3 arguments :
$context, in your case it should be com_content.article, so test it before soing anything else
$article, the instance of the article you are saving
$isNew, a boolean, true if it is a new article, false if it is an udpate
Plugin code
class PlgContentMaterialwords extends JPlugin {
public function onContentAfterSave($context, $article, $isNew){
if ($context != 'com_content.content'){
return true;
}
// do stuff
}
}
Plugin declaration
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="content">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
Plugin to override save in javascript
With previous method you can not add javascript in this page. If you want to do such you have to add a onBeforeRender method. When clicking on an admin button, javascript method Joomla.submitbutton is called, so you can override it (take care of saving it before so you can call it after your process).
class PlgContentMaterialwords extends JPlugin
{
public function onBeforeRender()
{
if ( JFactory::getApplication()->isAdmin() ){
$document = JFactory::getDocument();
$document->addScriptDeclaration('
var Myvar = {};
Myvar.submitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
if ( task == "article.save" || task == "article.apply" || task == "article.save2new" ){
alert("foo");
}
Myvar.submitbutton(task);
}
');
}
}
}

Joomla 3.x Get Module Parameters Within Ajax Call

I am playing around with a custom build module in Joomla 3.x that uses Ajax to display some real-time data. Within the function executed by the Ajax call I need to access the module parameters and I'm not sure how to do this. Normally, I could just put $var = $params('paramName', 'default') in the module PHP file to get the param but this is not available when the call is made by Ajax. This is my template code that executes the Ajax call:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.get('index.php?option=com_ajax&module=whatsinport&method=getWhatsInPort&format=json', function(data) {
console.log(data);
var response = jQuery.parseJSON(data);
This is the code in my helper.php class:
class modWhatsInPortHelper {
public static function getWhatsInPortAjax()
{
$results = array();
$results['status'] = 'ok';
$app = JFactory::getApplication();
$serverName = $app->getCfg('mod_whatsinport_serverName');
$dbName = $app->getCfg('mod_whatsinport_dbName');
$dbUser = $app->getCfg('mod_whatsinport_dbUser');
$dbPwd = $app->getCfg('mod_whatsinport_dbPwd');
$connectionInfo = array( "Database"=>$dbName, "UID"=>$dbUser, "PWD"=>$dbPwd, "ReturnDatesAsStrings"=>true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
The $app->getCfg does not appear to do what I want - I am guessing it is only used for Joomla config settings. I also tried:
$app = JFactory::getApplication();
$params = $app->getParams();
$serverName = $params->get('mod_whatsinport_serverName');
$dbName = $params->get('mod_whatsinport_dbName');
$dbUser = $params->get('mod_whatsinport_dbUser');
$dbPwd = $params->get('mod_whatsinport_dbPwd');
But this didn't work either. I forgot to include my module config file:
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1.0" client="site" method="upgrade">
<name>WhatsInPort</name>
<author>Chris Krohn</author>
<version>1.0.0</version>
<description>Displays a list of current vessels in port.</description>
<files>
<filename>mod_whatsinport.xml</filename>
<filename module="mod_whatsinport">mod_whatsinport.php</filename>
<filename>index.html</filename>
<filename>helper.php</filename>
<filename>tmpl/default.php</filename>
<filename>tmpl/index.html</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="mod_whatsinport_serverName" type="text" default="" label="Server Name" description="NETBIOS name of the database server to connect to." />
<field name="mod_whatsinport_dbName" type="text" default="" label="Database Name" description="Name of the database with the HMLOG table." />
<field name="mod_whatsinport_dbUser" type="text" default="" label="Database User" description="User name to login to the server with." />
<field name="mod_whatsinport_dbPwd" type="password" default="" label="Database Password" description="Password to login to the server with." />
</fieldset>
</fields>
</config>
</extension>
Figured it out. Should be:
$app = JFactory::getApplication();
$module = JModuleHelper::getModule('mod_whatsinport','WhatsInPort');
$params = new JRegistry($module->params);
$serverName = $params->get('mod_whatsinport_serverName');
$dbName = $params->get('mod_whatsinport_dbName');
$dbUser = $params->get('mod_whatsinport_dbUser');
$dbPwd = $params->get('mod_whatsinport_dbPwd');
Retrieve data of a parameter within the getjax() method.
public static function getAjax(){
$app = JFactory::getApplication();
$module = JModuleHelper::getModule('my_module');
$params = new JRegistry($module->params);
return $params ->get('myparams');
}

How to return a value from phing ad-hoc task?

Is there any way to get a return value from a phing ad-hoc task?
For example, I'm trying to get the version number from a JSON string in a file as follows:
<target name="get-app-version">
<adhoc-task name="appversion" ><![CDATA[
class AppversionTask extends Task {
private $version;
public function getVersion() {
return $this->version;
}
function main() {
$manifest = file_get_contents("manifest.json");
$manifest_json = json_decode($manifest);
$version = $manifest_json->version;
$this->log("App version: " . $version);
$this->version = $version;
}
}
]]></adhoc-task>
<appversion output="version" />
<echo message="${version}" />
</target>
I can only find documentation on setting values, but not getting values. However, the adhoc typdef task seems to show a get syntax, so I'm wondering if there is some way to do this.
I am not sure if I understand completely. It sounds like, rather than setting
$this->version
you should instead call
$this->project->setProperty('version', $version);
This will add the 'version' property to your project instance. You won't need to have to set the attribute for your task, unless say, you will want to later change what property name in your project gets set (from 'version' to some other property).
`
<adhoc-task name="appversion" ><![CDATA[
class AppversionTask extends Task {
function main() {
$manifest = file_get_contents("manifest.json");
$manifest_json = json_decode($manifest);
$version = $manifest_json->version;
$this->log("App version: " . $version);
$this->project->setProperty('version', $version);
}
}
]]></adhoc-task>
<appversion />
<!-- The version property should now be set -->
<echo message="${version}" />
`

Categories