Tassos Marinos Tassos Marinos Joomla Extensions

Developers: PHP Scripts Collection

Published in Extensions
Updated 27 Oct, 2023

Here you can find a collection of ready PHP Scripts that you can use within the extensions as well as anywhere you desire.

How to create a Joomla Article programmatically

Below you can find a PHP snippet that will allow you create a new article by providing a title, alias, intro & full text as well as category and its state.

Joomla 3

JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_content/tables');

$table = JTable::getInstance('Content', 'JTable', array());

$data = [
    'catid' => 1,
    'alias' => JFilterOutput::stringURLSafe('My Article Title'),
    'title' => 'My Article Title',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
];

// Bind data
if (!$table->bind($data))
{
    throw new Exception($table->getError());
}

// Save Article
if (!$table->store())
{
    throw new Exception($table->getError());
}

Joomla 4

$app = \Joomla\CMS\Factory::getApplication();
$mvcFactory = $app->bootComponent('com_content')->getMVCFactory();
$articleModel = $mvcFactory->createModel('Article', 'Administrator', ['ignore_request' => true]);

$article = [
    'catid' => 2,
    'alias' => \Joomla\CMS\Filter\OutputFilter::stringURLSafe('A41234My Article Title'),
    'title' => '123My Article Title',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
	'language' => '*',
];

if (!$articleModel->save($article))
{
    throw new Exception($articleModel->getError());
}

How to create a new Joomla! User Account

Below is a snippet on how to create a new Joomla! user account.

/**
 * Helper method to create a Joomla! User account
 *
 * @param   String  $username           The account's username
 * @param   String  $name               The account's name
 * @param   String  $email              The account's email address
 * @param   String  $password           The account's password
 * @param   Array   $groups             Comma separated Joomla! User Groups. Defaults to 2 = Registered.
 * @param   Bool    $activate           If set to true, the account will be activated without a confirmation e-mail.
 *
 * @throws  Exception
 * @return  Mixed   Object on success
 */
function addJoomlaUser($username, $name, $email, $password, $groups, $activate = false)
{
	jimport('joomla.user.helper');

	$data = [
        'name'   	 => $name,
        'username'	 => $username,
        'password'	 => $password,
        'password2'	 => $password,
        'email'		 => JStringPunycode::emailToPunycode($email),
        'groups'	 => explode(',', $groups)
	];

	if (!$activate)
	{
        $hash = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
		$data['activation'] = $hash;
		$data['block'] = 1;
	}

	// Load the users plugin group.
	JPluginHelper::importPlugin('user');
	
	$user = new JUser;
	
	if(!$user->bind($data))
	{
        throw new Exception($user->getError());
	}

	if (!$user->save())
	{
        throw new Exception($user->getError());
    }

    return $user;
}

// Create an inactive account. User will need to click on the confirmation e-mail.
$new_user = addJoomlaUser('johndoe', 'John Doe', '[email protected]', '123456', '2');

// Create an active user account. No confirmation e-mail will be sent.
$new_user = addJoomlaUser('johndoe', 'John Doe', '[email protected]', '123456', '2', true);

How to detect if a user is a Super User

Below you can find a PHP snippet that will allow you to detect whether a user is a Super User.

$isSuperUser = JFactory::getUser()->authorise('core.admin');

if ($isSuperUser)
{
    echo "Hey Super User";
}

How to check if current day of week is Saturday or Sunday

Below you can find a PHP snippet that will allow you to check whether the current day of the week is a weekday.

// Method that checks whether the current day of week is either Saturday or Sunday using Joomla API
function isWeekend()
{
    // Comma separated list of days to check. Sunday = 7
    $allowDays = array(6,7);

    // Do not edit below
    return in_array(JFactory::getDate()->format('N'), $allowDays);
}

// Call method
if (isWeekend())
{
    echo 'Hooray! is weekend!';
}

How to check if a user has certain cookies stored in their browser

Below you can find a PHP snippet that will allow you to check if a user has certain cookies stored in their browser.

// Method that checks if multiple cookies exist using Joomla API
function cookiesExist($cookies)
{
    foreach ($cookies as $cookie)
    {
        if (!$pass = (bool) JFactory::getApplication()->input->cookie->get($cookie))
        {
            return false;
        }
    }

    return true;
}

// The cookie names to check
$cookies = [
    'some_cookie_a', 
    'some_cookie_b', 
    'some_cookie_c'
];

// Check cookies
if (cookiesExist($cookies))
{
    echo 'All cookies exist!';
}

How to detect if we are browsing the home page

Below you can find a PHP snippet that will allow you to detect whether we are browsing the home page.

// Load Menu class
$menu = JFactory::getApplication()->getMenu();

// Determine if the user is viewing the front page
$isHomePage = ($menu->getActive() == $menu->getDefault());

if ($isHomePage)
{
    echo 'This is the front page!';
}

How to send HTML & Plan text Email

Below you can find a PHP snippet that will allow you to send a HTML as well as Plain text Email.

// Load the Joomla mailer class
$mailer = JFactory::getMailer();

// Set mail sender
$mailer->setSender(array(
    $sender_email,
    $sender_name
));

// Set recipient, subject and body
$mailer
    ->addRecipient($recipient)
    ->isHTML(true)
    ->setSubject($subject)
    ->setBody($body);

// This is the key line which sets the Content-Type to multipart/alternative so the email can be read by mail clients that do not have HTML email capability.
$mailer->AltBody = strip_tags($body);

// Send mail
$mailer->Send();

How to connect to an external database

Below you can find a PHP snippet that will allow you to connect to an external database.

// Define the external database driver options
$options = [
	'driver'   => 'mysql',          // The Database driver name
	'host'     => 'db.myhost.com',  // Database host name
	'user'     => 'username',       // User for database authentication
	'password' => 'password',       // Password for database authentication
	'database' => 'database_name',  // Database name
	'prefix'   => 'abc_'            // Database prefix (may be empty)
];

$db = JDatabaseDriver::getInstance($options);

// Use the new database driver in your queries
$query = $db->getQuery(true);

$query
	->select($db->quoteName(array('column1', 'column2')))
	->from($db->quoteName('#__table'));

$db->setQuery($query);

$results = $db->loadObjectList();