Creating nodes programmatically in Drupal 6 - php

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.

Related

PHP nodeValue being classified as non-object

Recently I have been experimenting with making my own rudimentary search engine. Things have been going smoothly as I have the URL's and URL hashes logged into my phpMyAdmin database, no title or descriptions were logged but the program did work with sites such as YouTube, Google, and a local music venue. However recently I have encountered an error that I can't seem to fix and is stopping new websites from being added to my table and I have been receiving this error message:
Notice: Trying to get property 'nodeValue' of non-object in C:\xampp\htdocs\se\index.php on line 22
I have tried making slight adjustments, such as ensuring that the item is an object by using a code
if (is_object($title ->item(0))) {
$title = $title->item(0)->nodeValue;
}
// Does not work, PHP Recoverable fatal error: Object of class DOMNodeList could not be converted
// to string...
but this only lead to an issue that would not allow the program to move forward.
here is the preceding code up until the error
$already_crawled = array();
$crawling = array();
function get_details($url) {
$options = array('http' => array('method' => "GET", 'headers' => "User-Agent: howBot/0.1\n"));
$context = stream_context_create($options);
$doc = new DOMDocument();
#$doc->loadHTML(#file_get_contents($url, false, $context));
$title = $doc->getElementsByTagName("title");
$title = $title->item(0)->nodeValue; // error occurs here
I am using php7 and I'm still relatively new to it so any other advice would help. Thanks

phpredis zRange return

I'm getting a http 500 error when trying to post to this leaderboard index:
<?php
$reference = "sorted";
$printboard = "leaderboard";
$my_win = 0;
$my_check = 0;
//get the name or member or element of the lowest score
$my_check = $redis->zRange($reference, 0, 0);
//I have the lowest ranking member now get that members score to check against
$my_win = $redis->zScore($reference, $my_check[0]);
//$wins is what I'm posting to this index
if ($my_win < $wins) {
$redis->zDelete($reference, $my_check);//I beat the lowest ranking user so take his spot
//update the new score and push the new user to the print list
$redis->zAdd($reference,$wins, $name);
//if im adding someone new I need to remove someone
//if this is running I want to strip the list of it's 99th user so don't use 1188 use 1176
$redis->listTrim($printboard, 0, 1176);
//then rpush the new player to have made the list
$redis->rpush($printboard,$name,$avatar,$wins,$losses,$ties,$fave,$meter,$game1,$game2,$game3,$game4,$game5);
}
?>
Is my use of zRange correct?
$my_check = $redis->zRange($reference, 0, 0);
And then checking the first array spot?
$my_win = $redis->zScore($reference, $my_check[0]);
I think this may be my issue am I using the return of $my_check incorrectly?
Also, with Redis do you ever need to initialize anything?
I frequently go over the phpredis GitHub manual and the redis website itself and didn't note any details about what happens if you use zRange on an empty sorted set.

PHP SQLite - prepared statement misbehaves?

I have the following SQLite table
CREATE TABLE keywords
(
id INTEGER PRIMARY KEY,
lang INTEGER NOT NULL,
kwd TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
locs TEXT NOT NULL DEFAULT '{}'
);
CREATE UNIQUE INDEX kwd ON keywords(lang,kwd);
Working in PHP I typically need to insert keywords in this table, or update the row count if the keyword already exists. Take an example
$langs = array(0,1,2,3,4,5);
$kwds = array('noel,canard,foie gras','','','','','');
I now these data run through the following code
$len = count($langs);
$klen = count($kwds);
$klen = ($klen < $len)?$klen:$len;
$sqlite = new SQLite3('/path/to/keywords.sqlite');
$iStmt = $sqlite->prepare("INSERT OR IGNORE INTO keywords (lang,kwd)
VALUES(:lang,:kwd)");
$sStmt = $sqlite->prepare("SELECT rowid FROM keywords WHERE lang = :lang
AND kwd = :kwd");
if (!$iStmt || !$sStmt) return;
for($i=0;$i < $klen;$i++)
{
$keywords = $kwds[$i];
if (0 === strlen($keywords)) continue;
$lang = intval($langs[$i]);
$keywords = explode(',',$keywords);
for($j=0;$j < count($keywords);$j++)
{
$keyword = $keywords[$j];
if (0 === strlen($keyword)) continue;
$iStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
$iStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
trigger_error($keyword);
$iStmt->execute();
$sqlite->exec("UPDATE keywords SET count = count + 1 WHERE lang =
'{$lang}' AND kwd = '{$keyword}';");
$rslt = $sStmt->execute();
trigger_error($sqlite->lastErrorMsg());
trigger_error(json_encode($rslt->fetchArray()));
}
}
which generates the following trigger_error output
Keyword: noel
Last error: not an error
SELECT Result: {"0":1,"id":1}
Keyword: canard
Last Error: not an error
SELECT Reult:false
Keyword:foiegras
Last Error: not an error
SELECT Result: false
From the SQLite command line I see that the three row entries are present and correct in the table with the id/rowid columns set to 1, 2 and 3 respectively. lastErrorMsg does not report an error and yet two of the three $rslt->fetchArray() statements are returning false as opposed to an array with rowid/id attributes. So what am I doing wrong here?
I investigated this a bit more and found the underlying case. In my original code the result from the first SQLite3::execute - $iStmt-execute() - was not being assigned to anything. I did not see any particular reason for fetching and interpreting that result. When I changed that line of code to read $rslt = $iStmt->execute() I got the expected result - the rowid/id of the three rows that get inserted was correctly reported.
It is as though internally the PHP SQLite3 extension buffers the result from SQLiteStatement::execute function calls. When I was skipping the assignment my next effort at running such a statement, $sStmt->execute() was in effect fetching the previous result. This is my interpretation without knowing the inner workings of the PHP SQLite3 extension. Perhaps someone who understands the extension better would like to comment.
Add $rslt = NONE; right after trigger_error(json_encode($rslt->fetchArray())); and the correct results appear.
FetchArray can only be called once and somehow php is not detecting that the variable has changed. I also played with changing bindValue to bindParam and moving that before the loop but that is unrelated to the main issue.
It is my opinion that my solution should not work unless there is a bug in php. I am too new at the language to feel confident in that opinion and would like help verifying it. Okay, not a bug, but a violation of the least surprise principle. The object still exists in memory so without finalizing it or resetting the variable, fetch array isn't triggering.

Changing module name

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.

Prestashop Db::getInstance()->update() return Undefined variable

I tried to import my CSV file to update my products, it keeps give me time out and after 2 weeks, we ruled out the server is the problem ( we tried changing max_execution_time, memory_limit, or anything that we think would cause it)
The error logs showed following error:
PHP Notice: Undefined variable: return in /var/www/vhosts/22/xxxxxx/webspace/httpdocs/xxxxxx/controllers/admin/AdminImportController.php on line 1518
which is a customized code that we added to sort our products listing;
Following are the code
$prod_pos = get_object_vars($product);
if (isset($info['position']) && !empty($info['position']))
{
$update_prod_cat_id = array();
for ($i = 0; $i < count($product->category); $i++)
{
if (is_numeric($product->category[$i])){
$return &= Db::getInstance()->update('category_product', array(
'position' => $info['position'],
), '`id_category` = '.(int)$product->category[$i].' AND `id_product` = '.(int)$product->id);
}
else
{
$update_prod_cat_id[] = Category::searchByName($default_language_id, trim($product->category[$i]), true);
$return &= Db::getInstance()->update('category_product', array(
'position' => $info['position'],
), '`id_category` = '.(int)$pos_cat_id['id_category'].' AND `id_product` = '.(int)$product->id);
}
}
}
The funny thing is this code was working until we move the hosting to cloud hosting then every time we tried to upload a CSV file more than 300 lines, it will just timed out and the error log will show the above error!
I am wondering if the db_prefix needed for Db::getInstance()->update()
But I read it will automatically put it when we use this instance.
I am not sure. I tried everything I though it would work but it's not.
Any idea?
From what I see in the code, the varable $return is undefined on the two rows that is being assigned
May be the script really timeouts, but this can be confirmed during the debugging process. The code above seems OK.
The db prefix is automatically added in your case.

Categories