With a custom module, I'm trying to create a new node, save an image to a node's image field from URL and save the node as well. However when I'm trying to save the node, this error messages comes up
Notice: Trying to get property of non-object in file_field_presave() (line 220 of /var/www/clients/client1/web20/web/modules/file/file.field.inc).
Notice: Undefined property: stdClass::$uri in file_save() (line 566 of /var/www/clients/client1/web20/web/includes/file.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => 1373886933 ) in drupal_write_record() (line 7136 of /var/www/clients/client1/web20/web/includes/common.inc).
This is the code I wrote for saving the image into a folder, saving it into a node field and save the node:
$node = new stdClass();
$node->type = "flickr_image";
node_object_prepare($node);
$node->title = $photo['title'];
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$url = $image[10]['source']; //URL of the image
$directory = file_build_uri('flickr_images/');
$file = system_retrieve_file($url, $directory, TRUE, $replace = FILE_EXISTS_REPLACE);
file_save($file);
$node->field_image[LANGUAGE_NONE] = $file;
if($node = node_submit($node)) {
node_save($node);
}
What am I doing wrong? I've looked up several similar questions here, but I don't understand what's the problem. The messages only come up when I use node_save(). When I comment it out, the messages disappear.