Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring user import #37

Merged
merged 6 commits into from
Dec 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 78 additions & 64 deletions src/plugins/migratetojoomla/wordpress/src/Extension/Wordpress.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,17 @@
use Joomla\CMS\Form\Form;
use Joomla\CMS\Helper\TagsHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Table\Table;
use Joomla\CMS\User\User;
use Joomla\Component\MigrateToJoomla\Administrator\Helper\LogHelper;
use Joomla\Database\DatabaseDriver;
use Joomla\Database\DatabaseInterface;
use Joomla\Event\DispatcherInterface;
use Joomla\Event\EventInterface;
use Joomla\Event\SubscriberInterface;
use Joomla\Registry\Registry;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
Expand All @@ -41,6 +46,16 @@ final class Wordpress extends CMSPlugin implements SubscriberInterface

public $db;

/**
* @var DatabaseInterface DB object connected to the WP DB
*
* @since __DEPLOY_VERSION__
*/
public $wpDB;


public $log;

/**
* Returns an array of events this subscriber will listen to.
*
Expand All @@ -64,6 +79,17 @@ public static function getSubscribedEvents(): array
];
}

public function __construct(DispatcherInterface $dispatcher, array $config = [])
{
parent::__construct($dispatcher, $config);

self::setdatabase($this, $this->getApplication()->getUserState('com_migratetojoomla.information', []));

$options['format'] = '{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}';
$options['text_file'] = 'wordpress-to-joomla.php';
Log::addLogger($options);
}

/**
* Method to store max primary key of Joomla Table
*
Expand Down Expand Up @@ -129,7 +155,8 @@ public static function setdatabase($instance, $data = [])
try {
$db = DatabaseDriver::getInstance($options);
$db->getVersion();
$instance->db = $db;
$instance->db = $db;
$instance->wpDB = $db;
return true;
} catch (\RuntimeException $th) {
LogHelper::writeLog(Text::_('COM_MIGRATETOJOOMLA_DATABASE_CONNECTION_UNSUCCESSFULLY'), 'error');
Expand Down Expand Up @@ -167,8 +194,8 @@ public function storePrimarykey()

$tablesmap = [
'user' => $db->getQuery(true)->select($db->quoteName("ID"))->from($db->quoteName($tableusers)),
'tag' => $db->getQuery(true)->select($db->quoteName("term_id"))->from($db->quoteName($tabletermtaxonomy))->where($db->quoteName('taxonomy') . '=' . $db->q('post_tag')),
"category" => $db->getQuery(true)->select($db->quoteName("term_id"))->from($db->quoteName($tabletermtaxonomy))->where($db->quoteName('taxonomy') . '=' . $db->q('category')),
'tag' => $db->getQuery(true)->select($db->quoteName("term_id"))->from($db->quoteName($tabletermtaxonomy))->where($db->quoteName('taxonomy') . '=' . $db->quote('post_tag')),
"category" => $db->getQuery(true)->select($db->quoteName("term_id"))->from($db->quoteName($tabletermtaxonomy))->where($db->quoteName('taxonomy') . '=' . $db->quote('category')),
"menu" => $db->getQuery(true)->select($db->quoteName("term_id"))->from($db->quoteName($tabletermtaxonomy)),
"menuitem" => $db->getQuery(true)
->select('DISTINCT ID')
Expand All @@ -177,7 +204,7 @@ public function storePrimarykey()
->join('LEFT', $db->quoteName($tabletermrelationship, 'c'), $db->quoteName('a.ID') . '=' . $db->quoteName('c.object_id'))
->join('LEFT', $db->quoteName($tabletermtaxonomy, 'd'), $db->quoteName('c.term_taxonomy_id') . '=' . $db->quoteName('d.term_taxonomy_id'))
->join('LEFT', $db->quoteName($tableterms, 'e'), $db->quoteName('d.term_id') . '=' . $db->quoteName('e.term_id'))
->where($db->quoteName('a.post_type') . '=' . $db->q('nav_menu_item') . 'AND' . $db->quoteName('b.meta_value') . '=' . $db->q('category') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->q('post_tag') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->q('page') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->q('custom') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->q('post')),
->where($db->quoteName('a.post_type') . '=' . $db->quote('nav_menu_item') . 'AND' . $db->quoteName('b.meta_value') . '=' . $db->quote('category') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->quote('post_tag') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->quote('page') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->quote('custom') . 'OR' . $db->quoteName('b.meta_value') . '=' . $db->quote('post')),
"postsandpage" => $db->getQuery(true)->select('ID')->from($db->quoteName($tableposts, 'a'))->where('a.post_status !="trash" AND a.post_status!="inherit" AND a.post_status!="auto-draft"
AND (a.post_type = "post" OR a.post_type ="page")'),
];
Expand Down Expand Up @@ -276,61 +303,54 @@ public static function createDisplayData(EventInterface $event)
*
* @param EventInterface $event
*
* @return void
*
* @since 1.0
*/
public function importUser(EventInterface $event)
{
$app = $this->getApplication();
$jdb = Factory::getDbo();
$key = $event->getArgument('key');
$field = $event->getArgument('field');
$update[] = [];
$maxKey = $app->getSession()->get('migratetojoomla.maxkey', []);
try {
if (!\is_resource($this->db)) {
self::setdatabase($this, $app->getUserState('com_migratetojoomla.information', []));
}
$data = $app->getUserState('com_migratetojoomla.information', []);
$db = $this->db;
$app = $this->getApplication();
$map = $app->getUserState('com_migratetojoomla.wordpress.user_map', []);
$data = $app->getUserState('com_migratetojoomla.information', []);
$key = $event->getArgument('key');
$field = $event->getArgument('field');
$update = [];

try {
// Specify the table name
$tableUsers = rtrim($data['dbtableprefix'], '_') . '_users';
$tableUsersMeta = rtrim($data['dbtableprefix'], '_') . '_usermeta';
$config['dbo'] = $db;
$tablePrefix = $app->get('dbprefix');

// load data from framework table
$query = $db->getQuery(true)
$query = $this->wpDB->getQuery(true)
->select('*')
->from($db->quoteName($tableUsers))
->where($db->quoteName('ID') . '=' . $key);
->from($this->wpDB->quoteName($tableUsers))
->where($this->wpDB->quoteName('ID') . '=' . $key);

$db->setQuery($query);
$results = $db->loadAssocList();
$row = $results[0];

$user = new \stdClass();
$user->id = $row['ID'] + $maxKey['users'];
$user->name = $row['display_name'];
$user->username = $row['user_login'];
$user->email = $row['user_email'];
$user->registerDate = $row['user_registered'];
$user->activation = $row['user_activation_key'];
$user->requireReset = 1;
$user->params = '{"admin_style":"","admin_language":"","language":"","editor":"","timezone":"","a11y_mono":"0","a11y_contrast":"0","a11y_highlight":"0","a11y_font":"0"}';
$this->wpDB->setQuery($query);
$wpUser = $this->wpDB->loadObject();

$jdb->insertObject($tablePrefix . 'users', $user);
if (!$wpUser) {
throw new \Exception('User with ID ' . $key . ' not found');
}

// load user group
$query = $db->getQuery(true)
$query = $this->wpDB->getQuery(true)
->select('meta_value')
->from($db->quoteName($tableUsersMeta, 'a'))
->where($db->quoteName('a.user_id') . '=' . $key, 'AND')
->where($db->quoteName('a.meta_key') . '=' . $db->q('wp_capabilities'));
$db->setQuery($query);
$result = $db->loadAssocList();

$grouprow = $result[0]['meta_value'];
->from($this->wpDB->quoteName($tableUsersMeta, 'a'))
->where($this->wpDB->quoteName('a.user_id') . '=' . $key, 'AND')
->where($this->wpDB->quoteName('a.meta_key') . '=' . $this->wpDB->quote('wp_capabilities'));
$this->wpDB->setQuery($query);
$grouprow = $this->wpDB->loadResult();

$user = new User();
$user->name = $wpUser->display_name;
$user->username = $wpUser->user_login;
$user->email = $wpUser->user_email;
$user->registerDate = $wpUser->user_registered;
$user->activation = $wpUser->user_activation_key;
$user->requireReset = 1;
$user->params = new Registry('{"admin_style":"","admin_language":"","language":"","editor":"","timezone":"","a11y_mono":"0","a11y_contrast":"0","a11y_highlight":"0","a11y_font":"0"}');

$groupId = 1;

Expand All @@ -340,29 +360,23 @@ public function importUser(EventInterface $event)
$groupId = 3;
} elseif (preg_match("/editor/", $grouprow)) {
$groupId = 4;
} else {
$groupId = 1; // default as public
}
LogHelper::writeLog("GroupID: " . $groupId, "success");

// inserting in user_usergroup_map
$usergroup = new \stdClass();
$usergroup->user_id = $row['ID'] + $maxKey['users'];
$usergroup->group_id = $groupId;
$user->groups = [$groupId];
$user->save();
$map[$wpUser->ID] = $user->id;
Log::add('User with WP ID ' . $key . ' (Joomla: ' . $user->id . ') and group ' . $groupId . ' successfully imported.');

$jdb->insertObject($tablePrefix . 'user_usergroup_map', $usergroup);

$contentTowrite = 'User Imported Successfully with id = ' . $key;
LogHelper::writeLog($contentTowrite, 'success');
LogHelper::writeSessionLog("success", $field);
$update[] = ['status' => "success"];
} catch (\RuntimeException $th) {
LogHelper::writeLog('User Imported Unsuccessfully with id = ' . $key, 'error');
} catch (\RuntimeException $e) {
Log::add('Error: Importing user with ID ' . $key . 'failed. ' . $e->getMessage(), Log::ERROR);

LogHelper::writeSessionLog("error", $field);
$update[] = ['status' => "error"];
LogHelper::writeLog($th, 'normal');
}
$app->getSession()->set('migratetojoomla.ajaxresponse', $update);
$app->setUserState('com_migratetojoomla.wordpress.user_map', $map);
}

