users ending up with the same id.... possible race condition? - mysql

I have inherited a piece of code from a Laravel 5 codebase that essentially takes an svg symbol, allows you to add effects and text, and saves it as an SVG that gets linked to a user's account. The system works, but every once and a while you will see that 2 customers will end up with the same "newAvatar->id" linked to their account. I have been scratching my brain as to why but can't seem to figure it out.
Would this be caused by some sort of race condition? Do I need to put a semaphore or mutex of some sort around this code?
public function createAvatar()
{
$status = 400;
$_data = array('error' => 'Unknown Error');
if (Input::has('avatar_svg'))
{
$svg = Input::get('avatar_svg');
$newAvatar = Avatar::create([
'svg_content' => $svg,
]);
if ($newAvatar) {
$status = 200;
$_data = array('avatarID' => $newAvatar->id);
}
}
//data is sent back as JSON to be processed by AngularJS
return Response::json([
'data' => $_data,
], $status, array(), JSON_PRETTY_PRINT);
}

Thanks to all for the help, but the answer was that users managed to find a path through the software that was never intended to be taken or possible.
It's amazing the things that people find when code goes live

Related

Read long text in Angular 2

I have a very long document - 40000 words - I would like to display in a styled manner, like html.
I need to display it with headers, paragraphs and bold styling.
I am building an Angular app. I tried loading the converted document as a local html, but it takes a very long time.
For instance, I tried this:
var html = this.http.get("../data.html").map(ref => {
console.log(html);
} );
Are there any other ways I can load this text? Maybe break it up into smaller chunks somehow?
Based on what you've provided with no other context:
You need to subscribe to the Observable otherwise, nothing will ever happen since Observable execution is lazy:
var html = this.http.get("../data.html")
.map(ref => {
console.log(html);
return ref;
})
.subscribe(ref => ...);
Also, you're using console.log(html) in your map, but html does not exist in the context of map so you would need to do something like:
var html = this.http.get("../data.html")
.map(ref => {
console.log(ref); // Does this log appear and what does it contain?
return ref;
})
.subscribe(ref => ...);
Finally, var html is an Observable not HTML so I'd probably rename this to something a bit more descriptive if you're passing it around and subscribing to the response:
const data$ = this.http.get("../data.html")
.map(ref => {
console.log(ref);
return ref;
});
// ... do other stuff
data$.subscribe(ref => ...);
Or if not passed chain it and subscribe which indicates the Observeable has completed:
this.http.get("../data.html")
.map(ref => {
console.log(ref);
return ref;
}).subscribe(ref => ...);
If this doesn't help answer the question it's because you haven't provided enough information, and I'd suggest answering:
In the second example what does console.log(ref) output?
Include more code that provides more context like do you use subscribe already and what does the data you're using look like?
Make an example in StackBlitz that replicates the issue. Just click Angular and you get a pre-made Angular application you can drop your code into and then people can hack directly on the issue. Takes tops 5 seconds to setup

Wiki - table content from an external source

Is it possible to have a wiki page with two tables reflecting the data from two different 3rd party sites?
If so, how to get it done? Will page templates be of any help here?
Short answer is no, there's no easy, built-in way to pull external content into a MediaWiki site. Allowing a third party to inject arbitrary content would be massive security risk.
Long answer is that anything is possible with extensions, either existing ones or ones you write yourself. The MediaWiki site has an entire category of listings for "Remote content extensions" that do this kind of thing in one form or another, with External Data looking particularly useful. You will need admin rights to install any of these, and you'll need to trust both the extension code and the data you pull in.
I already wrote exactly what you describe. Might be helpful for you.
# Define a setup function
$wgHooks['ParserFirstCallInit'][] = 'efStackOverflow_Setup';
# Add a hook to initialise the magic word
$wgHooks['LanguageGetMagic'][] = 'efStackOverflow_Magic';
function efStackOverflow_Setup( &$parser ) {
# Set a function hook associating the "example" magic word with our function
$parser->setFunctionHook( 'stag', 'efStackOverflow_Render' );
return true;
}
function efStackOverflow_Magic( &$magicWords, $langCode ) {
# Add the magic word
# The first array element is whether to be case sensitive, in this case (0) it is not case sensitive, 1 would be sensitive
# All remaining elements are synonyms for our parser function
$magicWords['stag'] = array(1, 'stag');
# unless we return true, other parser functions extensions won't get loaded.
return true;
}
function efStackOverflow_Render( $parser, $param1 = '', $param2 = '' ) {
// there was filtering
$modif = 0;
$cache_file_path = "cache/".$param1."_".$param2;
if (file_exists($cache_file_path))
$modif = time() - #filemtime ($cache_file_path);
if (file_exists($cache_file_path) and $modif < 60*60*24) {
return file_get_contents($cache_file_path);
}
$page = file_get_contents("http://www.google.com/rss/".$param1);
$xml = new SimpleXMLElement($page);
foreach ($xml as $key => $value) {
// do some
}
if (!empty($output))
file_put_contents($cache_file_path, $output);
return $output;
}
Mediawiki version was 1.16.

