I am working on youtube api
and I want to get youtube video information using youtube video info JSON object
and I am using a code as given below but when I try to run this code it is showing error as "Video Is not cipher not needed to decode"
please help me to solve it out also tell me where is the problem in code
<?php
// Video with cipher signature
$video_id = "zDrNLZ1uJ2w";
// get_video_info url formation
// although for cipher signature we have to get the details from the video's webapge not from get_video_info object
$info_url = "http://www.youtube.com/get_video_info?el=detailpage&asv=3&video_id=".$video_id;
// youtube webpage url formation
$yt_url = 'http://www.youtube.com/watch?v='.$video_id.'&gl=US&persist_gl=1&hl=en&persist_hl=1';;
// get the contents from the url
$raw_data = file_get_contents($info_url);
// parse the data received and save it as an array
$output = array();
parse_str($raw_data,$output);
// check the status of the get_video_info object
if($output['status']=='ok'){
// check for the cipher signature
$cipher = (isset($output['use_cipher_signature']) && $output['use_cipher_signature']=='True') ? true : false;
// If cipher is true then we have to decode it
if($cipher == true){
// if cipher is true then we have to change the plan and get the details from the video's youtube wbe page
$yt_html = file_get_contents($yt_url);
// parse for the script containing the configuration
preg_match('/ytplayer.config = {(.*?)};/',$yt_html,$match);
$yt_object = #json_decode('{'.$match[1].'}') ;
/// check if we are able to parse data
if(!is_object($yt_object)){
echo 'Sorry! Unable to parse Data';
}else{
// parse available formats
$formats = $yt_object->args->url_encoded_fmt_stream_map;
// get the player id from assets section
$player_id = strbtwn($yt_object->assets->js,'html5player-','.js');
$player_id = explode("/", $player_id);
$player_id = $player_id[0];
echo 'Player ID: '.$player_id.'<br /><hr />';
// get the algo dictionary
// first check if the file exists
if(file_exists('./algo.json'))
$algos = json_decode(file_get_contents('algo.json'),true);
else{
// API call to fetch the algo dictionary
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
// saving the algo dictonary in local env for easy access
// Note: Developers should save the dictionary in their local env.
// Only make the API call for the new player ids which is not present in the algo dictionary.
// Repeated violation will results in IP ban.
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
}
/// check if the algo exist for the given player id
if(!array_key_exists($player_id, $algos)){
// if the algo dictionary is old then fetch a new one
$algos_dict = file_get_contents("http://api.gitnol.com/getAlgo.php?playerID=".$player_id);
file_put_contents('algo.json', $algos_dict);
$algos = json_decode($algos_dict,true);
$algo = $algos[$player_id][1];
}else{
$algo = $algos[$player_id][1];
}
echo 'Algo Used: '.$algo.'<br /><hr />';
// download links formation
$dlinks = array();
$links = explode(',',$formats);
echo 'Download links <br /><br />';
foreach ($links as $link) {
parse_str($link,$linkarr);
// parse link array one by one and decrypt the signature
$dlinks[$linkarr['itag']] = $linkarr['url'] . "&signature=" . decrypt($linkarr['s'],$algo);
echo $linkarr['itag'].'<br />';
echo $dlinks[$linkarr['itag']].'<br /><br />';
}
echo '<hr />';
}
}else{
echo 'Video Is not cipher not needed to decode';
}
}else{
echo 'Unable to get Video Info';
}
// string helper function
function strbtwn($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
// signature decoding
// parse the python string operation into php string operation
function decrypt($sig, $algo){
$funcarr = explode(' + ', $algo);
$decrypt = '';
foreach($funcarr as $singfunc){
$singfunc = substr($singfunc,2,-1);
$operators = explode(':', $singfunc);
if (sizeof($operators) == 1) {
$decrypt .= $sig[$operators[0]];
}
if (sizeof($operators) == 2) {
if($operators[0] == ''){
$decrypt .= substr($sig, 0 ,$operators[1]);
}
if($operators[1] == ''){
$decrypt .= substr($sig, $operators[0]);
}
if($operators[0] >= 0 && $operators[1] >= 0){
$decrypt .= substr($sig, $operators[0], $operators[1] - $operators[0]);
}
}
if (sizeof($operators) == 3) {
if($operators[0] == '' && $operators[1] == ''){
$decrypt .= strrev($sig);
}
if($operators[0] >=0 && $operators[1] == '' && $operators[0] != ''){
$decrypt .= strrev(substr($sig, 0, $operators[0] + 1));
}
if($operators[0] >=0 && $operators[1] >= 0 && $operators[0] != '' && $operators[1] != ''){
$decrypt .= strrev(substr($sig, $operators[1] + 1, $operators[0] - $operators[1]));
}
}
}
return $decrypt;
}
?>
According to your code $cipher is being set to false because 'use_cipher_signature' is not found in the $raw_data from file_get_contents($info_url).
Related
Basically, I have a table with 8 million codes for promotion. The contestant will enter the code on a gravity form, which will then query the database for code, once it is there the code will be marked as used, and the contestant should be redirected to the entry form. If not the form should tell the user code is invalid. This is my code below which I pulled from other sources because I am not a coder. However, when I submit, the correct code, it says incorrect. Any help will be appreciated just bear in mind I am not a programmer
add_filter( 'gform_field_validation_4', 'validate_code' );
function validate_code($validation_result){
$form = $validation_result['form'];
foreach( $form['fields'] as &$field ) {
if ( strpos( $field->cssClass, 'validate-code' ) === false ) {
continue;
}
}
$field_value = rgpost( "input_1" );
$is_valid = is_code( $field_value );
$validation_result['is_valid'] = false;
$field->failed_validation = true;
$field->validation_message = 'The code you have entered is not valid. Please enter another.';
$validation_result['form'] = $form;
return $validation_result;
}
function is_code($code){
$info = 'mysql response';
require_once(ABSPATH . '/wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo 'Unable to connect to server, please use the back button in your browser and resubmit the form';
exit();
}
$code = mysqli_real_escape_string($conn, $_POST['codes']);
$sql_check = mysqli_query($conn, "SELECT * FROM entrycode WHERE codes = '$code' AND valid = 0");
$sql_checkrows = mysqli_num_rows($sql_check);
if ($sql_checkrows > 0) {
$sql_update = "UPDATE entrycode SET used = 1 WHERE codes ='$code'";
if (mysqli_query($conn, $sql_update)) {
$info = mysqli_affected_rows($conn) . " Row updated.\n";
$info = 'success';
return true;
} else {
return false;
}
mysql_close($conn);
}
}
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://sample.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
so I modified the code from Phill, I am no longer getting the error, but the code is not being validated, as a matter of fact, any code I type in is valid., I am at a lost. My table is structured like this
entry codes table
ID
Codes
Used
34
98j65XF16
O
add_filter('gform_validation_4_1', 'validate_code');
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if($is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
// use this function to validate codes
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( $matched_codes > 0) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://demo.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
Updated function to validate codes:
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
this code i have still is not checking the database with codes for validation ,, all codes returning invalid code message
add_filter('gform_validation_2', 'validate_code');
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if(!is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
function is_code_valid($thiscode){
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_2', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$country = ($_POST['input_3']);
$success_url = 'https://sample.com/enter' . '/?code=' .$lead[1] .'&country=' .$country;
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
I have a script that allows me to convert a database from MySQL to Excel .xls format, It was a success,
here is the code
<?php
// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!
// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
$cdate = date("Y-m-d");
$dbhost = "localhost";
$dbuser = "-";
$dbpass = "-";
$dbname = "-";
$dbtable = "-";
$filename = "C:\xxx";
// END CHANGING STUFF
// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got
// them from some where else but hey it works so I am not going to question it
// just reuse
// This one makes the beginning of the xls file
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// This one makes the end of the xls file
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." ";
$qr = mysql_query( $q ) or die( mysql_error() );
//start the object
ob_start();
// start the file
xlsBOF();
// these will be used for keeping things in order.
$col = 0;
$row = 0;
// This tells us that we are on the first row
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
// Ok we are on the first row
// lets make some headers of sorts
if( $first )
{
// di comment karena ini ngasih label tabelnya, sepertinya nggak butuh
//foreach( $qrow as $k => $v )
//{
// // take the key and make label
// // make it uppper case and replace _ with ' '
// xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
// $col++;
//}
// prepare for the first real data row
$col = 0;
$row = 0;//$row++; // nyoba
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
//write the contents of the object to a file
file_put_contents($filename, ob_get_clean());
?>
this code produced a .xls file. I used Matlab to read my .xls file through readxls function, but it didn't recognize the value inside the .xls file as a numeric data, so my script on matlab couldn't make a matrix from reading my xls file. I had to convert it manually inside excel, there were some pop-ups near the value that offers me to convert it into numbers
If your goal is to take data from MySQL and put it in Matlab it might be easier to directly connect to MySQL from Matlab rather than sending the data through the xls format.
http://www.mathworks.com/help/database/ug/database.fetch.html
We are trying to interface between a MySQL database and Google API using ajax and php (on line 3 "phpsqlajax_dbinfo.php" dedfines the database info). We want to create a marker with the lat/long from Google API, but we get the fatal error on "add(Child)"
Actual error message : "Call to a member function addChild() on a non-object"
How can we get the db to register and store the info?
<?php
require_once("phpsqlajax_dbinfo.php");
$xml = ("mapPointInfo.xml") ;
$newLatLng = $_POST['latlng']; //new markers LatLng
$newLatLng = substr($newLatLng, 1, -1); //removes first and last characters of
newLatLng which are ( and )
list($newLat, $newLng) = explode(",", $newLatLng);
//$newLng = substr($newLng, 1, 0);
$locName = $_POST['geoNameMarker']; //geocoded or simple incremented site name
$markerComment = $_POST['createMarker']; //comment entered by user
$userName = $_POST['user']; //acquire username from session
$voteValue = "likes"; //acquire vote value if any
date_default_timezone_set('America/New_York');
$timeStamp = date("m/d/Y G:i"); //get timestamp
year:month:date:hour:minutes:seconds (example: 11:6:31:14:31:42)
if($markerComment == null || $markerComment == '' || $markerComment == ' '){
$markerComment = ' ';
}
$markerComment = htmlentities($markerComment, ENT_QUOTES);
$locName = htmlentities($locName, ENT_QUOTES);
$marker = $xml->addChild('marker');
$marker->addAttribute('lat', $newLat);
$marker->addAttribute('lng', $newLng);
$marker->addAttribute('name', $locName);
$marker->addAttribute('type', 'user-sug');
$comment = $marker->addChild('comment', $markerComment); //add information to
latest/last marker
$comment->addAttribute('user', $userName);
$comment->addAttribute('vote', 'likes');
$comment->addAttribute('time', $timeStamp);
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
header ('http://www.wmuhotspotmap.org/');
exit();
?>
The fatal error? You get a fatal error. What was it? I'm guessing it has something to do with the fact that $xml is a string, but you're for some reason doing $xml->addChild() as if it were an object with functions.
i have this js piece of code:
<script language="JavaScript" type="text/javascript">
var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
//more code
}
}
function getChatText()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
receiveReq.open("GET", 'getChat_xml.php?chat=1&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
</script>
and in getChat_xml i have this:
$xml = '<?xml version="1.0" ?><root>';
if(!isset($_GET['chat']))
{
$xml .='Your are not currently in a chat session. Enter a chat session here';
$xml .= '<message id="0">';
$xml .= '<user>Admin</user>';
$xml .= '<text>Your are not currently in a chat session. <a href="">Enter a chat session here</a></text>';
$xml .= '<time>' . date('h:i') . '</time>';
$xml .= '</message>';
}
else
{
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" .
" FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
$message_query = db_query($sql);
//Loop through each message and create an XML message node for each.
while($message_array = db_fetch_array($message_query))
{
$xml .= '<message id="' . $message_array['message_id'] . '">';
$xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
$xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
$xml .= '<time>' . $message_array['post_time'] . '</time>';
$xml .= '</message>';
}
}
$xml .= '</root>';
can anybody help here please?? dont understand how this works
thanks
After seeing the code you have posted, these problems come to mind...
You have not actually added an echo $xml; to output the generated XML.
Even after adding an 'echo' statement, you may get null responseXML (and hence an undefined getElementsByTagName) because of some errors in your PHP code (maybe the SQL query).
Even if your PHP code is right, you will get null responseXML because u have not sent proper content header (header('Content-Type: text/xml');).
Maybe a stupid question but are you actually echoing $xml in your getChat_xml.php file? I can see xmldoc.getElementsByTagName("message") returning null because it can't find any <message> elements because the DOM was never outputted by PHP. What happens when you view the file directly? : http://www.yoursite.com/getChat_xml.php?chat=1&last=xxx
Just a shot in the dark here, but try this:
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
if (message_nodes)
{
//more code
}
}
}
Been reading up on php and json and am trying this piece of code which is not working and I can't figure out why. Any help is appreciated.
I call a JavaScript function from my html file onLoad(). That function is
function getSched()
{
$.post("schedlz.php", {dat: ""+inputString+"", action: "searchSched"}, function(data)
{
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else //some error handler
}
function getRes(data)
{
var str="";
var obj = JSON.parse (data);
alert (data.length + " | " +obj + " | ");
return str;
}
In schedlz.php file
$conn = getDbConn();
mysql_select_db("myschedulez", $conn);
$result = mysql_query($sql,$conn) or die('Error: ' . mysql_error());
$rows = array();
while ($r = mysql_fetch_assoc($result))
{
// $rows['schedulez'][] = $r;
$rows[] = $r;
}
echo json_encode($rows);
mysql_close($conn);
The problem is that I get the data back in correct json format but when I parse it, there is no Object. What could be going wrong here?
You need to add the dataType parameter to your $.post, which in your case is json.
I'm also not sure if you closed $.post correctly in your sample so I'm adding the closing ); as well.
function getSched()
{
$.post("schedlz.php",
{dat: ""+inputString+"", action: "searchSched"},
function(data) {
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else {} //some error handler
},
'json'
);
}