Skip to content

Instantly share code, notes, and snippets.

@and1truong
Created September 6, 2012 11:27
Show Gist options
  • Select an option

  • Save and1truong/3655119 to your computer and use it in GitHub Desktop.

Select an option

Save and1truong/3655119 to your computer and use it in GitHub Desktop.
name = "VC Go"
version = 7.x-1.x-dev
description = "Detect old URL, redirect to the new path."
core = 7.x
<?php
/**
* @file vcgo.module
* Detect old path request, redirect to new one.
*/
/**
* Expressions to detect old pages, separator = ~~~ .
* This configuration is for URLs like:
* ./Templates.asp?ID_CATEGORIE=871&ID_MESSAGE=1543&CAT_RAC=711
* ./article/123/article-title
*/
define('VCGO_REGEXS', '/.+ID_MESSAGE=(\d+).+/ ~~~ /.+\/article\/(\d+)\/.+/');
/**
* On migrating, we save old content ID in a node field. We can put the name here.
*/
define('VCGO_FIELD_OLD_ID', 'field_old_id');
/**
* Implements hook_menu().
*/
function vcgo_menu() {
$items['vcgo_fetch/%'] = array(
'title' => 'Fetch content from old site by ID',
'access arguments' => array('access content'),
'page callback' => 'vcgo_fetch_by_id_callback',
);
return $items;
}
/**
* Implements hook_init().
*/
function vcgo_init() {
$path = request_path();
foreach (explode(' ~~~ ', VCGO_REGEXS) as $regex) {
if ($old_id = vcgo_detect($regex, $path)) {
drupal_goto("vcgo_fetch/{$old_id}");
# vcgo_fetch_by_id_callback($old_id);
}
}
}
/**
* Detect old Request, found node ID, redirect and exit the function.
* If node is not found or unpublished, function just return the old ID value.
*/
function vcgo_detect($regex, $path) {
// Find old ID in request path.
$old_id = preg_replace($regex, '$1', $path);
if (!is_numeric($old_id)) return FALSE;
// Find Node ID by old ID
$query = new EntityFieldQuery();
$query->entityCondition('entity_type' , 'node');
$query->fieldCondition(VCGO_FIELD_OLD_ID, 'value' , $old_id);
if (!$entities = $query->execute()) return $old_id;
// Load the node
$entity = reset($entities['node']);
if (!$entity->nid) return $old_id;
if (!$node = node_load($entity->nid)) return $old_id;
if (!$node->status) return $old_id;
// Redirect to node page
drupal_goto("node/{$node->nid}");
}
/**
* @TODO: Function to fetch content by ID from old site.
*/
function vcgo_fetch_by_id_callback($old_id) {
return '…';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment