How to store a permanent boolean flag? - php

I have created a web app that has 2 control panels. One for the admin and one for the users. I want the users to be able to perform one specific action from their panel only if the admin sets this action "on" (from his panel) and not being able when he sets it "off".
My app also uses a MySql database.
How can I implement it? Is an extra table with only one field a viable solution? Can I do it by reading a file (maybe JSON)?
EDIT: I want the admin to be able to toggle the "on/off" status with a click of a button, so constants are not a solution.

A database query could be used every time the action is used but if it is more general and you are going to be using this a lot, I would look into PHP constants. You could set it in a configuration file like:
Config.php
define('USER_CAN_MODIFY', true);
Other.php
if ((defined('USER_CAN_MODIFY') and USER_CAN_MODIFY === true) { }
Constants have a global scope and cannot be changed once set.

Since you want to store a single value you don't need to use DB. You may simply store this flag in a file as serialized value.
Below is simplified example.
define('PERM_FLAG_FILE', 'perm_flag.dat');
$PERM_FLAG = false;
function loadFlag() {
global $PERM_FLAG;
return file_exists(PERM_FLAG_FILE)? unserialize(file_get_contents($PERM_FLAG)) : false;
}
function saveFlag() {
global $PERM_FLAG;
file_put_contents(PERM_FLAG_FILE, serialize($PERM_FLAG));
}
function setFlag($v) {
global $PERM_FLAG;
$PERM_FLAG = (bool)$v;
}

Related

Dark Mode via PHP and Laravel if statement

Was wondering if it is possible. My attempt is to have a dark mode checker within the PHP controller and send it back to the body as an if statement checking if the boolean is true or not.
Here's my current work:
Sender URL
Switch modes
Controller
public function switchModes()
{
//doesnt work since $isDark's value is not initialized
$isDark = !$isDark;
dd($isDark);
return $isDark;
}
Target result:
<body background="#if($isDark) #505050 #else #ffffff #endif">
The short answer is yes. But you should really try to make your question clearer.
If you want user to click a button or link to switch between light/dark modes, you should use Session.
In your current controller method, you commented that $isDark isn't initialized. You didn't provide a way to initialize that value anywhere, and your controller has no way to figure out what you are doing.
By using session variables, you can have values that persist between pages.
Learn more about sessions here: PHP Session Introduction
Session in Laravel works a little different, but the idea is the same. You want to fetch a session variable in your controller method, and check the value to determine if the user is under light or dark mode, then you would switch his mode by setting the session variable to the other value. In your view, you can check related session variable to determine the mode.
In your controller, you may want to do something like:
public function switchModes()
{
if (session()->has('isDark')) {
session()->put('isDark', !session('isDark'));
}
else {
//provide an initial value of isDark
session()->put('isDark', true);
}
return redirect()->route('your-route-name');
}
And in your view, you can check the session variable like this:
<body class="#if (session('isDark')) dark-mode #else light-mode">

Save temporary data with CakePhp

I am looking for a solution in CakePhp, to store and read temporary datas :
I read some XML from others websites in order to display some news in my website, but on each page load, it does a call to the other xml websites.
Is there a way (memcached like) to save temp. data in CakePhp in order to store data for 1 hour and read temp. data to display them in my webpages ; then 1 hour after update them (with cron) ?
Thanks.
CakePHP Caching seems what you'd want.
WHICH cache you use (Redis, Memcache...etc) would be up to you though. Set your cache to last an hour, and you're all set. (read more about cache on the link above).
If you're on CakePHP 2.5+, you can use the remember method described here.
public function newest() {
$model = $this;
return Cache::remember('newest_posts', function() use ($model){
// get your data from whatever source here, and return it
return $model->getMyData();
}, 'long');
}
Basically, this just checks to see if the cache key exists, and if not, runs some code in order to populate it again.
If you're below 2.5, you can do the same basic thing, but without the remember:
public function newest() {
$result = Cache::read('newest_posts', 'long');
if (!$result) {
// get your data from whatever source here, and write it
Cache::write('newest_posts', $this->getMyData(), 'long');
}
return $result;
}
If you don't have a cache engine installed or are aren't wanting to mess w/ your own server, there are companies that you can use for cache, and you can just set your cache settings to connect to them. ObjectRocket (Redis) is the one I know offhand, but I'm sure there are plenty.
One of many awesome things about CakePHP, is that in this case, your code doesn't change regardless of Cache type/location/configuration you choose.

Modx Plugin: Set createdby of Resource to Match TV Value

I am trying to create a plugin that will take the value of a listbox TV and set the document's createdby field to match that TV's setting onDocFormSave. The TV populates itself automatically with all active users and output's their ID.
I have the following code for the plugin, but when I try to save any resource it simply hangs and never saves. setCreatedBy is the name of the listbox TV:
switch ($modx->event->name) {
case 'onDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy')
if ($resource->get('createdby') != $created_by) {
$modx->resource->set('createdby', $created_by));
}
break;
}
Untested.
It looks like setting also has to be done on the resource, not via the Modx-class.
$resource->set('createdby', $created_by); // You also have a ) too much in your code.
Inspected the docs.
If you omit the $resource->set... and run the plugin, will it pass? I'm wondering if you might be causing a loop, i.e $resource->set triggers another onDocFormSave. Do you have access to the server error.log? It probably contains whatever is crashing.
Those on the Modx forums were able to give me a leg up.
switch ($modx->event->name) {
case 'OnDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy');
if (!empty($created_by) && $resource->get('createdby') != $created_by) {
$resource->set('createdby', $created_by);
$resource->save();
}
break;}
For reference, the way I handled gathering the names and user id's of Modx users and placing them in a selectbox TV was to use the Peoples snippet in an #EVAL binding:
#EVAL return $modx->runSnippet('Peoples',array('tpl'=>'peoplesTpl','outputSeparator'=>'||','active'=>'1'));
This is a petty dirty and slow way of doing things, but a request to have this be a standard field on Modx resources has been submitted to GitHub

Drupal variable_set when resetting module admin form values

I am trying to do a variable_set() when clicking 'Reset default values' on my module's admin page form. This runs through system_settings_form_submit(). The #default_value inside my form is reset, but my module relies on this stored variable to display some data. Clicking reset fills in the form with the default, but does not 'Save' it to recreate the variable in the database, so my module's function breaks. It appears that nothing happens after clicking Reset, other than it deleting the variable from the database. Thanks in advance.
My submit function looks like this:
function faculty_submit(&$form, &$form_state){
if($form_state['values']['op'] == 'Reset to defaults') {
global $faculty_detail_template_default;
variable_set('faculty_detail_template', $faculty_detail_template_default);
}
elseif ($form_state['values']['op'] == 'Save configuration') {
// Clear caches for list and detail pages.
cache_clear_all('faculty_list', 'cache', TRUE);
cache_clear_all('faculty_detail_load', 'cache', TRUE);
}
}
First of all that's what system_settings_form_submit does when you press the Reset to defaults button. It calls variable_del which will delete all your defined variables in the form from the variables table.
Now your form's #default value is probably filled because you do something like this:
global $faculty_detail_template_default;
$form = array (
'#default_value' => variable_get('faculty_detail_template', $faculty_detail_template_default),
);
I don't see why you insist of adding a default value in the variables table. This entire approach is flawed. Just use variable_get($name, $default) wherever your code depends on faculty_detail_template. That's precisely what the second parameter of this function is used for: $default The default value to use if this variable has never been set. So for Drupal, the absence of a variable from the variable table means it's up to the coder how to handle this case (provide a default for example). Default value which is specified using variable_get.
Second, if you used system_settings_form then you already have a submit function, the one mentioned above (system_settings_form_submit) so your faculty_submit won't be called unless you add it specifically to the array of submit callbacks to be executed. Something like this:
$form['#submit'][] = 'faculty_submit';
return system_settings_form($form);
BTW, using global variables is a bad idea (in general) and you should try to avoid using them. That's what variables are used for :) Pieces of information which can be retrieved in different parts of the code. So instead add a .install file to your module and in that file you define these global variables using variable_set. This is a lot cleaner than just magically popping some global variables in the middle of the code.
you need to use &$form_state['values']['yourVariableNameOfForm'] instead of what I have made bold below.
variable_set('faculty_detail_template', $faculty_detail_template_default);

How to make Drupal redirect to pages after user registration

I have a Drupal website and I want to show different welcome pages, depending on what my users enter as profile fields. I can't use the global $user variable, because users are not automatically logged in (They have to very their email address before they can log in).
Where can I add code to set the redirect?
I've tried with $form['#redirect'] and $form_state['redirect'] in the form validator, but that didn't work.
You can use logintobogan for inspiration:
#implementation of hook_user
mymodule_user($op) {
if ($op == 'login') {
$_REQUEST['destination'] = '/user/will/be/redirected/here'
}
}
The important part is to make sure, that by the time the final drupal_goto() is called in user.module, you have set your $_REQUEST['destination'].
A few things to note:
Logintoboggan has a lot of code to deal with all sorts of edge-cases, such as redirecting out/to https. You can ignore these, if your case is simple.
Your module must be called after user.module and probably after other modules implementing hook_user, for they might change this global too. Very ugly, but the way this works in Drupal.
Do not -ever- issue drupal_goto() in any hook. Especially not hook_user, or hook_form_alter. drupal_goto will prohibit other hooks from being called; breaking functionality at the least, but often corrupting your database.
Do not issue drupal_goto() in form_alter callbacks such as "_submit", this might break many other modules and might even corrupt your database.
Similar to Berke's answer, but it seems like you just want this to be a one time thing. For that, you can check for the $account->access property to check their last login. If it is 0, then they are logging in for the first time.
This should work fine for email or no email validation.
<?php
/**
* Implements hook_user().
*/
function mymodule_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
case 'login':
// execute this if they have never accessed the site before
if ($account->access == 0) {
// run conditional logic based on profile fields
// to set destination here
$_REQUEST['destination'] = 'path/to/welcome-page';
}
break;
}
}
?>
I suggest you use the Login Destionation module or you can use the Rules module redirect action which is maybe to robust for your purpose.
Just in case you don't want to write your own custom module :-)

Categories