Changing module name - php

I am customising a opensource phreebooks. I want to change the module names in that. I did change the module names for phreebooks and phreedom successfully, but when i change the name for phreedom i can not print any pdf. I am getting this error
User: 1 Company: phree RUN-TIME WARNING: 'Creating default object from empty value' line 50 in file
F:\wamp\www\phree\modules\report\pages\popup_gen\pre_process.php
In line no 50, code is like this
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
Can somebody please tell me where exactly i am doing wrong. I have been tying it from past 3 days.
EDITED
if (isset($_GET['xfld'])) { // check for extra filters
if (!isset($_GET['xfld'])) $xfld = new stdClass();
echo "BLANK";
if (isset($_GET['xfld'])) $report->xfilterlist[0]->fieldname = $_GET['xfld'];
if (isset($_GET['xcr'])) $report->xfilterlist[0]->default = $_GET['xcr'];
if (isset($_GET['xmin'])) $report->xfilterlist[0]->min_val = $_GET['xmin'];
if (isset($_GET['xmax'])) $report->xfilterlist[0]->max_val = $_GET['xmax'];
}
i did like this
It displays "BLANK" but actually isset($_GET['xfld'] is SET from URL.

$_GET['xfld'] = $xfld;
$xfld = NULL;
$xfld->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $xfld is already initialized to some value but is not an object:
$xfld = something;
$xfld->success = false; // Warning: Attempt to assign property of non-object
You shoud check whether the object already exists:
if (!isset($_GET['xfld'])) $xfld = new stdClass();
Otherwise, this code is not an equivalent replacement for the "old PHP" implicit object creation.

Related

Guide a newbie: PHP 7 warning: Warning: count(): Parameter must be an array or an object that implements Countable

After upgrading to PHP 7 I get the following error message in a really old WP theme. Unfortunately changing the theme is not an option right now, so I have to try to find a fix. I can kind of read PHP, but have a hard time writing it on my own, so I'd love some pointers on how to change this.
The Error message:
Warning: count(): Parameter must be an array or an object that implements Countable
The code that needs to implement Countable
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE) {
$settings = $this['option']->get('warp_theme_options', array());
} else {
$settings = ($file = $this['path']->path('template:config')) ? file_get_contents($file) : array();
}
// set config or load defaults
if (count($settings)) {
$this->config = $this['data']->create($settings);
} else {
$this->config = $this['data']->create(file_get_contents($this['path']->path('template:config.default')));
}
From trying to read up on this I think the error is that count no longer allows Null? But how would I change the code if statement above to work then?

Warning: Creating default object from empty value - with PHP function

I know this is common error and I have read all answer but my case looks different, at least as a PHP newbie so kindly don't decide action based on question subject.
I have a PHP code which working but I am trying to arrange it in appropriate functions, as in below code but I get following error Warning: Creating default object from empty value in /home/abc/vhosts/localhost/public/portfolio.php on line 16:
<?php
// configuration
require("../includes/config.php");
// prepare portfolio object
$portfolioObject = (object) ["portfolioSummaryArr" => [], "cashInHand" => ""];
function getCashInHand(){
// query database to get cash in hand
$rows = CS50::query("SELECT cash FROM users WHERE username = ?", $_SESSION["username"]);
// get first (and only) row
$row = $rows[0];
$portfolioObject->cashInHand = $row["cash"];
$portfolioObject->portfolioSummaryArr = [11, 22, 33, 44, 55];
}
getCashInHand();
?>
Now after reading all the answers and documentation I think I need some sort of object first so I did this and then I get this error Parse error: syntax error, unexpected '$myObject' (T_VARIABLE) in /home/abc/vhosts/localhost/public/portfolio.php on line 12. I trusted this because something similar is allowed in JS and it works, but guess in PHP isn't so my guess is that using objects created like this you cannot define or access function.
$myObject = new stdClass();
$myObject->demoFunction = function(){
echo "I am coming from demo function.";
}
$myObject->demoFunction();
To me things get more interesting because if I do as in below in my code just after require("../includes/config.php"); then it works and no error, but function definition and access as shown in my first code snippet doesn't work.
// Defining function
function whatIsToday(){
echo "Today is XXX";
}
// Calling function
whatIsToday();
It was just matter of time, I would say. I had to do some reading to understand leverage the object orientation of PHP. Below is how I could resolve all my PHP errors and warnings. Needless to say my favorite debugging methodology "print to screen/terminal", in case of PHP using echo helped a lot.
<?php
// configuration
require("../includes/config.php");
class portfolio{
public $portfolioObject;
public function __construct(){
echo "__construct()</br>";
$this->portfolioObject = new stdClass();
}
public function initialize(){
echo "initialize()";
$portfolioObject = (object) ["portfolioSummaryArr" => [], "cashInHand" => ""];
}
public function getCashInHand(){
// query database to get cash in hand
$rows = CS50::query("SELECT cash FROM users WHERE username = ?", $_SESSION["username"]);
// get first (and only) row
$row = $rows[0];
$this->portfolioObject->cashInHand = $row["cash"];
$this->portfolioObject->portfolioSummaryArr = [11, 22, 33, 44, 55];
}
public function setSessionObject(){
$_SESSION["portfolioSummaryResults"] = $this->portfolioObject;
}
}
$myPortfolio = new portfolio();
$myPortfolio->initialize();
$myPortfolio->getCashInHand();
$myPortfolio->setSessionObject();
render("portfolio/portfolio_results.php", ["title" => "Portfolio"]);
?>

