Skip to content

Instantly share code, notes, and snippets.

@sadiefp
Last active Sep 22, 2017
Embed
What would you like to do?
hook_update() to create photo nodes out of untracked files
/**
* Move files from files dir & add image node.
*/
function hook_update_N(&$sandbox) {
if (!isset($sandbox['progress'])) {
$sandbox['progress'] = 0;
$sandbox['current_nid'] = 0;
$sandbox['max'] = db_query("SELECT COUNT(entity_id) FROM {field_data_field_body} WHERE field_body_value LIKE '%src=\"https://www.example.com/sites/default/files/%'")->fetchField();
$sandbox['messages'] = array();
$sandbox['csv'] = array();
}
// Select all NIDs where we have an old reference.
$nids = db_select('field_data_field_body', 'n')
->fields('n', array('entity_id'))
->condition('field_body_value', '%src="https://www.example.com/sites/default/files/%', 'LIKE')
->condition('entity_id', $sandbox['current_nid'], '>')
->range(0, 5)
->orderBy('entity_id', 'ASC')
->execute();
foreach ($nids as $nid) {
$images_unique = array();
$node_id = $nid->entity_id;
$node = node_load($node_id);
$body = $node->field_body[LANGUAGE_NONE][0]['value'];
// Find all hardcoded image tags.
preg_match_all('~(<img[^>]+example\.com.*?>)+~', $body, $images);
foreach ($images[0] as $image) {
if (!in_array($image, $images_unique)) {
$image_path = array();
preg_match_all('~(\/sites\/default\/files\/.+?(?="|\'))~', $image, $image_path);
if (!empty($image_path[0])) {
$images_unique[] = array(
'tag' => $image,
'path' => $image_path[0][0],
);
}
}
}
// Loop through relevant unique image tags, update them in the body field.
foreach ($images_unique as $image) {
$image_nid = '';
$image_url = 'https://www.example.com' . $image['path'];
$image_base = str_replace('/sites/default/files/', '', $image['path']);
// If photo is in the file_managed table, add shortcode to correct node.
$image_file = entity_load('file', FALSE, array('filename' => basename($image_url)));
if (!empty($image_file)) {
$image_file = reset($image_file);
if ($image_file->filesize > 0) {
// Check if file is attached to a photo node.
$images = db_select('field_data_field_image', 'n')
->fields('n', array('entity_id'))
->condition('field_image_fid', $image_file->fid, '=')
->range(0, 1)
->execute();
foreach ($images as $nid) {
// If file is attached to a photo node, get the photo nid.
$image_nid = $nid->entity_id;
$message = "Fid & photo node found for hardcoded image reference. Shortcode for photo " . $image_nid . " added to article " . $node_id;
}
// If not attached to a photo node, add new photo node.
if (empty($image_nid)) {
$values = array(
'type' => 'photo',
'status' => 1,
'comment' => 0,
'promote' => 0,
);
$entity = entity_create('node', $values);
$entity_w = entity_metadata_wrapper('node', $entity);
$entity_w->title->set(basename($image_url));
$entity_w->field_image = (array) $image_file;
$entity_w->save();
$image_nid = $entity_w->nid->value();
$message = "Fid found. New photo node created. Shortcode for photo " . $image_nid . " added to article " . $node_id;
}
}
// Filesize is 0
else {
// Log, handle as needed later.
$message = "Fid found. Image size = 0 for image on article " . $node_id;
}
}
// If photo is not in the file_managed table.
else {
// Get the image file.
if ($image_file = system_retrieve_file($image_url, file_default_scheme() . '://' . $image_base, TRUE)) {
if ($image_file->filesize > 0) {
$values = array(
'type' => 'photo',
'status' => 1,
'comment' => 0,
'promote' => 0,
);
$entity = entity_create('node', $values);
$entity_w = entity_metadata_wrapper('node', $entity);
$entity_w->title->set(basename($image_url));
$entity_w->field_image = (array) $image_file;
$entity_w->save();
$image_nid = $entity_w->nid->value();
$message = "New photo node created. Shortcode for photo " . $image_nid . " added to article " . $node_id;
}
// Filesize is 0
else {
// Log, handle as needed later.
$message = "Image size = 0 for image on article " . $node_id;
}
}
// If image does not exist.
else {
// Log, handle as needed later.
$message = "Hardcoded image reference not found in file structure for article " . $node_id;
}
}
if (!empty($image_nid)) {
// Replace image tag with new image shortcode.
$body = str_replace($image['tag'], '[photo align=center | size=original]' . $image_nid . '[/photo]', $body);
$sandbox['csv'][] = array(
'article_nid' => $node_id,
'image_nid' => $image_nid,
'image_path' => $image_base,
'message' => $message,
);
}
else {
$message = "Something went wrong with image for article " . $node_id . ". " . $message;
$sandbox['csv'][] = array(
'article_nid' => $node_id,
'image_nid' => 0,
'image_path' => $image_base,
'message' => $message,
);
}
$sandbox['messages'][] = $message;
}
// If body changed, save node.
if ($node->field_body[LANGUAGE_NONE][0]['value'] !== $body) {
$node->field_body[LANGUAGE_NONE][0]['value'] = $body;
node_save($node);
$message = "Article " . $node_id . " updated with new shortcode image(s).";
$sandbox['csv'][] = array(
'article_nid' => $node_id,
'image_nid' => 0,
'image_path' => 'n/a',
'message' => $message,
);
$sandbox['messages'][] = $message;
};
$sandbox['progress']++;
$sandbox['current_nid'] = $node_id;
}
$sandbox['#finished'] = ($sandbox['progress'] >= $sandbox['max']) ? TRUE : ($sandbox['progress'] / $sandbox['max']);
if ($sandbox['progress'] >= $sandbox['max']) {
// Output urls to csv file.
$csv_headers = array(
'article_nid' => 'article_nid',
'image_nid' => 'image_nid',
'image_path' => 'image_path',
'message' => 'message',
);
$csv_title = 'hard-coded-image-references';
_create_csv($sandbox['csv'], $csv_headers, $csv_title);
// Display final message;
$final_message = implode("\n", $sandbox['messages']);
return t('@max # of entities with example.com image references: @message', array(
'@max' => $sandbox['max'],
'@message' => $final_message,
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment