How to log the calling class infos? - php

I would like to override the CI_Log class to improve the log lines.
I want to log the name of the calling class, and the method.
Example :
DEBUG - 2011-04-23 09:21:29 - MY_Class - method --> Router Class Initialized
I tried to override the write_log mehod like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Log extends CI_Log {
public function write_log($level = 'error', $msg, $php_error = FALSE)
{
[...]
$message .=
$level .
(($level == 'INFO') ? ' - ' : ' - ') .
$this->router->fetch_class() .
' - ' .
$this->router->fetch_method() .
' - ' .
date($this->_date_fmt). ' --> ' .
$msg .
"\n";
[...]
}
}
But it doesn't work, the $this->router is not accessible.
Could you help me?

You can use somewhere in your method:
//$RTR is available from system/core/CodeIgniter.php
global $RTR;
$router_class = $RTR->fetch_class();
$rotuer_method = $RTR->fetch_method();

Ok, I think I got it. Here is my code :
[...]
$message .= $level.(($level == 'INFO') ? ' - ' : ' - ') . date($this->_date_fmt);
$stack = debug_backtrace();
// We are searching for the 2nd element of the $stack array beacause :
// - $stack[0] is always taken by JG_Log->write_log()
// - $stack[1] is always taken by log_message()
if (isset($stack[2]['class'])) {
$message .= ' - ' . $stack[2]['class'] . ' - ' . $stack[2]['function'];
}
$message .= ' --> '.$msg."\n";
[...]
I hope that can help others ! :-)

Related

Alphabetize Petfinder API List

I'm using the Petfinder API for Wordpress plugin. The plugin defaults to listing animals based on how old the Petfinder entries are, from oldest to newest. I'm trying to figure out a way to either do newest to oldest, or alphabetize based on animal names.
The data is loaded via the following code:
function get_petfinder_data($api_key, $shelter_id, $count, $pet = '') {
// If no specific pet is specified
if ( $pet == '' ) {
// Create request URL for all pets from the shelter
$request_url = 'http://api.petfinder.com/shelter.getPets?key=' . $api_key . '&count=' . $count . '&id=' . $shelter_id . '&status=A&output=full';
}
// If a specific pet IS specified
else {
// Create a request URL for that specific pet's data
$request_url = 'http://api.petfinder.com/pet.get?key=' . $api_key . '&id=' . $pet;
}
// Request data from Petfinder
$petfinder_data = #simplexml_load_file( $request_url );
// If data not available, don't display errors on page
if ($petfinder_data === false) {}
return $petfinder_data;
And the code that creates the list looks like this:
function get_all_pets($pets) {
foreach( $pets as $pet ) {
// Define Variables
$pet_name = get_pet_name($pet->name);
$pet_type = get_pet_type($pet->animal);
$pet_size = get_pet_size($pet->size);
$pet_age = get_pet_age($pet->age);
$pet_gender = get_pet_gender($pet->sex);
$pet_options = get_pet_options_list($pet);
$pet_description = get_pet_description($pet->description);
$pet_photo_thumbnail = get_pet_photos($pet, 'medium');
$pet_photo_all = get_pet_photos ($pet, 'large', false);
$pet_more_url = get_site_url() . '/adopt/adoptable-dogs/?view=pet-details&id=' . $pet->id;
$pet_pf_url = 'http://www.petfinder.com/petdetail/' . $pet->id;
// Create breed classes
$pet_breeds_condensed = '';
foreach( $pet->breeds->breed as $breed ) {
$pet_breeds_condensed .= pet_value_condensed($breed) . ' ';
}
// Create options classes
$pet_options_condensed = '';
foreach( $pet->options->option as $option ) {
$option = get_pet_option($option);
if ( $option != '' ) {
$pet_options_condensed .= pet_value_condensed($option) . ' ';
}
}
// Compile pet info
// Add $pet_options and $pet_breeds as classes and meta info
$pet_list .= '<div class="vc_col-sm-3 petfinder ' . pet_value_condensed($pet_age) . ' ' . pet_value_condensed($pet_gender) . ' ' . $pet_breeds_condensed . ' ' . $pet_options_condensed . '">' .
'<div class="dogthumbnail">' .
'' . $pet_photo_thumbnail . '<br>' .
'</div>' .
'<a class="dogname" href="' . $pet_more_url . '">' . $pet_name . '</a><br>' .
'<span> ' . $pet_age . ' • ' . $pet_gender . '<br>' .
'<div class="dogbreed">' . $pet_breeds_condensed . '</div>' .
'<a class="morelink" href="' . $pet_more_url . '">Learn More <i class="fas fa-angle-right"></i></a><br>' .
'</div>';
}
// Return pet list
return $pet_list;
Here's an example of the XML that the Petfinder API spits out (right now there are 25 pet entries in the full thing):
<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd">
<header>
<version>0.1</version>
<timestamp>2018-06-11T17:32:34Z</timestamp>
<status>
<code>100</code>
<message/>
</status>
</header>
<lastOffset>25</lastOffset>
<pets>
<pet>
<id>31035385</id>
<shelterId>IL687</shelterId>
<shelterPetId/>
<name>Chanel</name>
<animal>Dog</animal>
<breeds>...</breeds>
<mix>yes</mix>
<age>Adult</age>
<sex>F</sex>
<size>M</size>
<options>...</options>
<description>...</description>
<lastUpdate>2014-12-14T17:59:49Z</lastUpdate>
<status>A</status>
<media>...</media>
<contact>...</contact>
</pet>
</pets>
</petfinder>
I'd like to sort all entries by either "name" or "lastUpdate". I've been looking at a lot of posts about sorting XML element objects but they either don't seem to work or I can't figure out how to apply them specifically to my code. I'm not super well-versed in this stuff, so any assistance is much appreciated!!
After a LOT of research and trial and error, I figured out how to organize alphabetically by animal name. Posting this in case anybody is ever trying to figure out the same.
First of all, I was wrong in my assumption of which sections I might need to be editing. It was actually line 723 of the plugin file. Here's how I modified the code for that section:
// Display a list of all available dogs
else {
// Access Petfinder Data
$petfinder_data = get_petfinder_data($api_key, $shelter_id, $count);
// If the API returns without errors
if( $petfinder_data->header->status->code == '100' ) {
// If there is at least one animal
if( count( $petfinder_data->pets->pet ) > 0 ) {
//Sort list of dogs ALPHABETICALLY by NAME
$petSXE = $petfinder_data->pets->children();
$petArray = array();
foreach($petSXE->pet as $d) {
$petArray[] = $d;
}
function name_cmp($a, $b) {
$va = (string) $a->name;
$vb = (string) $b->name;
if ($va===$vb) {
return 0;
}
return ($va<$vb) ? -1 : 1;
}
usort($petArray, 'name_cmp');
$pets = $petArray;
// Compile information that you want to include
$petfinder_list = get_type_list($pets).
get_age_list($pets) .
get_size_list($pets) .
get_gender_list($pets) .
get_options_list($pets) .
get_breed_list($pets) .
get_all_pets($pets);
}
This is adapting the solution I found in this thread: sort xml div by child node PHP SimpleXML

laravel mysql to query builder

i'm relatively new to laravel and i'm having issues when trying to convert this function to laravel's query builder. This is the function i've been given which also runs a python script to decrypt the database.
Using the documentation from laravel.com you can do something like this:
function call($unitId)
{
$pfContact = DB::table('PFContact')
->where('UnitID', $unitId)
->latest() // Order by created_at
->first([ // Only retrieve these columns
'Send',
'Receive',
'Core',
'lock'
]);
$pfReadings = DB::table('PFReadings')
->get();
$rowCount = $pfReadings->count();
foreach ($pfReadings as $i => $reading) {
echo $i < count($reading) / $rowCount;
foreach ($reading as $column => $value) {
echo shell_exec(
'python3 enc.py ' . $value
. ' ' . $pfContact->Send
. ' ' . $pfContact->Receive
. ' ' . $pfContact->Core
. ' ' . $pfContact->lock . ' '
. $unitId . ' l'
) . '~';
}
echo ';';
}
}
And although I do not know what arguments this pyhton script needs you should really think this through. Why would you use PHP for this and not just handle everything from the python (or php) side because this looks over complicated to me.

how i get the information

I have this script and i need this result:
Numelem / Title / ElmPoste
foreach ( $jobPrintingInfos as $jobprinting_index => $jobprinting ) {
$machine = $jobprinting ['ElmPoste'];
//var_dump($machine);
// var_dump($machine);
}
foreach ( $GetJobResult->Components->Component as $component_index => $component ) {
$quote_support ='';
$quote_impression = '';
$quote_title = ($component->NumElem) . ' / ' . $component->Title . ' ' .$machine. "\r\n";
var_dump($quote_title);
}
but when i do var_dump($quote_title) i have the last machine not all the machine :such as
1/Dessus /Nesspresso
2/Inter/Nesspresso
3/Assem/Nesspresso
Thanks in advance
i dont know the idea behind that script... but if you want that $quote_title <-- is one long String then you need to add a .
like this:
$quote_title .= ($component->NumElem) . ' / ' . $component->Title . ' ' .$machine. "\r\n";
--------------------^
or as array, then its easyer to use a for loop

calling a function inside a class from another class php

I am very new to oops in php. Can anyone tell me how can i use a function
public static function getCategories($id_lang = false, $active = true,$order = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT *
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND `id_lang` = ' . (int)$id_lang : '') . '
' . ($active ? 'AND `active` = 1' : '') . '
' . (!$id_lang ? 'GROUP BY c.id_category' : '') . '
' . ($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, category_shop.`position` ASC') . '
' . ($sql_limit != '' ? $sql_limit : '')
);
if (!$order)
return $result;
$categories = array();
foreach ($result as $row)
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
return $categories;
}
getCategories() is inside a class named class CategoryCore i want to use this getcategory into a new class totalDiscount in which a function called configure_products();
How can i use getcategory() inside the configure products?
include the class file on the page
You can create a object of the class inside another class
function configure_products(){
$categories = new CategoryCore();
$categories->getcategory();
// use $categories to do stuff
......
.....
}
OR
You can call it directly
function configure_products(){
$categories = CategoryCore::getCategories();
.....
....
}
Your function getCategories() is a static function.
So, it can be called without creating object on teh class CategoryCore.
You can use it as (using scope resolution operator):
$categories = CategoryCore::getCategories(YOUR_ARGUMENTS)
Reference

php Object of class Closure could not be converted to string

I'm creating a search-function for my PHP-based file manager. I'm getting this error: 'Catchable fatal error: Object of class Closure could not be converted to string' on the following line:
if ($data->input_ext)
{
$data_ext = ($begun ? ($data->input_logic ? ' OR ' : ' AND ') :
function ()
{
$begun = true;
return "";
}) . 'ext = "' . $data->input_ext . '"';
$data_string.= $data_ext;
}
That's part of what builds the SQL query. $begun_files simply determines whether or not to put 'OR' or 'AND' at the beginning based on whether or not the user input a name or anything that comes before this to match. I have a feeling that I'm not allowed to include anonymous functions in ternary expressions but what should I do instead?
Thanks!
You can't use anonymous functions for inline flow control; just use a regular if statement and don't shun writing things on multiple lines:
if ($data->input_size) {
if ($begun_files) {
$str .= $data->input_logic ? ' OR ' : ' AND ';
$begun_files = true;
}
$str .= sprintf('size %s "%f"',
$data->input_size_op ? '<=' : '>=',
$data->input_size * pow(1024,$data->input_size_unit)
);
}
Building off of the previous answer I ended up going with this:
if ($data->input_ext) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_ext = $logic.'ext = "'.$data->input_ext.'"'; $data_string .= $data_ext;
}
if ($data->input_size) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_size = $logic.'size '.($data->input_size_op ? '<=' : '>=').' '.($data->input_size * pow(1024,$data->input_size_unit)); $data_string .= $data_size;
}
Thanks!

Categories