Skip to content

Instantly share code, notes, and snippets.

@n9iels
Created March 16, 2017 10:40
Show Gist options
  • Save n9iels/72292530480cee854873b061e6ea6f41 to your computer and use it in GitHub Desktop.
Save n9iels/72292530480cee854873b061e6ea6f41 to your computer and use it in GitHub Desktop.
Joomla! CLI script to import a CSV file with Joomla! Tag names
<?php
/*
* @package Knowledge
* @copyright Copyright (c) 2017 Perfect Web Team / perfectwebteam.nl
* @license GNU General Public License version 3 or later
*/
// Make sure we're being called from the command line, not a web interface
if (PHP_SAPI !== 'cli')
{
die('This is a command line only application.');
}
// We are a valid entry point.
const _JEXEC = 1;
// Load system defines
if (file_exists(dirname(__DIR__) . '/defines.php'))
{
require_once dirname(__DIR__) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(__DIR__));
require_once JPATH_BASE . '/includes/defines.php';
}
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_ADMINISTRATOR . '/components');
// Get the framework.
require_once JPATH_LIBRARIES . '/import.legacy.php';
// Bootstrap the CMS libraries.
require_once JPATH_LIBRARIES . '/cms.php';
// Import the configuration.
require_once JPATH_CONFIGURATION . '/configuration.php';
// Import the tags model and helper
JLoader::register('TagsModelTag', JPATH_COMPONENT_ADMINISTRATOR . '/com_tags/models/tag.php');
JLoader::register('TagsTableTag', JPATH_COMPONENT_ADMINISTRATOR . '/com_tags/tables/tag.php');
class ImportTags extends JApplicationCli
{
public function execute()
{
$this->out('== Start importing tags ==');
if (($handle = fopen("tags.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 0, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
$tagName = ucwords(strtolower($data[$c]));
$tagAlias = JApplicationHelper::stringURLSafe($data[$c]);
if ($this->tagExists($tagAlias) == false)
{
$tagModel = new TagsModelTag();
$save = $tagModel->save(array('id' => null, 'published' => 1, 'language' => '*', 'title' => $tagName, 'parent_id' => 4));
if ($save !== true)
{
$this->out('someting went wrong');
exit();
}
else
{
$this->out("imported " . $tagName);
}
}
}
}
fclose($handle);
}
$this->out('== Importing tags finished ==');
}
private function tagExists($alias)
{
$db = JFactory::getDbo();
$q = $db
->getQuery(true)
->select('*')
->from('#__tags')
->where($db->qn('alias') . '=' . $db->q($alias));
$db->setQuery($q);
$result = $db->loadResult();
if (empty($result))
{
return false;
}
return true;
}
}
// Instantiate the application object, passing the class name to JCli::getInstance
// and use chaining to execute the application.
$app = JApplicationCli::getInstance('ImportTags');
JFactory::$application = $app;
$app->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment