I am trying to use Google Closure but called through a php library.
This is the code I'm trying to work with
https://code.google.com/p/php-closure/
So far it seems to be working well. However I now need to use the "Externs" feature of Google Closure.
I have gone through the php library code but I am unsure on how to add this feature. The library appears to call the Google Closure online API code, so I assume to add the externs feature I just need to pass the correct string attached to the correct variable.
I won't post the entire library here as it would be hard to read, but the efforts I've made to incorporate this feature.
To begin I added the variable to the library
var $_srcs = array();
var $_mode = "WHITESPACE_ONLY";
var $_warning_level = "DEFAULT";
var $_use_closure_library = false;
var $_pretty_print = false;
var $_debug = true;
var $_cache_dir = "";
var $_code_url_prefix = "";
var $_extern_file = ""; //my new code
add to the hash function
function _getHash() {
return md5(implode(",", $this->_srcs) . "-" .
$this->_mode . "-" .
$this->_warning_level . "-" .
$this->_use_closure_library . "-" .
$this->_pretty_print . "-" .
$this->_extern_file . "-" . //here again
$this->_debug);
}
add to get params list
function _getParamList() {
$params = array();
...
$params["warning_level"] = $this->_warning_level;
$params["extern_file"] = $this->_extern_file; //again here
if ($this->_pretty_print) $params["formatting"] = "pretty_print";
if ($this->_use_closure_library) $params["use_closure_library"] = "true";
$params["output_info_1"] = "compiled_code";
$params["output_info_2"] = "statistics";
$params["output_info_3"] = "warnings";
$params["output_info_4"] = "errors";
return $params;
}
my add externs file function
function externs($file) {
$this->_extern_file = $file;
return $this;
}
then my user call
$c->add("js/my-app.js")
->add("js/popup.js")
->externs("js/externs.js") //new code
->cacheDir("/tmp/js-cache/")
->write();
When trying to execute the code I get the same result as the original code. It appears the externs file that I'm trying to pass isn't being processed.
If anyone else is interested in this feature / library please feel free to post any ideas.
Thanks.
Related
Let's say that you have a class in php with functions and all that. How could you check if there is no code outside the class?
I tried to code this checker with PHP and did it with regex and tokens but nothing worked for me :/
An exmple
<?php
class example {
var $name;
var $password;
function __construct($name, $password) {
$this->name = $name;
$this->password = $password;
}
----Allowed code----
}
----Not allowed code----
?>
EDIT: (SOLVED)
Thanks #user3163495 for all the information
Here what I did:
1ยบ I tried to get the class name inside the file with this two functions:
function getClass($tokens) {
$clases = array();
for($i = 0; $i < count($tokens); $i++) {
//Tipo del token actual
$tokenName = getTokenName($tokens, $i);
if($tokenName === "T_CLASS") {
//Searchs the name that it has in the file.
return getClassName($tokens, $i);
}
}
return "";
}
function getClassName($tokens, $i) {
$index = $i + 1;
//Line in which is the class inside the file
$lineaClase = getTokenLine($tokens, $i);
//Line to be updated while searching
$lineaTemp = getTokenLine($tokens, $index);
//Type of token to be updated while searching
$tokenName = getTokenName($tokens, $index);
//Searchs in the parsed array for the first class token
while($index < count($tokens) &&
$lineaClase === $lineaTemp &&
($tokenName === "UNKOWN" || $tokenName === "T_WHITESPACE")) {
$index++;
$tokenName = getTokenName($tokens, $index);
$lineaTemp = getTokenLine($tokens, $index);
}
//Returns the name of the class
return getTokenContent($tokens, $index);
}
Then, I injected PHP code in the end of the file that I tried to check if it's only a class. Also I saved this new content in a new file called temp.php and finally I shell-executed this to get the echo of the injected code, that will correspond to beginning_of_class:end_of_class. Here is where I used what #user3163495 told me, thank you again.
function codeInjection($clase, $contenido) {
//PHP code to inject, thanks to #user3163495
$codigoPHP = "<?php \$class = new ReflectionClass(\"{$clase}\"); \$comienzo = \$class->getStartLine(); \$fin = \$class->getEndLine(); echo \$comienzo . \":\" . \$fin; ?>";
$contenido .= $codigoPHP;
//Creating temp file
file_put_contents("temp.php", $contenido);
//Returning result of execution
return shell_exec("php temp.php");
}
Further, I removed from the token parsed array those tokens which line where between the beginning and the end of the class. Last I go through the array searching for something that is different than a comment, white space, etc..
(Variables are in spanish, if you don't understand the meaning of some feel free to ask)
If you are wanting to "scan" the questionable file from another script to see if there is any code outside the class, then you could use the ReflectionClass in PHP.
Step 1: get the file name that your class is defined in
$class = new ReflectionClass("example");
$fileName = $class->getFileName();
Step 2: get the starting and ending lines of code that the class definition occupies in the file
$startLine = $class->getStartLine();
$endLine = $class->getEndLine();
$numLines = $endLine - $startLine;
Step 3: use file_get_contents() on the file name you obtained in Step 1, and see if there is any forbidden code before the start line or after the end line. You'll have to test and play around with what you get as I don't know exactly where getStartLine() and getEndLine() consider "start" and "end", respectively.
I hope you get the idea.
Some code lifted from this answer: https://stackoverflow.com/a/7909101/3163495
My client contacts with the database via service. When I do some action, I call the service URL with file_get_contents then process the response.
I think when a user enters the site from google search result, I think google adds some parameters to my service URL which belongs to file_get_contents.
For example,
as it should be,
file_get_contents(service.domain/service_name?param1=0)
but google adds some strange parameters at the end of url. like this:
file_get_contents(service.domain/service_name?param1=0&force=1)
I saw two or three strange parameters so,
force = 1
gclid=CNC-jvTapbcCFaaj
I don't know how can I handle and remove these parameters.
How can I remove these strange parameters before calling the URL with file_get_contents?
This is my function:
public function getWhere($keyword)
{
$locale = session('locale');
if($locale != "en" && $locale != "")
{
$locale = "_".session('locale');
}else{
$locale = "";
}
$page = file_get_contents(getenv('API_URL')."station_info?search.url=".$keyword);
$page = json_decode($page);
$page = (array) $page->rows;
$station = $page[0];
if($station->search->status == 1)
{
return redirect('/');
}
return view('station', compact('station', 'locale'));
}
Strange parameters add themselves end of the URL.
Edit
I think someone is trying to something. $keyword must take a string which is station name, example, London.
But someone is trying to send London&force=1 so I have to check the $keyword variable.
You can parse url by parse_url function, remove unwanted parameters or just keep parameters you want and build url back
after using parse_url function you may need to parse query by parse_str function, so code will look like:
$urlParsed = parse_url("service.domain/service_name?param1=0&force=1");
$params = parse_str ($urlParsed['query']);
$newParams = [];
$neededParams = ['param1', 'param2'];
foreach ($neededParams as $p) {
if (isset($params[$p])) {
$newParams[$p] = $params[$p];
}
}
$newUrl = $urlParsed['scheme'] . '://' . $urlParsed['host'] . $urlParsed['path'] . '?' . http_build_query($newParams);
file_get_contents($newUrl);
I didn't test that code, but I hope the idea is clear and you can amend it to your needing.
I am working on a custom script to automatically send out invites and reminders. I have everything working fine up until a point. My function to send invites looks like this:
function sendInvites($iSurveyID) {
$oSurvey = Survey::model()->findByPk($iSurveyID);
if (!isset($oSurvey)) {
die("could not load survey");
}
if(!tableExists("{{tokens_$iSurveyID}}")) {
die("survey has no tokens or something");
}
$SQLemailstatuscondition = "emailstatus = 'OK'";
$SQLremindercountcondition = '';
$SQLreminderdelaycondition = '';
$iMaxEmails = (int)Yii::app()->getConfig("maxemails");
$iMaxReminders = 1;
if(!is_null($iMaxReminders)) {
$SQLremindercountcondition = "remindercount < " . $iMaxReminders;
}
$oTokens = Tokens_dynamic::model($iSurveyID);
$aResultTokens = $oTokens->findUninvited(false, $iMaxEmails, true, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
if (empty($aResultTokens)) {
die("No tokens to send invites to");
}
$aResult = emailTokens($iSurveyID, $aResultTokens, 'invite');
}
I also have a simple little file that starts up Yii:
Yii::createApplication('LSYii_Application', APPPATH . 'config/config' . EXT);
Yii::app()->loadHelper('admin/token');
Yii::app()->loadHelper('common');
Everything works as expected up until I actually try to send emails to the tokens. I've tracked the problem down to the following, on of the functions called by emailTokens has this in it:
$clang = Yii::app()->lang;
$aBasicTokenFields=array('firstname'=>array(
'description'=>$clang->gT('First name'),
'mandatory'=>'N',
'showregister'=>'Y'
),
The Yii::app()->lang part seems to be causing issues because then php is unable to call the gT method. However, when LimeSurvey is running "properly" this never happens. I can't even seem to find where "lang" is in the LimeSurvey source.
What can I do to make it work?
Why do you make it so hard on yourself and not use the RemoteControl2 API ?
See http://manual.limesurvey.org/wiki/RemoteControl_2_API#invite_participants
On that page you will also find a PHP example script.
maybe
Yii::import('application.libraries.Limesurvey_lang');
$clang = new Limesurvey_lang($oTokens->language);
I have drupal 7 question that may involve some php help. I have created an rss feed from google alerts that I am mapping into fields. I have had success mapping into all the fields except the link module field where I have put a field formatter that creates a pagepeeker screenshot by attaching the appropriate url server query to the feeds url. Feeds is doing its job by taking the Item URL (link) and putting it into the field correctly. I am having an issue with with either pagepeeker or link module because below keeps happening.
To recap-
Google Alert feed -> Link module field -> pagepeeker screenshot formatter
here's the error
The url that google alerts provides is
http://www.google.com/url?sa=X&q=http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius/&ct=ga&cad=CAcQARgAIAEoATAAOABA3t-Y_gRIAlgBYgVlbi1VUw&cd=F7w9TwL-6ao&usg=AFQjCNG2rbJCENvRR2_k6pL9RntjP66Rvg
When the link is displayed I get :
http://pagepeeker.com/thumbs.php?size=m&url=www.google.com/url
Its cutting the url at url and not getting the rest of the url.
Here's the code that pagepeeker uses to parse the url ?
<?php
function _pagepeeker_format_url($url, $domain_only = FALSE) {
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
return FALSE;
}
// try to parse the url
$parsed_url = parse_url($url);
if (!empty($parsed_url)) {
$host = (!empty($parsed_url['host'])) ? $parsed_url['host'] : '';
$port = (!empty($parsed_url['port'])) ? ':' . $parsed_url['port'] : '';
$path = (!empty($parsed_url['path'])) ? $parsed_url['path'] : '';
$query = (!empty($parsed_url['query'])) ? '?' . $parsed_url['query'] : '';
$fragment = (!empty($parsed_url['fragment'])) ? '#' . $parsed_url['fragment'] : '';
if ($domain_only) {
return $host . $port;
}
else {
return $host . $port . $path . $query . $fragment;
}
}
return FALSE;
}
Could this be the problem?
Please let me know I can clarify in any way.
What I need is for the entire url to get processed and not just the truncated one
Thanks !
I have seen a very similar question here at SO or drupal SO page but couldn't find it so I'm writing "my way" answer again here.
<?php
function _pagepeeker_format_url($url, $domain_only = FALSE) {
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
return FALSE;
}
//$url = 'http://www.google.com/url?sa=X&q=http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius/&ct=ga&cad=CAcQARgAIAEoATAAOABA3t-Y_gRIAlgBYgVlbi1VUw&cd=F7w9TwL-6ao&usg=AFQjCNG2rbJCENvRR2_k6pL9RntjP66Rvg';
// Now we use parse_url to split the url to an array with url parts.
$parsed_url = parse_url($url);
// $parsed_url['query'] is 'sa=X&q=http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius/&ct=ga&cad=CAcQARgAIAEoATAAOABA3t-Y_gRIAlgBYgVlbi1VUw&cd=F7w9TwL-6ao&usg=AFQjCNG2rbJCENvRR2_k6pL9RntjP66Rvg'
// ";" can also be used to separate params. But & is the usual one so using it.
$queryParts = explode('&', $parsed_url['query']);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
// sa = X, etc.
$params[$item[0]] = $item[1];
}
//$params is now an array with query parts.
// $params['sa'] = 'X' , q = 'http://www.beautyjunkiesunite.com/WP/2012/05/30/whats-new-anastasia-beverly-hills-lash-genius', etc.
if ($domain_only){
$new_url_parsts = parse_url($params['q']);
return $new_url_parts['host'];
}
else{
return $params['q'];
}
I am developing a site for a client and one of the requirements is to integrate worldpay payments for the purchasing process.
Once the user has completed payment for a product I need to alert a licencing system to the completed payment. The worldpay documentation gives an overview of the payment response service but does not give a code example.
I have had the client set up the payment response option in their test installation but would rather not have to go about coding my own page to handle the response if someone else has already done it. Does anyone have a link to a good code example (in php)?? I have had a decent look online and have not turned up much.
Thanks!
Problem solved. I ended up creating a custom class to handle the response from worldpay. Here is a simplified version of my handler page in case anyone else might find it useful.
(Note: I am not really a php developer so some syntax might be a bit dodgy!)
<?php //Worldpay
// class definition
class WorldPay_Response {
// define properties
public $transaction_id = null;
public $transaction_status = null;
public $transaction_time = null;
public $authorisation_amount = null;
public $authorisation_currency = null;
public $authorisation_amount_string = null;
public $raw_auth_message = null;
public $raw_auth_code = null;
public $callback_password = null;
public $card_type = null;
public $authentication = null;
public $ip_address = null;
public $character_encoding = null;
public $future_payment_id = null;
public $future_payment_status_change = null;
//custom properties not included by worldpay
public $mc_custom_property = null;
// constructor
public function __construct() {
$this->transaction_id = $_POST['transId'];
$this->transaction_status = $_POST['transStatus']; //should be either Y (successful) or C (cancelled)
$this->transaction_time = $_POST['transTime'];
$this->authorisation_amount = $_POST['authAmount'];
$this->authorisation_currency = $_POST['authCurrency'];
$this->authorisation_amount_string = $_POST['authAmountString'];
$this->raw_auth_message = $_POST['rawAuthMessage'];
$this->raw_auth_code = $_POST['rawAuthCode'];
$this->callback_password = $_POST['callbackPW'];
$this->card_type = $_POST['cardType'];
$this->country_match = $_POST['countryMatch']; //Y - Match, N - Mismatch, B - Not Available, I - Country not supplied, S - Issue Country not available
$this->waf_merchant_message = $_POST['wafMerchMessage'];
$this->authentication = $_POST['authentication'];
$this->ip_address = $_POST['ipAddress'];
$this->character_encoding = $_POST['charenc'];
$this->future_payment_id = $_POST['futurePayId'];
$this->future_payment_status_change = $_POST['futurePayStatusChange'];
//custom properties
$this->mc_custom_property = $_POST['MC_custom_property'];
}
}
?>
<html>
<head><title>Thank you for your payment</title></head>
<WPDISPLAY FILE="header.html">
<?php
//Response from Worldpay
$wp_response = new WorldPay_Response();
if($wp_response->transaction_status == "Y"){ ?>
<strong>Transaction Details</strong><br />
<?php
echo "Worldpay Transaction id: " . $wp_response->transaction_id . "<br />";
echo "Payment Status: " . $wp_response->transaction_status . "<br />";
echo "Transaction Time: " . $wp_response->transaction_time . "<br />";
echo "Amount: " . $wp_response->authorisation_amount_string . "<br />";
echo "IP Address: " . $wp_response->ip_address . "<br /><br />";
}else if($wp_response->transaction_status == "C") { ?>
<strong>Transaction Cancelled</strong>
<?php } else { ?>
Your transaction was unsuccessful.
<?php } ?>
<WPDISPLAY ITEM="banner">
<WPDISPLAY FILE="footer.html">
</html>
For others who are reading this from a Google search, re: worldpay Payment response.
March 2015:
I am setting up a worldpay online payment system for a client and damn, it's terrible. They have made a mediocre system in 2011 and not bothered updating it since. It is tedious and the code examples and documentation leaves a LOT to be desired.
Worldpay still use MD5() hashing as a "highly secure method of encryption" and are still referencing various resources and server concepts that are no longer used. From a practical programming point of view DO NOT USE WORLDPAY .
They have no documentation to handle dynamic payments and still expect each payment to be completed by me sending them a .html file for them to display, rather than them sending the customer back to my website to output dynamic code.
I would never touch WorldPay after this work, but my client has already paid them for signing up with them, and so I have to implement this for him. :-/
Their customer service (UK) is also very poor.
looks a lot like paypal. basically server<>server stuff. they have their 9 yards here. http://www.worldpay.com/support/kb/bg/pdf/custa.pdf are you looking for a full blown buy service center? b/c just receiving with a simple notification is a page or so. google has some open source stuff. http://code.google.com/p/opencart/source/browse/trunk/upload/catalog/language/english/payment/worldpay.php?spec=svn694&r=694. just google worldpay.php. if you find something, LET US KNOW. we have been considering offering WORLDPAY to our clients. My how they have changed in the last 5 years.
small class extension to the TGuimond - WorldPay_Response class:
<?php //Worldpay
class WorldPay_Response {
// define properties
public $transaction_id = null;
public $transaction_status = null;
public $transaction_time = null;
public $authorisation_amount = null;
public $authorisation_currency = null;
public $authorisation_amount_string = null;
public $raw_auth_message = null;
public $raw_auth_code = null;
public $callback_password = null;
public $card_type = null;
public $authentication = null;
public $ip_address = null;
public $character_encoding = null;
public $future_payment_id = null;
public $future_payment_status_change = null;
/* extension */
public $name = null;
public $address = null;
public $town = null;
public $email = null;
public $desc = null;
//custom properties not included by worldpay
public $mc_custom_property = null;
// constructor
public function __construct() {
$this->transaction_id = $_POST['transId'];
$this->transaction_status = $_POST['transStatus']; //should be either Y (successful) or C (cancelled)
$this->transaction_time = $_POST['transTime'];
$this->authorisation_amount = $_POST['authAmount'];
$this->authorisation_currency = $_POST['authCurrency'];
$this->authorisation_amount_string = $_POST['authAmountString'];
$this->raw_auth_message = $_POST['rawAuthMessage'];
$this->raw_auth_code = $_POST['rawAuthCode'];
$this->callback_password = $_POST['callbackPW'];
$this->card_type = $_POST['cardType'];
$this->country_match = $_POST['countryMatch']; //Y - Match, N - Mismatch, B - Not Available, I - Country not supplied, S - Issue Country not available
$this->waf_merchant_message = $_POST['wafMerchMessage'];
$this->authentication = $_POST['authentication'];
$this->ip_address = $_POST['ipAddress'];
$this->character_encoding = $_POST['charenc'];
$this->future_payment_id = $_POST['futurePayId'];
$this->future_payment_status_change = $_POST['futurePayStatusChange'];
if(isset($_POST['name'])){
$this->name = $_POST['name'];
}
if(isset($_POST['address'])){
$this->address = $_POST['address'];
}
if(isset($_POST['town'])){
$this->town = $_POST['town'];
}
if(isset($_POST['email'])){
$this->email = $_POST['email'];
}
if(isset($_POST['desc'])){
$this->desc = $_POST['desc'];
}
//custom properties
$this->mc_custom_property = $_POST['MC_custom_property'];
}
}