Moodle: Access global variables on theme settings pages - moodle

Is it possible to access a global variable from either $OUTPUT or $PAGE in /admin/settings.php?
I've tried var_dump on them but I get something along the lines of:
object(bootstrap_renderer)#3 (5) { ["initialising":protected]=> bool(false) ["opencontainers":protected]=>

The variables you want to access, if I understand, are fields of the $PAGE object. You cannot access directly these fields, because they are protected (you can see it in the class defining the $PAGE in /lib/pagelib.php). However, you can access their value by using a slightly different syntax: if the variable is named $_myvariable, you can access it with $PAGE->myvariable, (leaving out the underscore).
Example: you want to access $_pagetype, $_url, and $_navigation, use:
$test = $PAGE->pagetype;
$test1 = $PAGE->url;
$test2 = $PAGE->navigation;
Variables (fields) of the $OUTPUT object are also protected, and I did not find a way to access them, though. Here you can probably change the renderer bound to your $OUTPUT variable, and implement public functions returning your fields.

Related

Powershell - Hashtable in Foreach statement

I'm looking to get an idea of how to go about this.
In a for each loop. Do you need to define the variables before using them in a hash table for TITLE,DEPARTMENT,MANANGER,OFFICE
Currently, this does not set anything for the users in the foreach statement.
Foreach ($userdata in $datafile) {
$SetADUserdetails = #{
Identity=$userdata.Adusername
Title = $userdata.title
Office=$userdata.office
Department=$userdata.department
Manager=$userdata.manager
}
Set-ADUser #SetADUserdetails # Need to add Domain Controller Parameter
}
This is how the datafile looks like.
GivenName,Surname,Office,Title,Path,Manager,Department,Adusername
I'm sure if I set the variable first and then match the variable to hash table keys, it going to work.
Please let me know your thought. I'm fair new to PowerShell. I tried searching the internet for the correct method. No luck. just want to double-check before I define variables.
Yes, variables are rendered at runtime. When you define the hashtable the key will have the variable assigned at the time the hashtable was defined, or the last value that was set for that key with =.
In your code example, the keys of $SetADUserdetails have no value because the $userdata Properties have no value. Make sure that $datafile has the correct entries you are expecting and confirm each iteration of $userdata has some value. Either $datafile is incorrect or you are referencing each column by the wrong column name.

Handle POST data sent as array

I have an html form which sends a hidden field and a radio button with the same name.
This allows people to submit the form without picking from the list (but records a zero answer).
When the user does select a radio button, the form posts BOTH the hidden value and the selected value.
I'd like to write a perl function to convert the POST data to a hash. The following works for standard text boxes etc.
#!/usr/bin/perl
use CGI qw(:standard);
sub GetForm{
%form;
foreach my $p (param()) {
$form{$p} = param($p);
}
return %form;
}
However when faced with two form inputs with the same name it just returns the first one (ie the hidden one)
I can see that the inputs are included in the POST header as an array but I don't know how to process them.
I'm working with legacy code so I can't change the form unfortunately!
Is there a way to do this?
I have an html form which sends a hidden field and a radio button with
the same name.
This allows people to submit the form without picking from the list
(but records a zero answer).
That's an odd approach. It would be easier to leave the hidden input out and treat the absence of the data as a zero answer.
However, if you want to stick to your approach, read the documentation for the CGI module.
Specifically, the documentation for param:
When calling param() If the parameter is multivalued (e.g. from multiple selections in a scrolling list), you can ask to receive an array. Otherwise the method will return the first value.
Thus:
$form{$p} = [ param($p) ];
However, you do seem to be reinventing the wheel. There is a built-in method to get a hash of all paramaters:
$form = $CGI->new->Vars
That said, the documentation also says:
CGI.pm is no longer considered good practice for developing web applications, including quick prototyping and small web scripts. There are far better, cleaner, quicker, easier, safer, more scalable, more extensible, more modern alternatives available at this point in time. These will be documented with CGI::Alternatives.
So you should migrate away from this anyway.
Replace
$form{$p} = param($p); # Value of first field named $p
with
$form{$p} = ( multi_param($p) )[-1]; # Value of last field named $p
or
$form{$p} = ( grep length, multi_param($p) )[-1]; # Value of last field named $p
# that has a non-blank value

Powershell Parameter passing issue

I have a strange one I have searched the existing Q&A and haven't found a match.
I have written my functions using parameter validation using the basic format
function FunctioName
{
[CmdletBinding()]
Param(
[parameter(Mandatory)]
[String]$VariableName
)
When I set the parameter to Mandatory as above I get a parameter binding exception indicating a null value was passed. Running the script in debug I can see the function parameter being passed is not null and is a valid string.
When I run the script in the exact same way without the mandatory flag the string is passed into the function and it executes correctly.
Has anyone got any ideas, what could be the issue. This problem is affecting a number of functions in my application interestingly it appears that the affected functions all have only a single parameter functions with multiple parameters do not appear to be affected.
Ok thanks guys for your feedback its much appreciated. BTW i am using powershell 5 .
Further to the issue, looking into it further I found that the variable was being passed to the function as an array of strings, however an empty string value was being appended into the array which I believe was the cause for the issue. This is where it starts to get interesting, I will need to give a bit more background.
The script I am running queries active directory for user attributes meeting specific conditions, those that match I create an array of strings with each value a delimited value of the user,hostname and other attribute properties.
To ensure that I am getting the latest values I use the ASDI GetInfo method,which seems to trigger the odd behavior.
At a high level the functions are
Function GetuserAttr
{
$inscopeusers = New-Object System.Collections.ArrayList
$accountlist = (Get-ADUser -Filter { attribute1 -eq "value"} -Properties attribute1).SamAccountName
foreach ($user in $accountlist)
{
$DN = getDN($user) # basically a funtion I wrote to create ASDI object for user account.
$DN.GetInfo() # this method call appears to cause issues
$attr1 = $DN.Get("Attribute1")
$attr2 = $DN.Get("Attribute2")
$hoststring = "$($user)|$($attr1)|$($attr2)"
$inscopeusers.Add($hoststring) > null
}
return $inscopeusers
}
The string array returned in this function is fed into a number of other functions, one of which is the one that was giving the error that I originally brought up.
The thing is when I use the GetInfo method the array returned by this function contains several null values in the array, when I remove the command the array has no null strings.
Even more strange when I am operating on the array in other functions it appears that the array looses some of its properties when the GetInfo method is used. So for instance I am able to use the foreach loop to iterate through array values but I cannot access an array value by index such as $array[1].
By simply commenting out the GetInfo method call in the function the array returned seems to function normally and you can access array values by index.
I have another function that also uses GetInfo and returns a hash table, when I try to operate on the returned hashtable I cannot access values using a key value such as $hashtable['key'], but I can access them using $hashtable.key. I know this is really weird and can't really think what it could be
Has any one else experienced a similar problem.
You're missing an argument.
Function Test
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[String]
$Variable
)
Write "$Variable"
}

Drupal save global variables

I make a form in drupal to store data (for annonymous user) so when the form is validate i would like to save it to access it from all page but that does not work outside this function the variable is NULL
can you help me or have you another method to proceed ?
function myform_form_submit($form, &$form_state) {
....
$GLOBALS ['info'] = $info;
}
When a Drupal form is evaluated, it executes any code, including database changes. But then it redirects the user to a new page, which discards the PHP session, including $GLOBALS, among other things.
The more Drupally way is to use persistent variables, which are stored in the "variables" database table.
The variable_set function can be used here. So replace
### $GLOBALS['info'] = $info ### replace with:
variable_set('mymodule_info', $info);
and then when you access it, instead of using $GLOBALS, just use
$info = variable_get('mymodule_info', NULL);
You can use any name to specify the variable. I add NULL as a second parameter to variable_get in case the value isn't present in the database.
If the data is associated with a particular user, you might need to do something like
global $user;
variable_set('mymodule_info_uid_' . $user->uid, $info);
and then to retrieve the data use
global $user;
$info = variable_get('mymodule_info_uid_' . $user->uid, NULL);
EDIT: Ah, now I see you're dealing with anonymous users. In that case, PHP can identify anonymous users for you by giving a session id that can be used in the same way:
variable_set('mymodule_info_session_' . session_id(), $info);
variable_get('mymodule_info_session_' . session_id(), NULL);
This should be persistent for an anonymous user's browsing session.
The issue with this approach is that you'll need to come up with some way of clearing these out. You'll probably need to store a timestamp in the $info variable and have a cron job to delete expired entries from the variable table.

escape HTML by default in Template Toolkit

Can I somehow configure Template Toolkit so that:
[% foo %]
does what you would now need to say:
[% foo | html %]
that is, escape HTML in foo? And do something else, like:
[% foo | noHtml %]
if I don't want to escape?
Came across your question when trying to answer the same question for myself.
http://search.cpan.org/~mithaldu/Template-AutoFilter/ seems to do what we want, but it does require installing another module. I'm going to give it a try anyway.
I guess you could create your own stash by extending Template::Stash so that it would by default escape variables.
That said I think it is not a good idea. Better to stick with default behaviour and refrain from custom modifications as they are certainly confusing.
I spent some time on this problem recently. Here is the outline of my solution.
I created a new class called HtmlSafe which contains strings that can be safely written to WWW client without a security vulnerability. The idea was that the functions that generate HTML tags return HtmlSafe objects, and variables out of the box are not HtmlSafe. Whatever creates a HtmlSafe also has vouched for the safety for the string in question. Concatenating a non-HTML-safe string with HTML-safe string causes the non-HTML-safe string to be escaped through CGI::escapeHTML, and then joined with the HTML-safe string. Concatenating another instance of HtmlSafe to HtmlSafe just joins the strings in question without escaping. I ended up using an overload so I could redefine the . operator for HtmlSafe class.
Armed with this thing, I gave a $template->process() function an $output variable that was actually a sub that invoked a concatenation with HtmlSafe, like this:
my $output = HtmlSafe->new("");
$template->process($vars, sub { $output .= $_[0]; });
return $output->unwrap(); # remove HtmlSafe and return underlying string
We are almost ready with the HtmlSafe TT2. The big changed I had to actually do was to change the textblock() function in Template::Directive, which is used by the Template::Parser to generate HtmlSafe instances of whatever text block it tried to emit. These appear to correspond with the TEXT nodes of the parsed template, so just doing
package MyDirective;
use base "Template::Directive";
sub textblock { my $self = shift; return "$Template::Directive::OUTPUT HtmlSafe->new(" . $self->text(#_) . ")"; }
which I gave to parser like so:
my $parser = Template::Parser->new({
FACTORY => "MyDirective",
});
In addition to this, I defined a "none" filter for TT2 which simply wraps whatever is defined as HtmlSafe, so you can output raw HTML if you have to. This avoids escaping things. The default "html" filter is no-op, because anything concatenated to HtmlSafe gets escaped now anyway.