PHP Custom CMS - How to handle settings - php

I'm currently trying to find a way to handle settings on my custom CMS (just a playground to learn PHP). I have database table that stores all settings. My temporary solution is a function that returns one dimensional array with query results.
// Get settings from db.
function getPanelOptions( $pdo ) {
$options = [];
$getOptions = $pdo->query( 'SELECT option_name, option_value FROM bp_options' );
while( $result = $getOptions->fetch() ) {
$options[ $result['option_name'] ] = $result['option_value'];
}
return $options;
}
$bpOptions = getPanelOptions( $pdo ); // Get settings to arr.
// Example use
if( $bpOptions['post_max_lenght'] === 400 ) ...
I've read a lot that global variables are not best way to do this, so I call function in file that is included on every page. I don't have problem with using hard coded variable, because I won't change it (even so I can replace all occurrences in sublime). My biggest problem is that I can't find a way to use settings to create a 'wrapper' functions like in WordPress, for example 'getHtmlLang()'. In JS it would be easy, but in PHP I need to pass setting to this function, at it gets to lengthy.
// Now i use
<html lang="<?php echo $bpOptions['panel_lang']; ?>">
// I'd like some wrapper function.
<html <?php getHtmlLang() ?>>
I'm not familiar with OOP in PHP so maybe this is way to achieve this, or should I simply use global because it's justified?

Related

Joomla custom fields inside template

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.
For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.
certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..
This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;
I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.
I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Wordpress - make variables available for all theme files (without Globals)