/**
Expand Down Expand Up @@ -706,7 +720,7 @@ public function importMenuItem(EventInterface $event)
->select('meta_value')
->from($db->quoteName($tablepostmeta, 'a'))
->where($db->quoteName('a.post_id') . '=' . $key, 'AND')
->where($db->quoteName('a.meta_key') . '=' . $db->q('_menu_item_object_id'));
->where($db->quoteName('a.meta_key') . '=' . $db->quote('_menu_item_object_id'));
$db->setQuery($query);
$result = $db->loadAssocList();

Expand All @@ -717,7 +731,7 @@ public function importMenuItem(EventInterface $event)
->select($db->quoteName('meta_value'))
->from($db->quoteName($tablepostmeta, 'a'))
->where($db->quoteName('a.post_id') . '=' . $key, 'AND')
->where($db->quoteName('a.meta_key') . '=' . $db->q('_menu_item_object'));
->where($db->quoteName('a.meta_key') . '=' . $db->quote('_menu_item_object'));
$db->setQuery($query);
$resultload = $db->loadAssocList();
$taxonomytype = $resultload[0]['meta_value'];
Expand All @@ -738,7 +752,7 @@ public function importMenuItem(EventInterface $event)
$query = $db->getQuery(true)
->select($db->quoteName('post_title'))
->from($db->quoteName($tableposts, 'a'))
->where($db->quoteName('a.ID') . '=' . $db->q($taxonomyid));
->where($db->quoteName('a.ID') . '=' . $db->quote($taxonomyid));
$db->setQuery($query);
$taxonomyinfo = $db->loadAssocList();
$menuitemtitle = (empty($row['post_title'])) ? $taxonomyinfo['post_title'] : $row['post_title'];
Expand All @@ -763,7 +777,7 @@ public function importMenuItem(EventInterface $event)
->select($db->quoteName('meta_value'))
->from($db->quoteName($tablepostmeta, 'a'))
->where($db->quoteName('a.post_id') . '=' . $key, 'AND')
->where($db->quoteName('a.meta_key') . '=' . $db->q('_menu_item_url'));
->where($db->quoteName('a.meta_key') . '=' . $db->quote('_menu_item_url'));
$db->setQuery($query);
$menuitemlink = ($db->loadAssocList())[0]['meta_value'];
break;
Expand Down Expand Up @@ -880,7 +894,7 @@ public function importPostsAndPage(EventInterface $event)
->join('LEFT', $db->quoteName($tabletermtaxonomy, 'b'), $db->quoteName('a.term_taxonomy_id') . '=' . $db->quoteName('b.term_taxonomy_id'))
->join('LEFT', $db->quoteName($tableterms, 'c'), $db->quoteName('b.term_id') . '=' . $db->quoteName('c.term_id'))
->where($db->quoteName('a.object_id') . '=' . $key, 'AND')
->where($db->quoteName('b.taxonomy') . '=' . $db->q('category'));
->where($db->quoteName('b.taxonomy') . '=' . $db->quote('category'));
$db->setQuery($query);
$allcategories = $db->loadAssocList();

Expand All @@ -891,7 +905,7 @@ public function importPostsAndPage(EventInterface $event)
->join('LEFT', $db->quoteName($tabletermtaxonomy, 'b'), $db->quoteName('a.term_taxonomy_id') . '=' . $db->quoteName('b.term_taxonomy_id'))
->join('LEFT', $db->quoteName($tableterms, 'c'), $db->quoteName('b.term_id') . '=' . $db->quoteName('c.term_id'))
->where($db->quoteName('a.object_id') . '=' . $key, 'AND')
->where($db->quoteName('b.taxonomy') . '=' . $db->q('post_tag'));
->where($db->quoteName('b.taxonomy') . '=' . $db->quote('post_tag'));
$db->setQuery($query);
$alltags = $db->loadAssocList();

Expand All @@ -900,7 +914,7 @@ public function importPostsAndPage(EventInterface $event)
->select('meta_value')
->from($db->quoteName($tablepostmeta, 'a'))
->where($db->quoteName('a.post_id') . '=' . $key, 'AND')
->where($db->quoteName('a.meta_key') . '=' . $db->q('_thumbnail_id'));
->where($db->quoteName('a.meta_key') . '=' . $db->quote('_thumbnail_id'));
$db->setQuery($query);
$tempresult = $db->loadAssocList();

Expand Down