How to set Component parameters in J2.5? - joomla

I've created a J2.5 component with some config fields using config.xml in the admin folder of the component.
How can I set parameters in the config programatically?
I've tried the code bellow, but it obviously doesn't save the result to the DB:
$params = & JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
Could anyone please show some examples of how to achieve this?

The safest way to do this would be to include com_config/models/component.php and use it to validate and save the params. However, if you can somehow validate the data params yourself I would stick with the following (much more simple solution):
// Get the params and set the new values
$params = JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);
// Get a new database query instance
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Build the query
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where('a.element = "com_mycomponent"');
// Execute the query
$db->setQuery($query);
$db->query();
Notice how I cast the params to a string (when building the query), it will convert the JRegistry object to a JSON formatted string.
If you get any caching problems, you might want to run the following after editing the params:
From a model:
$this->cleanCache('_system');
Or, else where:
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '_system',
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('callback', $options);
$cache->clean();

The solution is here...
http://www.webtechriser.com/tutorials/82-joomla-3-0/86-how-to-save-component-parameters-to-database-programmatically
You can replace in Joomla 2.5+ the
// check for error
if (!$table->check()) {
$this->setError('lastcreatedate: check: ' . $table->getError());
return false;
}
if (!$table->store()) {
$this->setError('lastcreatedate: store: ' . $table->getError());
return false;
}
with
if (!$table->save()) {
$this->setError('Save Error: ' . $table->getError());
return false;
}

Related

How to convert from a string to className in PHP Symfony(Doctrine)

in order to get data from db Im using repo. My current code is working great but I want to update it to use for multiple purpose.
$objectData = $em->getRepository(Articles::class)->findBy(['id' => $modelDataArray['id']]);
so, what I need is something like this:
$moduleName = 'Articles';
$className = $moduleName . '::class';
$objectData = $em->getRepository($className)->findBy(['id' => $modelDataArray['id']]);
but because $className is string will throw an error
Class "Articles::class" does not exist
because its looking for "Articles::class" not Articles::class

spatie / laravel-sitemap | Adding new url replacing the previous file completely

I am using spatie/laravel-sitemap package to generate sitemap. I am able to generate sitemap nicely but when i try to add some new url it is replacing the previous urls completely. I am using the code below. Any suggestion would be very much appreciated.
$keywords = Keyword::all();
$sitemap = SitemapGenerator::create(config('app.url'))
->getSitemap();
$location = Location::where('id', $location_id)->select('id', 'name', 'city_id')->with('city:id,name')->first();
foreach ($keywords as $keyword) {
$url = Url::create("/toptechnicians/{$keyword->keyword}/{$location->city->name}/{$location->name}");
$url2 = Url::create("/topbusinesses/{$keyword->keyword}/{$location->city->name}/{$location->name}");
$sitemap
->add($url
->setLastModificationDate(Carbon::yesterday())
->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
->setPriority(0.1))
->add($url2
->setLastModificationDate(Carbon::yesterday())
->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
->setPriority(0.1))
->writeToFile(public_path('sitemap.xml'));
}

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

Get original image url Magento (1.6.1.0)

I have the following piece of code:
$cProduct = Mage::getModel("catalog/product");
foreach($products_id as $product_id) {
$product = $cProduct->load($product_id);
//$products_image[] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).str_replace(Mage::getBaseUrl('media'),"", $product);
//$products_image[] = $product->getMediaConfig()->getMediaUrl($_product->getData('image'));
$products_image[] = $product->getImageUrl(); //product's image url
}
As you can see, I've tried several ways to get the original image url. Currently I'm using getImageUrl(), but it retrieves the base image, which is a cropped version. How can I retrieve the original image??
Thanks in advance.
Edit:
Seriously appears there isn't a function for it, been Googling for hours straight (also before posting here). So I've written my own function.
function get_original_image_url($base_image_url) {
$exploded = explode("/", $base_image_url);
$image_name = $exploded[count($exploded) - 1];
$original_image_url = "http://yoursitehere.com/media/catalog/product/" . $image_name[0] . "/" .
$image_name[1] . "/" . $image_name;
return $original_image_url;
}
I call it with:
$original = get_original_image_url($product->getImageUrl());
Works for me, though it isn't a nice way to do it.
You should use the catalog product media config model for this purpose.
<?php
//your code ...
echo Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() ); //getSmallImage(), getThumbnail()
Hope this helps.
Other faster way:
$cProduct = Mage::getModel("catalog/product");
$baseUrl = Mage::getBaseUrl('media') . 'catalog/product/';
foreach($products_id as $product_id) {
$product = $cProduct->load($product_id);
$products_image[] = $baseUrl . $product->getImage();
}

Generate MS word document in Joomla

What I try to accomplish:
Admin creates MS Word document with placeholders that will be filled with data from Joomla database
Admin uploades MS Word file to Joomla and connects it with SQL statement
User execute "Generate MS Word" function and gets MS Word document filled with data from database.
Is there any components for Joomla that does this?
I have done this in my application using Interop libraries.
recently I've done this for a joomla component using phpdocx and pclzip libraries, where
a *.docx file is generated from a template file.
Config:
$params = Object with form data; // data from requeest
$template = 'xml_file_name'; // jfrom xml file name and *.docx template file name
$pl = '#'; // place holder prefix & suffix: (example: #PLACEHOLDER#)
$date_placehold = '#DATE#'; // will be replaced with current date
$date_formt = 'F j, Y'; // php date format
$template_path = JPATH_COMPONENT_SITE .DS.'templates'.DS.$template.'.docx';
$temp_dir = JPATH_ROOT.DS.'tmp'.DS.'phpdocx-temp-dir'; // + write access
$output_mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$filename = $params->first_name .' - '. $params->second_name.'.docx';
// get names of all form fields of type 'list' from xml file
$lists = (array) ComponentHelper::getJFormLists($template);
// get all field names from the xml file
$fields = (array) ComponentHelper::getJFormFieldsNames($template);
Initialize variables:
$doc =& JFactory::getDocument();
$doc->setMimeEncoding($output_mime);
// require phpdocx class
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'pclzip.lib.php');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'phpdocx.php');
$phpdocx = new phpdocx($template_path, $temp_dir);
bind form fields with user params:
foreach($params as $field => $value)
{
if(array_key_exists($field,$lists) && is_array($lists[$field]) && array_key_exists($value, $lists[$field]) )
{
// if the field is JFormInput with type "list" its value is not important but its label
$var = $lists[$field][$value];
} else {
$var = $value;
}
// use openxml carriage return on new lines
if(strpos($var, "\n")) {
$var = str_replace("\n", '<w:br/>', $var);
}
$fields[$field] = $var;
}
foreach application form fields:
foreach($fields as $field => $value)
{
// replace placeholder with form value
$phpdocx->assign($pl.strtoupper($field).$pl, $value);
}
// assign date for filled-in applications
if(!empty($date_placehold)
{
$phpdocx->assign($date_placehold, date($date_formt));
}
output the file:
$phpdocx->stream($filename, $output_mime);
return true;

Resources