Undefined index when calculating age from an inputted birthdate

I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47
If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}

Creating default object from empty value in php 5.4

i have some code like this:
function getAuthorizedPFComponents($pfState)
{
$authorizedPFComponents = new \stdClass();
$compTypeMap=array('platform'=>'pfAuthorizations','mainSite'=>'mainSiteAuthorizations','microSites'=>'microSiteAuthorizations','apps'=>'appAuthorizations');
foreach($compTypeMap as $compType=>$tagName)
{
$authorizationsNode=$this->pfAuthXMLDOM->getElementsByTagName($tagName)->item(0);
foreach($authorizationsNode->getElementsByTagName('authorizations') as $pfComponentAuthElem)
{
foreach($pfComponentAuthElem->getElementsByTagName('allow') as $allow)
{
switch($allow->getAttribute('orgCode'))
{
case 'K_ALL':
{
$authorizedPFComponents->$compType->{$pfComponentAuthElem->getAttribute('pfComponentCode')}->storeCode=$allow->getAttribute('storeCode');
}
}
It shows a warning:
Warning: Creating default object from empty value
The warning is traced back to the code under case K_ALL:
This was too long for a mere comment, so I'll remove it when it has outlived its usefulness.
First thing you should do is make the code simpler; there's a lot of stuff going on in that one statement:
$compCode = $pfComponentAuthElem->getAttribute('pfComponentCode');
$storeCode = $allow->getAttribute('storeCode');
And add debug code:
var_dump($authorizedPFComponents->$compType);
var_dump($authorizedPFComponents->$compType->$compCode);
$authorizedPFComponents->$compType->$compCode->storeCode = $storeCode;
Consider this code:
$x->y = 'test';
If $x is not defined, it will issue a warning:
Warning: Creating default object from empty value in xxx
The same goes for your chain of references:
$authorizedPFComponents->$compType->$compCode->storeCode
If any of those paths is empty, the next ->yyy will cause that warning.

Creating nodes programmatically in Drupal 6

I have been searching for how to create nodes in Drupal 6. I found some entries here on stackoverflow, but the questions seemed to either be for older versions or the solutions did not work for me. Ok, so here is my current process for trying to create
$node = new stdClass();
$node->title = "test title";
$node->body = "test body";
$node->type= "story";
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->uid = 1;
node_save( $node );
When I execute this code, the node is created, but when I got the administration page, it throws the following errors:
warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258.
warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258.
user warning: Duplicate entry '36' for key 1 query: INSERT INTO node_comment_statistics (nid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) VALUES (36, 1269980590, NULL, 1, 0) in C:\wamp\www\steelylib\sites\all\modules\nodecomment\nodecomment.module on line 409.
warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258.
warning: Invalid argument supplied for foreach() in C:\wamp\www\steelylib\includes\menu.inc on line 258.
I've looked at different tutorials, and all seem to follow the same process. I'm not sure what I am doing wrong. I am using Drupal 6.15. When I roll back the database (to right before I made the changes) the errors are gone.
Edit:
After playing around with it a bit, I did find that I had an error in my 'access arguments' in my hook_menu(), but as far as the duplicate entry goes, I was never able to figure it out.
I believe that the problem stems from somewhere else. Code snippet above is 100% correct. But I am sure you have a mistake somewhere.
I have encountered warnings in line 258 of menu.inc. Origin of warning was wrong menu entries. check all hook_menus in your module.
One common mistake -like mine- is assigning wrong values to these menu entries: 'access callback', 'access arguments', 'page callback', 'page arguments'
Keep these items in mind:
'access arguments' and 'page arguments' must be arrays.
If you want to grant unlimited access to a menu entry do like this: 'access callback' => true
Regarding the Duplicate entry, I still have no idea.
What I have done to programatically create node in Drupal 6 is;
$node = new stdClass();
$node->name = "test title";
$node->title = $node->name;
$node->body = "test body";
$node->type = "story";
$node->created = time();
$node->changed = $node->created;
$node->status = 1;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->uid = 1;
if ($node = node_submit($node)) {
node_save($node);
}
else {
// Process error
}
You need to wipe out the node, node revision, and node comment statistics table.
The problem is it is trying to insert a record that already exists in node comment statistics.
I'm not sure what's going on with your site exactly, would need check your db and other stuff, but the error you are seeing is cause by this line:
db_query('INSERT INTO {node_comment_statistics} (nid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) VALUES (%d, %d, NULL, %d, %d)', $node->nid, $node->created, $node->uid, 0);
It is exacuted when a node is saved and everything looks fine. It's the place where something get's inserted into that table. Somehow though, you already have an entry for the node with nid 36 in your node_comment_statistics table. I don't know if your tables are out of sync, or you are inserting two rows into this table.
Possible reasons:
You have some custom code / other module that uses this table?
You are triggering the nook_nodeapi op insert twice in your code when a node is created.
Good change are this is a matter of Permissions.
In my case, I had to give the "Story : Create new content" permission to user role.

Categories