I'm developing a Wordpress theme and I'm trying to store some of my variables in a function to re-use it among my theme files, without writing the same variables hundreds of time and without make them global. I've read that's a bad practice.
For now I'm using add_action but without results. Having in my functions.php
add_action( 'run_pms_variables', 'pms_variables_function' );
function pms_variables_function ($uid ) {
$the_group_uid = isset($_COOKIE["v_group_id"]) && !empty($_COOKIE["v_group_id"]) ? trim(strip_tags($_COOKIE["v_group_id"])) : "";
$session_detail = vpb_get_the_user_detail($uid);
$session_username = strlen($session_detail[0]) > 40 ? ucfirst(substr($session_detail[0],0,40)) : ucfirst($session_detail[0]);
$session_uid = $session_detail[1];
$session_email = $session_detail[2];
$session_photo = $session_detail[3];
$session_country = $session_detail[4];
//$session_usernames = explode(' ', $session_detail[0]);
$session_firstname = get_user_meta($uid,'first_name', true );
$session_lastname = get_user_meta($uid,'last_name', true );
}
and using eventually in my files like:
do_action('run_pms_variables', $uid );
I mean, can you address me to the right method? Thanks.
Write a class, declare a global object of that class, save all your variables as attribute/property of that class.
Now from anywhere just get the global object.
You have all variables stored inside that.
Uuuuhmm you are mixing apples with peaches. The WordPress Hooks, Actions and Filters are ment to modify the WordPress core the way you want, it is not build to store any data somewhere in your template.
One way to do it would be to simply store the values in the database of your WordPress installation. To do that you need to get familiar with the "Nonce" function, which is security mechanism for storing stuff in the database of WP.
There are hundrets and thousands of tutorials out there which show how to do it.
If you want only to store some numeric values or short strings, you could use the HTML data-* object to store some data, when php spits it back.
add_action( 'run_pms_variables', 'pms_variables_function' );
function pms_variables_function ($uid ) {
class GlobalVariables{
function __construct ($uid){
$this->the_group_uid = isset($_COOKIE["v_group_id"]) && !empty($_COOKIE["v_group_id"]) ? trim(strip_tags($_COOKIE["v_group_id"])) : "";
$this->session_detail = vpb_get_the_user_detail($uid);
$this->session_username = strlen($session_detail[0]) > 40 ? ucfirst(substr($session_detail[0],0,40)) : ucfirst($session_detail[0]);
$this->session_uid = $session_detail[1];
$this->session_email = $session_detail[2];
$this->session_photo = $session_detail[3];
$this->session_country = $session_detail[4];
//$session_usernames = explode(' ', $session_detail[0]);
$this->session_firstname = get_user_meta($uid,'first_name', true );
$this->session_lastname = get_user_meta($uid,'last_name', true );
}
}
return GlobalVariables($uid);
}
//and to access:
$global_variables = do_action('run_pms_variables', $uid );
echo $global_variables->the_group_uid;
As a side note, be definition global variables are variables that can be accessed anywhere, other options include setting variables in the $_SESSION super global (as most of you're variables look session specific) inside the pms_variables_function instead of setting class attributes.

Unable to put php code in return of shortcode

I need to hide the URLs of downloads in wordpress posts. I have found a great script to do this but it is not a plugin. I have installed the script and created a function to include it. I am not a pro with php at all.
However the script has a line to normally call it:
<a href="<?php downloadurl('http://yourdomainname.comdownloadables.zip','veryspecials'); ?>" >Your Downloadables</a>
I am not able to place this directly in posts so I am trying to make a shortcode for it, but I am getting stuck. The shortcode that I have is:
function secshort_func($atts, $content = null) {
extract(shortcode_atts(array(
"linkurl" => '#Download_Does_Not_Exist',
"linktitle" => 'Download',
), $atts));
return '<a href="<?php downloadurl(' .$linkurl. ','veryspecials'); ?>" >' .$linktitle. '</a>';
}
add_shortcode( 'secdown', 'secshort_func' );
I am getting errors when trying to run this, and through a process of elimination I know that it is from this part of the return code:
"<?php downloadurl(' .$linkurl. ','veryspecials'); ?>"
After searching the internet for solutions and trying everything that I can think of, I am completely stuck.
Any help would be very much appreciated - it is driving me crazy being stuck on such a little thing!
A few observations along with the answer:
Format your code. It makes life much easier when troubleshooting. Good indenting is huge (see below for your code, formatted).
Don't use cryptic / abbreviated function names. Type them out so that you create self documenting code.
It's better to not use extract. There are some who say it's OK, but it can create confusing code that is hard to troubleshoot because you don't know where a variable came from. It's preferable to explicitly set the variables. (In your case, because you use them only once, it's simplest to just reference them in the array form - $atts['link_url'])
You can call the function, but it has to be concatenated into the string (see below). Your code (and the other answer), are passing php into the string, rather than calling the function and passing the result into the string.
Formatted code, with answer:
// Use a clearer function name. No need for "func", that's implied
function download_link_shortcode($atts, $content = NULL) {
// Declare $defaults in a separate variable to be clear, easy to read
$defaults = array(
"link_url" => '#Download_Does_Not_Exist',
"link_title" => 'Download',
);
// Merge the shortcode attributes
$atts = shortcode_atts( $defaults, $atts );
// Concatenate in the results of the `download` function call....
return '' . $atts['link_title'] . '';
}
add_shortcode( 'secdown', 'download_link_shortcode' );
Try using double outer quotes and escape inner single quotes like this:
return "<a href=\'<?php downloadurl(\'" . $linkurl . "\',\'veryspecials\'); ?>\' >" .$linktitle. '</a>';

Wordpress PHP - How to update plugin setting value in main file

This is from inside my Wordpress plugin, inside the main file:
function my_plugin_install() {
$my_site_url = get_site_url();
$my_options['my_site_url'] = $my_site_url;
// Save
}
register_activation_hook(__FILE__, 'my_plugin_install');
Currently, the install is successful but the 'my_site_url' option is not saved. I'm assuming because the way I'm using the $my_options array at this point doesn't mean anything. It should save this data to the wp_options table.
I can't seem to get this to save, or even find a way to test this as using "echo" gives Wordpress an error during install. Is there a best method for running a script and updating the database during install?
Thanks in advance.
You need to use the WordPress function update_option to save your option value:
function my_plugin_install() {
$my_site_url = get_site_url();
update_option('my_site_url', $my_site_url);
}
register_activation_hook(__FILE__, 'my_plugin_install');
And then later, when you need that value, you can use get_option:
$my_site_url = get_option('my_site_url');
*UPDATE
Since it appears you want to manage multiple of your own options, then I suggest using a simple "utility" function, like so:
function update_my_option($key, $value) {
// Load all of the option values from wp_options
$all_options = get_option('my_options');
// Update just the one option you passed in
$all_options[$key] = $value;
// Save to wp_options
update_option('my_options');
}
And, an appropriate getter function:
function get_my_option($key, $default = NULL) {
// Load all of your options from wp_options
$all_options = get_option('my_options');
// Return just the one option you are asking for
return (isset($all_options[$key])) ? $all_options[$key] : $default;
}
Then, rather than calling update_option directly, you'll call this function, as illustrated below:
function my_plugin_install() {
$my_site_url = get_site_url();
update_my_option('my_site_url', $my_site_url);
}
And, to get one of your options:
$my_site_url = get_my_option('my_site_url');

Allowing users to make template- Scan code for functions

I am currently creating a web app and I would like to allow my users to create a template. I would only allow them to use HTML and some functions to get some values, so I have some functions like
getDescription(); but since its PHP I also have other function (e.g. phpinfo();) which I don't want them to use.
Is it possible to set a filter (like in_array) to check if functions other than declared are used?
Or is there an Template engine or something else which does that.
I am very new to templating and I couldn't find anything.
If they are only creating HTML templates, you could allow them to put for example;
<div>
[PHP]getDescriptions()[PHP]
</div>
<div>
[PHP]phpinfo()[/PHP]
</div>
Then in your parsing file when they save or whatever, you could have
$allowedFunctions = array('getDescriptions');
$input = '';//html from the template
foreach($allowedFunctions as $key => $value){
$myVal = $value();
$input = str_replace('[PHP]'.$value.'()[/PHP]',$myVal,$input);
}
This would replace [PHP]getDescriptions()[/PHP] with whatever is returned from getDescriptions()...
and phpinfo() wouldnt change.
you can check if a function exists with function_exists. If you want them to use the functions you defined for that purpose only you could prefix those function with something like 'tpl_*". like this:
function tpl_getDescription() {/*code here*/}
and then when you user tries to implement a function like getDescription you add "tpl_" to it and check if that function exists with function_exists().
if(function_exists('tpl_' . $userFuncName))
{
call_user_func('tpl_' . $userFuncName)
}
that way even if the user tries to evoke a native php function tpl_ will be prefixed and if will return false.
Yes, you could easily make a script that enumerates all user functions in an external file. Lets say you have this "template", template.php :
<?
function getDescription() {
}
function userFunc() {
}
function anotherFunction() {
}
?>
then you could get a list of all functions in template.php this way :
<?
include('template.php');
$functions = get_defined_functions();
echo '<pre>';
print_r($functions['user']);
echo '</pre>';
?>
would output :
Array
(
[0] => getdescription
[1] => userfunc
[2] => anotherfunction
)
I would call this script through AJAX, like getfunctions.php?file=template.php which returned a JSON with all user functions inside template.php.

Categories