Integrate Facebook Credits with AS3-SDK

I’m trying to integrate Facebook Credits as a paying method using the as3-sdk. I managed to get “earn_credits” and “buy_credits” working. However the third and most important option, “buy_item”, doesn’t show up the pay dialog. Somehow the connection to the callback.php seems the reason for the issue. Note: I have typed in the callback URL in my apps settings, so I didn’t forget that. I use the example php file from the Facebook Developer docs.
This is my as3 code.
public static function buyItem ():void
{
var theAction:String = "buy_item";
var order_info:Object = { "item_id":"1a" };
var jOrder:String = JSON.encode(order_info);
var data:Object = {
action:theAction,
order_info:jOrder,
dev_purchase_params: {"oscif":true}
};
Facebook.ui("pay", data, purchaseCallback);
}
I think the json encoding might be the problem, but i'm not sure.
I use the example php file from the Facebook Developer docs (excerpt):
<?php
$app_secret = '***********************';
// Validate request is from Facebook and parse contents for use.
$request = parse_signed_request($_POST['signed_request'], $app_secret);
// Get request type.
// Two types:
// 1. payments_get_items.
// 2. payments_status_update.
$request_type = $_POST['method'];
// Setup response.
$response = '';
if ($request_type == 'payments_get_items') {
// Get order info from Pay Dialog's order_info.
// Assumes order_info is a JSON encoded string.
$order_info = json_decode($request['credits']['order_info'], true);
// Get item id.
$item_id = $order_info['item_id'];
// Simulutates item lookup based on Pay Dialog's order_info.
if ($item_id == '1a') {
$item = array(
'title' => '100 some game cash',
'description' => 'Spend cash in some game.',
// Price must be denominated in credits.
'price' => 1,
'image_url' => '**********************/banner1.jpg',
);
// Construct response.
$response = array(
'content' => array(
0 => $item,
),
'method' => $request_type,
);
// Response must be JSON encoded.
$response = json_encode($response);
}
Any help, is really appreciated.
Okay so I cannot confirm that this works but according to this forum, it does:
var title:String = "TITLE FOO";
var desc:String = "FOO";
var price:String = "200";
var img_url:String = [some image url];
var product_url:String = [some product url];
// create order info object
var order_info:Object = {
"title":title,
"description":desc,
"price":price,
"image_url":img_url,
"product_url":product_url
};
// calling the API ...
var obj:Object = {
method: 'pay.prompt',
order_info: order_info,
purchase_type: 'item',
credits_purchase: false
};
Facebook.ui('pay', obj, callbackFunction);
I see that this example differs from yours slightly on the AS3 side so hopefully this nfo will help you resolve your problem. I realize that this isn't the best way to go about answering questions but I can see after a couple of days on here, no one has a answered you so I figured anything could help at this point. :)
Thank you #Ascension Systems!
This worked out well and is much better than creating a pop-up via html, and using navigateToURL etc...
One caveat though, which caused your solution not to work for me initially:
If you are relying on the callback.php sample provided by Facebook ( at the end of this page: http://developers.facebook.com/docs/credits/callback/ ), then you need to add this tag to your order_info object:
var item_id:String = "1a";
var order_info:Object = {
"title":title,
"description":desc,
"price":price,
"image_url":img_url,
"product_url":product_url,
"item_id":item_id
};
Without item_id defined, the if statement in Facebook's callback.php ( if ($item_id == '1a') ... ) will fail, and you'll get an unpleasant window: "App Not Responding
The app you are using is not responding. Please try again later."

MediaWiki Extension question / suggestion

Complete beginner here. I want to create a new tab on each page that has a custom action. When clicked, it takes you to a new page which has custom HTML on it along with the text or the original article.
So far I could create a new Tab and could give a custom action mycustomaction to it. I am pasting what I did so far here. Please let me know if I am using the correct hooks etc. and what is a better way to achieve this basic functionality.
So far with their docs I have done this:
#Hook for Tab
$wgHooks['SkinTemplateContentActions'][] = 'myTab';
#Callback
function myTab( $content_actions) {
global $wgTitle;
$content_actions['0'] = array(
'text' => 'my custom label',
'href' => $wgTitle->getFullURL( 'action=mycustomaction' ),
);
return true;
}
#new action hook
$wgHooks['UnknownAction'][] = 'mycustomaction';
#callback
function mycustomaction($action, $article) {
echo $action;
return true;
}
This gives me error:
No such action
The action specified by the URL is invalid. You might have mistyped the URL, or followed an incorrect link. This might also indicate a bug in the software used by yourplugin
What I was doing wrong:
$content_actions[‘0’] should simply be $content_actions[] (minor nitpick)
$content_actions is passed-by-reference, it should be function myTab( &$content_actions ) {}
mycustomaction() should do something along the lines of
if ( $action == ‘mycustomaction’ ) {
do stuff; return false;
}
else {
return true;
}
It should use $wgOut->addHTML() instead of echo
Thanks a lot everyone for your help!

CakePHP - get last query run

I want to get the last query CakePHP ran. I can't turn debug on in core.php and I can't run the code locally. I need a way to get the last sql query and log it to the error log without effecting the live site. This query is failing but is being run.
something like this would be great:
$this->log($this->ModelName->lastQuery);
Thanks in advance.
For Cake 2.0, the query log is protected so this will work
function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
Tested in CakePHP v2.3.2
$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);
In CakePHP 1.x, the data you want is accessible in DataSource::_queriesLog. Cake doesn't really provide a getter method for this member, but the underlying language being PHP, nothing stops you from doing the following:
In app/app_model.php:
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
return end($logs);
}
You can use this inline.
$dbo = $this->Model->getDatasource();
// store old state
$oldStateFullDebug = $dbo->fullDebug;
// turn fullDebug on
$dbo->fullDebug = true;
// Your code here! eg.
$this->Model->find('all');
// write to logfile
// use print_r with second argument to return a dump of the array
Debugger::log(print_r($dbo->_queriesLog, true));
// restore fullDebug
$dbo->fullDebug = $oldStateFullDebug;
Simple you can use showLog() function
var_dump($this->YourModel->getDataSource()->showLog());
This is a very late answer, i know, but for whoever needs this in the future, you can always restrict setting debug to your IP, For example:
Configure::write('debug', 0);
if($_SERVER["REMOTE_ADDR"] == '192.168.0.100'){
Configure::write('debug', 2); //Enables debugging only for your IP.
}
Combination of Matt's and blavia's solution (works when debug is not 2):
$dbo = $this->Model->getDatasource();
$oldStateFullDebug = $dbo->fullDebug;
$dbo->fullDebug = true;
// find or whatever...
$this->Model->find("all");
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
CakeLog::write("DBLog", $lastLog['query']);
$dbo->fullDebug = $oldStateFullDebug;
Having a quick skim of the book, cakephp api getLog you could turn on logTransaction. Although having not used it, I'm not sure how it will perform.
Otherwise you could experiment with FirePHP and here is the a guide for it,
You might try DebugKit, although off the top of my head I think you do still need debug 2 to get it to work.
Hopefully something might give you a lead. :)
You can use this:
$log = $this->Model->getDataSource()->getLog(false, false);
pr($log);die;
There are two methods to view the query in CakePHP.
Both methods you have to add the below one line in app/Config/core.php
Configure::write('debug', 2);
First methods :
debug($this->getLastQuery());
where you want to get the query add above line and call this function getLastQuery() on same controller using below code
public function getLastQuery() {
$dbo = $this->TModel->getDatasource(); //Here TModel is a model.what table you want to print
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
second method :
add the below line in the any Elements files.
<?php echo $this->element('sql_dump'); ?>
This will help you.
echo '<pre>';
$log = $this->YOUR_MODEL->getDataSource();
print_r($log);
exit;