Ejemplo n.º 1
0
Archivo: dwbn.php Proyecto: jsib/curl
function dwbn_get_page($token, $page_uri)
{
    //Bind global variables
    global $oauth2_host;
    //Get full uri
    $uri = "https://" . $oauth2_host . $page_uri;
    //Connect via curl
    $ch = curl_init($uri);
    //Disable sertificates check for HTTPS
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //Show or not recieve header
    curl_setopt($ch, CURLOPT_HEADER, false);
    //Show or not sent header - will be presented by curl_getinfo()
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    //Header is here
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: ' . $oauth2_host, "Authorization: Bearer " . $token));
    //Return result to variable
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //Exec curl command
    $answer_json = curl_exec($ch);
    //Prepare JSON to show
    $answer_json_pretty = prettyPrint($answer_json);
    //Put info into variable
    $curl_getinfo = curl_getinfo($ch);
    //Close curl connection
    curl_close($ch);
    //Ruturn
    return array('curl_getinfo' => $curl_getinfo, 'answer_json' => $answer_json, 'answer_json_pretty' => $answer_json_pretty);
}
Ejemplo n.º 2
0
function dwbn_get_page($token, $page_uri)
{
    //Bind global variables
    global $oauth2_host;
    //Get full uri
    $uri = "https://" . $oauth2_host . $page_uri;
    //Connect using Google App Engine URL Fetch service
    $context = ['http' => ['method' => 'GET', 'header' => "Host: {$oauth2_host}\r\n" . "Authorization: Bearer " . $token . "\r\n"]];
    $context = stream_context_create($context);
    //Get answer from DWBN
    $answer_json = file_get_contents($uri, false, $context);
    //Prepare JSON to show
    $answer_json_pretty = prettyPrint($answer_json);
    //Ruturn
    return array('answer_json' => $answer_json, 'answer_json_pretty' => $answer_json_pretty);
}
Ejemplo n.º 3
0
function exportSongs()
{
    $db_connection = new mysqli('stardock.cs.virginia.edu', 'cs4750ams5daa', 'music', 'cs4750ams5da');
    if (mysqli_connect_errno()) {
        echo "Connection Error!";
        return;
    }
    /*	header('Content-type: text/xml');       
    	$data = '<?xml version="1.0" encoding="utf-8"?>';      
    	$data .= "<ReturnType><Data>Here is some data</Data></ReturnType>";       
    	echo "$data"; */
    $var = array();
    $sql = "SELECT * FROM Songs";
    $result = mysqli_query($db_connection, $sql);
    while ($obj = mysqli_fetch_object($result)) {
        $var[] = $obj;
    }
    header('Content-Type: application/json; charset=utf-8');
    $jsonStr = json_encode($var);
    echo '{"Songs":' . prettyPrint($jsonStr) . '}';
    //echo $jsonStr;
}
Ejemplo n.º 4
0
// Update an urban word that does not exist
// Throws an exception - Urban Word not found
//$urbanWordsManager->updateUrbanWord("TGIF", "Thank God It's Free", "OMG, TGIF");
echo '<h4>Updated Urban Word</h4>';
prettyPrint($updatedUrbanWord);
// Delete an Urban Word
$urbanWordsManager->deleteUrbanWord($slang3);
// Delete an Urban Word that does not exist
// Throws an exception
// $urbanWordsManager->deleteUrbanWord("Ganga");
echo '<h4>Result after deleting one of the Urban Words</h4>';
prettyPrint(UrbanWordsManager::$data);
// This section tests the WordsGroup Class
$sentence = "let us pretend Marhsal Mathers never picked up a pen, let us pretend things would have been no different, pretend he procrastinated had no motivation, pretend he just made excuses that were so paper thin.";
// The group function groups the words in the given
// statement into an associative array
$grouped = WordsGroup::group($sentence);
echo '<h3>Grouped Words Example</h3>';
echo '<h5>Original Sentence</h5>';
echo $sentence;
echo '<h5>Grouped</h5>';
prettyPrint($grouped);
/**
 * Hepler function to pretty print the data variables
 */
function prettyPrint($array)
{
    echo '<pre>';
    print_r((array) $array);
    echo '</pre>';
}
} else {
    if ($group_id) {
        // Attempt to load action permits for the specified group.
        if (!($results = loadGroupActionPermits($group_id))) {
            apiReturnError($ajax, getReferralPage());
        }
    } else {
        if ($all == "users") {
            // Attempt to load action permits for all users
            if (!($results = loadUserActionPermits("all"))) {
                apiReturnError($ajax, getReferralPage());
            }
        } else {
            if ($all == "groups") {
                // Attempt to load action permits for all groups
                if (!($results = loadGroupActionPermits("all"))) {
                    apiReturnError($ajax, getReferralPage());
                }
            } else {
                addAlert("danger", "user_id, group_id, or all must be specified.");
                apiReturnError($ajax, getReferralPage());
            }
        }
    }
}
restore_error_handler();
if ($pretty) {
    echo prettyPrint(json_encode($results, JSON_PRETTY_PRINT));
} else {
    echo json_encode($results);
}
Ejemplo n.º 6
0
                }
            }
        }
        if ($new_line_level !== NULL) {
            $result .= "\n" . str_repeat("\t", $new_line_level);
        }
        $result .= $char . $post;
    }
    return $result;
}
/* eat question mark and go from there */
$qs = $_SERVER['QUERY_STRING'];
if ($qs[0] == '?') {
    $qs = substr($qs, 1);
}
switch ($qs) {
    case 'ip':
        _h_json();
        echo prettyPrint(json_encode($_SERVER['REMOTE_ADDR']));
        return true;
    case 'headers':
        _h_json();
        $headers = apache_request_headers();
        echo prettyPrint(json_encode($headers));
        return true;
    default:
        define('C64LEGIT', true);
        return include 'redirector.php';
}
//unhandled
return false;
Ejemplo n.º 7
0
<?php

$style = new \Drupal\livesource\ArtistStyle(26);
$eventFormat = new \Drupal\livesource\EventFormatter($style);
$result = $eventFormat->setArtist()->formattedResults();
print prettyPrint(json_encode($result)) . "\n";
function prettyPrint($json)
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen($json);
    for ($i = 0; $i < $json_length; $i++) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if ($ends_line_level !== NULL) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ($in_escape) {
            $in_escape = false;
        } else {
            if ($char === '"') {
                $in_quotes = !$in_quotes;
            } else {
                if (!$in_quotes) {
                    switch ($char) {
                        case '}':
Ejemplo n.º 8
0
        }
        $result .= $char . $post;
        $prev_char = $char;
    }
    return $result;
}
?>

<form action="<?php 
echo Route::url('index.php?option=' . $this->option);
?>
" method="post" name="adminForm" id="adminForm">

	<table class="adminlist">
		<tbody>
			<tr>
				<td>
<pre>
<?php 
echo str_replace("\t", ' &nbsp; &nbsp;', prettyPrint(json_encode($this->output)));
?>
</pre>
				</td>
			</tr>
		</tbody>
	</table>

	<?php 
echo Html::input('token');
?>
</form>
Ejemplo n.º 9
0
 /**
  * Set miner config.
  * 
  * @param array $data
  *   The orig data from phpminer. (Optional, default = array())
  */
 public function set_config($data = array())
 {
     // Get current cgminer config.
     $conf = json_decode(file_get_contents($this->config['cgminer_config_path']), true);
     // When the value is empty, we have to remove it from the cgminer config.
     if (empty($data['value'])) {
         if (isset($conf[$data['key']])) {
             unset($conf[$data['key']]);
         }
     } else {
         // When we have a gpu key, then we have a multi value field. This means values can be seperated by , (comma).
         if (isset($data['gpu'])) {
             // If config key doesn't exist yet, create it.
             if (!isset($conf[$data['key']])) {
                 $conf[$data['key']] = '';
             }
             // Get current config values per gpu.
             $config_values = explode(",", $conf[$data['key']]);
             // If there are no config values yet, create an empty array.
             if (empty($config_values)) {
                 $config_values = array();
             }
             // Get the provided values, which should be set per gpu.
             $device_values = array();
             if (isset($data['current_values']) && !empty($data['current_values'])) {
                 $device_values = explode(",", $data['current_values']);
                 if (empty($device_values)) {
                     $device_values = array();
                 }
             }
             // Get the device count, so we can create the correct comma seperated value.
             $device_count = $data['devices'];
             // Loop through each device.
             for ($i = 0; $i < $device_count; $i++) {
                 // If the config key does not exist, fill it with 0.
                 if (!isset($config_values[$i])) {
                     $config_values[$i] = !isset($device_values[$i]) ? 0 : $device_values[$i];
                 }
             }
             // Set the given gpu value.
             $config_values[$data['gpu']] = $data['value'];
             // Get the end result of the config key with all gpu values.
             $conf[$data['key']] = implode(",", $config_values);
         } else {
             // Parse "true" to boolean true
             if ($data['value'] === 'true') {
                 $data['value'] = true;
             }
             // Parse "false" to boolean false
             if ($data['value'] === 'false') {
                 $data['value'] = false;
             }
             // Set new config key value.
             $conf[$data['key']] = $data['value'];
         }
     }
     // Try to store the new config.
     if (file_put_contents($this->config['cgminer_config_path'], str_replace('\\/', '/', prettyPrint(json_encode($conf)))) === false) {
         throw new Exception('Could not write config file');
     }
 }
Ejemplo n.º 10
0
    <table align="center">
    <tr>
      <th>Event ID</th>
      <th>Payload</th>
    </tr>
    <?php 
$sql_query = "SELECT * FROM events";
$result_set = mysql_query($sql_query);
while ($row = mysql_fetch_row($result_set)) {
    ?>
              <tr>
              <td><?php 
    echo $row[0];
    ?>
</td>
              <td><?php 
    echo prettyPrint($row[1]);
    ?>
</td>
              </tr>
    <?php 
}
?>
    </table>
    </div>
</div>

</center>
</body>
</html>
Ejemplo n.º 11
0
function ParseMap($mapname, $force = 0)
{
    global $datapath, $linebreak, $gametypelist, $mapdata_version;
    $entities_key = 'entities';
    $points_key = 'points';
    $controlpoints = array();
    $map_objects = array();
    $map = array();
    $reader = new KVReader();
    $dstfile = GetDataFile("maps/parsed/{$mapname}.json", null, null, -2);
    if (file_exists($dstfile)) {
        $dstdata = json_decode(file_get_contents($dstfile), true);
    }
    $srcfiles = array("CPSetup" => GetDataFile("maps/{$mapname}.txt"), "Overview" => GetDataFile("resource/overviews/{$mapname}.txt"), "VMF Source" => GetDataFile("maps/src/{$mapname}_d.vmf"));
    foreach ($srcfiles as $name => $file) {
        if (!file_exists($file)) {
            echo "FAIL: Missing {$name} \"{$file}\"!{$linebreak}";
            return;
        }
        // Get MD5 of source file
        $map['source_files'][$name] = md5_file($file);
    }
    $map['mapdata_version'] = $mapdata_version;
    // TODO: Proper KeyValues parser!!!
    // Load cpsetup.txt
    //echo "loading cpsetup\n";
    $data = $reader->read(strtolower(file_get_contents($srcfiles["CPSetup"])));
    //echo "done loading cpsetup\n";
    // Merge in bases
    foreach ($data as $name => $item) {
        if ($name == "#base") {
            //echo "found bases\n";
            if (!is_array($item)) {
                $item = array($item);
            }
            foreach ($item as $base) {
                //echo "merging {$base}\n";
                $data = array_merge_recursive($reader->read(strtolower(file_get_contents(GetDataFile("maps/{$base}")))), $data);
            }
            unset($data[$name]);
        }
    }
    //var_dump($data);
    // Process all nodes
    foreach ($data as $name => $item) {
        if (is_array($item)) {
            foreach ($item as $key => $val) {
                if (in_array($key, array_keys($gametypelist))) {
                    $map['gametypes'][$key] = $val;
                } else {
                    $map['CPSetup'][$key] = $val;
                }
            }
        }
    }
    //var_dump($map);
    // Load Overview
    //echo "starting load overview\n";
    //Get overview information (file, position, scale)
    $lines = file($srcfiles["Overview"], FILE_IGNORE_NEW_LINES);
    foreach ($lines as $line) {
        $data = explode("\t", preg_replace('/\\s+/', "\t", str_replace('"', '', trim($line))));
        if (isset($data[1])) {
            $map['overview'][$data[0]] = is_numeric($data[1]) ? (double) $data[1] : $data[1];
        }
    }
    //echo "done load overview\n";
    // Load VMF Source
    //Parse the decompiled VMF file
    if (file_exists($srcfiles["VMF Source"])) {
        //echo "start load vmf source\n";
        // Remove non-printable characters to make processing easier
        // Change to lowercase to make array indexing simpler
        $data = preg_replace('/[\\x00-\\x08\\x14-\\x1f]+/', '', strtolower(file_get_contents($srcfiles["VMF Source"])));
        // Quote all unquoted keys
        $data = preg_replace('/(\\s*)([a-zA-Z0-9]+)(\\s*{)/', '${1}"${2}"${3}', $data);
        // Get all nested objects
        preg_match_all('~[^{}]+ { ( (?>[^{}]+) | (?R) )* } ~x', $data, $matches);
        // Process entities
        //echo "start process entities\n";
        //var_dump($matches[0]);
        foreach ($matches[0] as $rawent) {
            // Read in KV
            $object = $reader->read($rawent);
            $type = implode('', array_keys($object));
            if ($type == "entity") {
                $entity = $object[$type];
            } else {
                continue;
            }
            //Only interested in certain entities
            $classnames = array("trigger_capture_zone", "point_controlpoint", "obj_weapon_cache", "ins_spawnzone", "ins_blockzone");
            if (in_array($entity['classname'], $classnames) !== false) {
                //echo "start processing {$entity['classname']} {$entity['id']}\n";
                //Special processing for capture zone
                /*
                				if ($entity['classname'] == "trigger_capture_zone") {
                //					continue;
                					$entity['targetname'] = $entity['controlpoint'];
                					$entity['classname'] = 'point_controlpoint';
                				}
                */
                // Create data structure for point
                $point = CreatePoint($entity, $map);
                $entname = $point['pos_name'];
                //if (!isset($point['pos_name'])) {
                //var_dump($point);
                //}
                //(isset($entity['controlpoint'])) ? $entity['controlpoint'] : $entity['targetname'];
                if (isset($entity['solid'])) {
                    if (isset($entity['solid']['is_multiple_array'])) {
                        $entity['solid'] = $entity['solid'][0];
                        //Temp hack for complex zones
                    }
                    $point['pos_type'] = 'area';
                    //This is silly, but I add together all the coordinates and average them to get the actual location on the map.
                    // I think a better way is to actually calculate the difference and average that way.
                    // TODO: Send all coord numbers into array, then sort and get min/max to average that way
                    $path = array();
                    foreach ($entity['solid']['side'] as $side) {
                        if (isset($side['plane'])) {
                            preg_match_all('#\\(([^)]+)\\)#', $side['plane'], $coord);
                            //Add coordinate to collection
                            foreach ($coord[1] as $xyz) {
                                $xyz = explode(' ', $xyz);
                                $vector = round(abs(($xyz[0] - $map['overview']['pos_x']) / $map['overview']['scale'])) . ',' . round(abs(($xyz[1] - $map['overview']['pos_y']) / $map['overview']['scale']));
                                //.','.round($xyz[2]/$map['overview']['scale']);
                                $path[$vector] = $vector;
                            }
                        }
                    }
                    //This is terrible logic that loops through the path points and calculates the high/low points for shape
                    if (count($path)) {
                        $min = array(0 => -1, 1 => -1);
                        $max = array(0 => -1, 1 => -1);
                        foreach ($path as $coord) {
                            $vector = explode(',', $coord);
                            $min[0] = $vector[0] < $min[0] || !isset($min[0]) || $min[0] < 0 ? $vector[0] : $min[0];
                            $min[1] = $vector[1] < $min[1] || !isset($min[1]) || $min[1] < 0 ? $vector[1] : $min[1];
                            $max[0] = $vector[0] > $max[0] || !isset($max[0]) ? $vector[0] : $max[0];
                            $max[1] = $vector[1] > $max[1] || !isset($max[1]) ? $vector[1] : $max[1];
                        }
                        // Count the sides to see if this is a square or not.
                        if (count($path) == 4) {
                            $point['pos_x'] = (int) $min[0];
                            $point['pos_y'] = (int) $min[1];
                            $point['pos_width'] = (int) ($max[0] - $min[0]);
                            $point['pos_height'] = (int) ($max[1] - $min[1]);
                            $point['pos_shape'] = 'rect';
                        } else {
                            $point['pos_shape'] = 'poly';
                            if ($point['pos_x'] < 1) {
                                unset($path["{$min[0]},{$min[1]}"]);
                                $point['pos_x'] = (int) $min[0];
                                $point['pos_y'] = (int) $min[1];
                            }
                            $point['pos_points'] = implode(' ', $path);
                        }
                    }
                    //echo "done processing {$entity['classname']} {$entity['id']}\n";
                }
                //Hackly logic to allow merging of cache/control point data gracefully no matter what order the entities come in
                foreach ($point as $key => $val) {
                    if (!isset($map[$points_key][$entname][$key])) {
                        $map[$points_key][$entname][$key] = $val;
                    }
                }
            }
            //echo "done process entities\n";
        }
        //echo "done parse vmf\n";
    }
    // Process combined data
    //Process game type data for this map
    foreach ($map['gametypes'] as $gtname => $gtdata) {
        //echo "start process gametypes\n";
        //Create an array called cps with the names of all the control points for this mode
        if (!isset($gtdata['controlpoint'])) {
            continue;
        }
        if (!is_array($gtdata['controlpoint'])) {
            $map['gametypes'][$gtname]['controlpoint'] = array($gtdata['controlpoint']);
        }
        $cps = $map['gametypes'][$gtname]['controlpoint'];
        //Process any entities in the gamedata text file.
        $entlist = array();
        if (!isset($gtdata[$entities_key])) {
            continue;
        }
        foreach ($gtdata[$entities_key] as $entname => $entity) {
            //var_dump($entname,$entity);
            //KV reader now handles multiple like-named resources by creating a numerically indexed array
            //When doing that, the is_multiple_array flag is set
            if (isset($entity['is_multiple_array'])) {
                //If multiple items, send each to the array
                foreach ($entity as $subent) {
                    if (is_array($subent)) {
                        $subent['classname'] = $entname;
                        $entlist[] = CreatePoint($subent, $map);
                    }
                }
            } else {
                //Otherwise, pack the single item
                $entity['classname'] = $entname;
                $entlist[] = CreatePoint($entity, $map);
            }
        }
        //Process all gamedata entities that are referenced by the controlpoints list
        foreach ($entlist as $id => $entity) {
            if (!isset($entity['pos_name'])) {
                continue;
            }
            $cp = $entity['pos_name'];
            //(isset($entity['controlpoint'])) ? $entity['controlpoint'] : $entity['targetname'];
            foreach ($entity as $key => $val) {
                if (!isset($map['gametypes'][$gtname][$points_key][$cp][$key]) || @$entity['targetname'] == $cp && $key != 'classname' || @$entity['targetname'] != $cp && $key == 'classname') {
                    $map['gametypes'][$gtname][$points_key][$cp][$key] = $val;
                }
            }
        }
        /*
        		//chr 65 is uppercase A. This lets me 'increment' letters
        		$chr = 65;
        		// Loop through control points and name them
        		foreach ($cps as $idx => $cp) {
        			$cpname = chr($chr);
        			unset($map['gametypes'][$gtname]['controlpoint'][$idx]);
        			$map['gametypes'][$gtname]['controlpoint'][$cpname] = (isset($map['gametypes'][$gtname][$points_key][$cp])) ? $map['gametypes'][$gtname][$points_key][$cp] : $map[$points_key][$cp];
        			//Set point name to the letter of the objective
        			//$map['gametypes'][$gtname][$points_key][$cp]
        			$map['gametypes'][$gtname]['controlpoint'][$cpname]['pos_name'] = $cpname;
        			if (isset($gtdata['attackingteam'])) {
        				$map['gametypes'][$gtname]['controlpoint'][$cpname]['pos_team'] = ($gtdata['attackingteam'] == 'security') ? 3 : 2;
        			}
        			$chr++;
        		}
        */
        //Bullshit to add teams to points, Skirmish game logic does it instead of saving it in the maps.
        if ($gtname == 'skirmish') {
            $map['gametypes'][$gtname]['controlpoint']['B']['pos_team'] = 2;
            $map['gametypes'][$gtname]['controlpoint']['D']['pos_team'] = 3;
        }
        //Same deal for Firefight
        if ($gtname == 'firefight') {
            $map['gametypes'][$gtname]['controlpoint']['A']['pos_team'] = 2;
            $map['gametypes'][$gtname]['controlpoint']['C']['pos_team'] = 3;
        }
        /*
        		//Parse spawn zones. This is tricky because there will usually be two zones with the same targetname
        		// but different teamnum. This is to allow spawning to move as the game changes I believe.
        		if (isset($gtdata['spawnzones'])) {
        			foreach ($gtdata['spawnzones'] as $szid => $szname) {
        				if (is_numeric($szid)) {
        					unset($map['gametypes'][$gtname]['spawnzones'][$szid]);
        					$sz = array();
        					foreach (array('_team2','_team3') as $suffix) {
        						if (isset($map[$points_key]["{$szname}{$suffix}"]))
        							$sz["{$szname}{$suffix}"] = $map[$points_key]["{$szname}{$suffix}"];
        					}
        					$map['gametypes'][$gtname]['spawnzones'][$szname] = $sz;
        				}
        			}
        		}
        		// Remove the points and entities sections from the finished data structure. We no longer need them.
        		if (@is_array($map['gametypes'][$gtname][$points_key])) {
        			unset($map['gametypes'][$gtname][$points_key]);
        		}
        		if (@is_array($map['gametypes'][$gtname][$entities_key])) {
        			unset($map['gametypes'][$gtname][$entities_key]);
        		}
        */
        //echo "done parse gametypes\n";
    }
    recur_ksort($map);
    $json = prettyPrint(json_encode($map));
    file_put_contents($dstfile, $json);
    echo "OK: Parsed {$mapname}{$linebreak}";
    //	var_dump(array_merge_recursive($srcfiles,$map['source_files']));
}
Ejemplo n.º 12
0
function cURL($jsonString)
{
    $protocol = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
    $options = array("url" => $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/../public/index.php");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $options["url"]);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($jsonString)));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    $res = prettyPrint($result, "API Response : ");
    echo "<br/><br/>";
    echo $res;
}
Ejemplo n.º 13
0
function GetServer($host, $port, $region = '', $cacheonly = 1, $forcerefresh = 0)
{
    global $paths, $columns, $server_file_maxage, $tag_values;
    $ip = gethostbyname($host);
    $server = array('region' => $region, 'info' => array('serverName' => "<b>[LOADING]</b>{$ip}:{$port}", 'mapName' => '', 'numberOfPlayers' => 0, 'maxPlayers' => 0, 'serverTags' => ''), 'tags' => array('g' => '', 'p' => '', 't' => '', 'pure' => ''), 'ipAddress' => $ip, 'port' => $port);
    /*
    	foreach ($columns as $column) {
    		if (!isset($server[$column])) {
    			$server[$column] = '';
    		}
    	}
    */
    $cache_file = "{$paths['servers']}/{$ip}_{$port}.json";
    // Should we use the cache file?
    if (file_exists($cache_file)) {
        $get_cache = filemtime($cache_file) > time() - $server_file_maxage && !$forcerefresh;
        if ($get_cache || $cacheonly) {
            $cache = json_decode(file_get_contents($cache_file), TRUE);
            $server = array_replace_recursive($server, $cache);
            //var_dump($cache,$server);
            //$server['updated'] = filemtime($cache_file);
            // If server has an error, attempt new fetch
            //$get_cache = (!isset($server['error']));
        }
    }
    // If the cached data is not available or has been invalidated, refresh
    if (!$cacheonly && (!$get_cache || $forcerefresh)) {
        try {
            $connection = new \SteamCondenser\Servers\SourceServer($ip, $port);
            $connection->initialize();
            // Collect data from Steam Condenser
            $server['ping'] = $connection->getPing();
            $server['players'] = $connection->getPlayers();
            $server['rules'] = $connection->getRules();
            $server['info'] = $connection->getServerInfo();
            $tags = array_filter(explode(',', $server['info']['serverTags']));
            foreach ($tags as $tag) {
                $bits = explode(':', $tag, 2);
                if (count($bits) == 2) {
                    $server['tags'][$bits[0]] = $tag_values[$bits[0]][$bits[1]] = $bits[1];
                } else {
                    $server['tags'][$tag] = $tag_values[$tag] = "__";
                }
            }
            $server['updated'] = time();
            file_put_contents($cache_file, prettyPrint(json_encode($server)), LOCK_EX);
        } catch (Exception $e) {
            //			echo 'Caught exception: ',  $e->getMessage(), "\n";
            $server['error'] = $e->getMessage();
            file_put_contents($cache_file, prettyPrint(json_encode($server)), LOCK_EX);
        }
    }
    // Skip processing for servers with errors
    if ($region) {
        $server['region'] = $region;
    }
    return $server;
}
Ejemplo n.º 14
0
    $line = fgets($file);
    echo $line . "<br>";
}
fclose($file);
?>
</code></pre>


              <p>Result:</p>

              <pre><code class="language-json"><?php 
$sample = explode(",", $response_json);
$sample = array_slice($sample, 0, 19);
$sample = implode(",", $sample);
$sample = str_replace("\\", "", $sample);
echo prettyPrint($sample);
?>

      ...     </code></pre>

              <p>If you want the result in standard php object, just decode it:</p>

              <pre><code class="language-php">$response = json_decode( $response_json );
//Prints the first item's text:
echo $response->data[0]->text;</code></pre>


              <h2>Notes</h2>

              <h3>Authentication</h3>
Ejemplo n.º 15
0
 function json_encode_helper($data, $pretty_print = FALSE)
 {
     $ret = json_encode((object) $data);
     $ret = str_replace('\\/', '/', $ret);
     if ($pretty_print) {
         $ret = prettyPrint($ret);
     }
     return $ret;
 }
Ejemplo n.º 16
0
        $AccountPrivileges = $row['AccountPrivileges'];
        $LastUpdateTime = $row['LastUpdateTime'];
        $avatar = $row["Avatar"];
        $avatarObj = json_decode($row["Avatar"], true);
        $gameobjects = $row["GameObjects"];
        $gameobjectsObj = json_decode($row["GameObjects"], true);
        $ClanId = $avatarObj['alliance_id'];
        $playerClan = "SELECT clan.ClanId, clan.LastUpdateTime, clan.Data FROM clan WHERE clan.ClanId=" . $ClanId;
        $playerClanResult = $conn->query($playerClan);
        if ($playerClanResult->num_rows > 0) {
            while ($playerClanRow = $playerClanResult->fetch_assoc()) {
                $clanData = json_decode($playerClanRow['Data'], true);
                $playerclan = $playerClanRow['Data'];
            }
        } else {
            $playerclan = "geen clan";
        }
        $players[] = array("PlayerId" => $row['PlayerId'], "AccountStatus" => $row['AccountStatus'], "AccountPrivileges" => $row['AccountPrivileges'], "LastUpdateTime" => $row['LastUpdateTime'], "avatar" => $avatar, "avatarObj" => $avatarObj, "gameobjects" => $gameobjects, "playerclan" => $playerclan, "clanID" => $clanData['alliance_id']);
    }
}
foreach ($players as $player) {
    $playername = $player['avatarObj']['avatar_name'];
    $ClanId = $player['avatarObj']['alliance_id'];
    $th = $player['avatarObj']['townhall_level'] + 1;
    echo "\n\t\t<div id='result'>\n\t\t\t<div id='details'>\n\t\t\t\t<h5>User details</h5>\n\t\t\t\t<ul>\n\t\t\t\t<li>Player id: " . $player["PlayerId"] . "</li>\n\t\t\t\t<li>Player name: " . $playername . "</li>\n\t\t\t\t<li>Town Hall level: " . $th . "</li>\n\t\t\t\t<li>Status: " . $player["AccountStatus"] . "</li>\n\t\t\t\t<li>Server Permissions: " . $player["AccountPrivileges"] . "</li>\n\t\t\t\t<li>Last online " . $player["LastUpdateTime"] . "</li>\n\t\t\t\t</ul>\n\t\t\t</div>\n\t\t\t<div id='ta'>\n\t\t\t\t<h5>Clan info " . $playername . "</h5>\n\t\t\t\t<form method='post' action='" . $_SERVER['PHP_SELF'] . "'>\n\t\t\t\t\t<input type='hidden' name='playerId' value='" . $player["PlayerId"] . "'>\n\t\t\t\t\t<input type='hidden' name='clanID' value='" . $player["clanID"] . "'>\n\t\t\t\t\t<textarea class='styled' name='playerclan'>" . prettyPrint($player['playerclan']) . "</textarea>\n\t\t\t\t\t<input type='submit' value='Update'>\n\t\t\t\t</form>\n\t\t\t</div>\n\t\t\t<div class='avatar-buildings'>\n\t\t\t\t<div class='avatar'>\n\t\t\t\t\t<h5>Avatar " . $playername . "</h5>\n\t\t\t\t\t<form method='post' action='" . $_SERVER['PHP_SELF'] . "'>\n\t\t\t\t\t\t<input type='hidden' name='playerId' value='" . $player["PlayerId"] . "'>\n\t\t\t\t\t\t<textarea class='styled' name='avatar'>" . prettyPrint($player['avatar']) . "</textarea>\n\t\t\t\t\t\t<input type='submit' value='Update'>\n\t\t\t\t\t</form>\n\t\t\t\t</div>\n\t\t\t\t<div class='buildings'>\n\t\t\t\t\t<h5>Buildings</h5> \n\t\t\t\t\t<form method='post' action='" . $_SERVER['PHP_SELF'] . "'>\n\t\t\t\t\t\t<input type='hidden' name='playerId' value='" . $player["PlayerId"] . "'>\n\t\t\t\t\t\t<textarea class='styled' name='gameObject'>" . prettyPrint($player['gameobjects']) . "</textarea>\n\t\t\t\t\t\t<input type='submit' value='Update'>\n\t\t\t\t\t</form>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t";
}
$conn->close();
?>
</div>
</body>
</html>
$auth = base64_encode("{$CREDENTIALS}");
$soap_do = curl_init("https://americas.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/AirService");
$header = array("Content-Type: text/xml;charset=UTF-8", "Accept: gzip,deflate", "Cache-Control: no-cache", "Pragma: no-cache", "SOAPAction: \"\"", "Authorization: Basic {$auth}", "Content-length: " . strlen($message));
//curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 30);
//curl_setopt($soap_do, CURLOPT_TIMEOUT, 30);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true);
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $message);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
// this will prevent the curl_exec to return result and will let us to capture output
$return = curl_exec($soap_do);
$file = "001-" . $Provider . "_AirAvailabilityRsp.xml";
// file name to save the response xml for test only(if you want to save the request/response)
$content = prettyPrint($return, $file);
parseOutput($content);
//print '<br>';
//echo $return;
//print '<br>';
//print_r(curl_getinfo($soap_do));
//Pretty print XML
function prettyPrint($result, $file)
{
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($result);
    $dom->formatOutput = true;
    //call function to write request/response in file
    outputWriter($file, $dom->saveXML());
    return $dom->saveXML();
Ejemplo n.º 18
0
function DisplayModSelection($compare = 0, $type = 'theater')
{
    $fields = array('mod', 'version', $type);
    $fieldname = $ext = $type;
    $suffix = $compare ? '_compare' : '';
    $js = $vars = $data = array();
    $path = array("{$type}s");
    foreach ($fields as $field) {
        switch ($field) {
            case 'theater':
                $fieldname = 'theaterfile';
                array_unshift($path, 'scripts');
                break;
            case 'map':
                $path = array('resource', 'overviews');
            default:
                $fieldname = $field;
        }
        $data[$field] = $suffix ? $GLOBALS["{$fieldname}{$suffix}"] == $GLOBALS[$fieldname] ? '-' : $GLOBALS["{$fieldname}{$suffix}"] : $GLOBALS[$fieldname];
        echo "{$field}: <select name='{$field}{$suffix}' id='{$field}{$suffix}'></select>\n";
        $vars[$field] = $data[$field];
        $jsf = $field == $type ? 'item' : $field;
        $js[] = "var select_{$jsf}{$suffix} = \$('#{$field}{$suffix}');";
        $js[] = "var cur_{$jsf}{$suffix} = '{$vars[$field]}';";
    }
    // If showing comparison options, put in blank as first entry to denote no comparison
    if ($compare) {
        $vars['data']['-']['-']['-'] = '-';
    }
    // Populate data hash
    foreach ($GLOBALS['mods'] as $mname => $mdata) {
        foreach ($mdata as $vname => $vdata) {
            foreach ($path as $key) {
                if (!isset($vdata[$key])) {
                    continue 2;
                }
                $vdata =& $vdata[$key];
            }
            foreach ($vdata as $tname => $tpath) {
                $bn = preg_replace('/\\.[^\\.]+$/', '', basename($tname));
                if ($type == 'map') {
                    if (!GetDataFile("maps/parsed/{$bn}.json")) {
                        continue;
                    }
                }
                $vars['data'][$mname][$vname][$bn] = $bn;
            }
        }
    }
    ?>
<script type="text/javascript">
jQuery(function($) {
	var data = <?php 
    echo prettyPrint(json_encode($vars['data']));
    ?>
;
	<?php 
    echo implode("\n\t", $js) . "\n";
    ?>

	$(select_mod).change(function () {
		var mod = $(this).val(), vers = data[mod] || [];
		var html =  $.map(Object.keys(vers).sort().reverse(), function(ver){
			return '<option value="' + ver + '">' + ver + '</option>'
		}).join('');
		select_version.html(html);
		select_version.change();
	});

	$(select_version).change(function () {
		var version = $(this).val(), mod = $(select_mod).val(), values = data[mod][version] || [];
		var html =  $.map(Object.keys(values), function(item){
			return '<option value="' + item + '">' + item + '</option>'
		}).join('');
		select_item.html(html);
		select_item.change();
	});
	var html =  $.map(Object.keys(data), function(mod){
		return '<option value="' + mod + '">' + mod + '</option>'
	}).join('');
	select_mod.html(html);
	select_mod.val(cur_mod);
	select_mod.change();
	select_version.val(cur_version);
	select_version.change();
	select_item.val(cur_item);
	select_item.change();
});
</script>
<?php 
}
    }
    $file = "003-" . $PROVIDER . "_HotelBookReq.xml";
    // file name to save the request xml for test only(if you want to save the request/response)
    prettyPrint($message, $file);
    //Calling the Pretty Print function
    //
    // Run the request
    //
    $result = runRequest($message);
    // send the request as parameter to the function
    $_SESSION["content"] = $result;
    // if you do not intend to save response in file use this to use the response for further processing
    //call function to pretty print xml
    $file = "003-" . $PROVIDER . "_HotelBookRsp.xml";
    // file name to save the response xml for test only(if you want to save the request/response)
    prettyPrint($result, $file);
    require_once 'bookingConfirmation.php';
}
//Parse the previous response to get the values to populate Request xml
function parseDetailOutput()
{
    //$hotelDetailRsp = file_get_contents('002_HotelDetailRsp.xml'); // Parsing the Hotel Detail Response xml
    $hotelDetailRsp = $_SESSION["content"];
    //use this if response is not saved anywhere else use above variable
    $xml = simplexml_load_String("{$hotelDetailRsp}", null, null, 'SOAP', true);
    if (!$xml) {
        header("Location: http://LocationOfErrorPage/projects/Hotel/error.php");
        // Use the location of the error page
    }
    $Results = $xml->children('SOAP', true);
    foreach ($Results->children('SOAP', true) as $fault) {
Ejemplo n.º 20
0
    protected $AProt = "C.AProt";
    public $APub = "C.APub";
    private $CPriv = "C.CPriv";
    protected $CProt = "C.BProt";
    public $CPub = "C.CPub";
    function audit()
    {
        return parent::audit() && isset($this->APriv, $this->AProt, $this->APub, $this->BProt, $this->BPub, $this->CPriv, $this->CProt, $this->CPub);
    }
}
function prettyPrint($obj)
{
    echo "\n\nBefore serialization:\n";
    var_dump($obj);
    echo "Serialized form:\n";
    $ser = serialize($obj);
    $serPrintable = str_replace("", '\\0', $ser);
    var_dump($serPrintable);
    echo "Unserialized:\n";
    $uobj = unserialize($ser);
    var_dump($uobj);
    echo "Sanity check: ";
    var_dump($uobj->audit());
}
echo "-- Test instance of A --\n";
prettyPrint(new A());
echo "\n\n-- Test instance of B --\n";
prettyPrint(new B());
echo "\n\n-- Test instance of C --\n";
prettyPrint(new C());
echo "Done";
Ejemplo n.º 21
0
/**
 * Retrieve even more specific Item-Data and store them. See above, "saveItems"
 * @param $db - Database
 */
function saveItemData($db)
{
    global $apiKey;
    $arr = json_decode(cURL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=from,into,tags&api_key=" . $apiKey), true);
    foreach ($arr["data"] as $val) {
        if (!empty($val["tags"])) {
            prettyPrint($val["tags"]);
            foreach ($val["tags"] as $tag) {
                $stmt = $db->mysqli->prepare("INSERT INTO `ItemTags` (`ItemID`, `Tag`) VALUES (?, ?)");
                $stmt->bind_param("is", $val["id"], $tag);
                $stmt->execute();
                $stmt->close();
            }
        }
        if (!empty($val["from"])) {
            foreach ($val["from"] as $from) {
                $stmt = $db->mysqli->prepare("INSERT INTO `ItemBuildsFrom` (`ItemID`, `BuildsFromID`) VALUES (?, ?)");
                $stmt->bind_param("is", $val["id"], $from);
                $stmt->execute();
                $stmt->close();
            }
        }
        if (!empty($val["into"])) {
            foreach ($val["into"] as $into) {
                $stmt = $db->mysqli->prepare("INSERT INTO `ItemBuildsInto` (`ItemID`, `BuildsIntoID`) VALUES (?, ?)");
                $stmt->bind_param("is", $val["id"], $into);
                $stmt->execute();
                $stmt->close();
            }
        }
    }
}
Ejemplo n.º 22
0
            echo $user['cne']['centro_electoral'];
            ?>
</div>
            <?php 
        }
        ?>
        </div>
        <?php 
    }
    ?>
    <br /><div class="clearfix"> </div><br />
    <div class="heading"><span>Datos retornados por el API</span></div>
    <div class="clearfix"> </div>
    <div class="col-md-12">
        <pre><?php 
    echo prettyPrint($consulta);
    ?>
</pre>
    </div>
    <?php 
}
?>
    <script>
      var myCallBack = function() {
        grecaptcha.render('recaptcha1', {
          'sitekey' : '<?php 
echo RECAPTCHAR_KEY;
?>
', //Replace this with your Site key
          'theme' : 'light'
        });
Ejemplo n.º 23
0
if ($_REQUEST['listtype']) {
    if (in_array($_REQUEST['listtype'], array_keys($lists[$version]))) {
        $listtype = $_REQUEST['listtype'];
    }
}
//var_dump($lists,$version,$listtype);
// If we don't have sane values, abort
if (!$version || !$listtype) {
    echo "Data not found";
    include "{$includepath}/footer.php";
    exit;
}
$data = GetCVARList($version, $listtype);
if ($_REQUEST['fetch'] == 'list') {
    header('Content-Type: application/json');
    echo prettyPrint(json_encode($data));
    exit;
}
//Start display
startbody();
DisplayCVARList($data);
require_once "{$includepath}/footer.php";
exit;
function DisplayCVARList($data)
{
    global $version, $listtype, $lists;
    //Collect Headers
    $header = "";
    foreach (array_keys(current($data)) as $field) {
        $header .= "<th>{$field}</th>";
    }
Ejemplo n.º 24
0
					</tr>
					<tr>
						<td><strong>' . letheglobal_date . '</strong></td>
						<td>' . ($sr->Get('subscriber_date') == '' ? '<span class="text-danger glyphicon glyphicon-ban-circle"></span>' : setMyDate($sr->Get('subscriber_date'), 1)) . '</td>
					</tr>
					<tr>
						<td><strong>' . letheglobal_phone . '</strong></td>
						<td>' . ($sr->Get('subscriber_phone') == '' ? '<span class="text-danger glyphicon glyphicon-ban-circle"></span>' : showIn($sr->Get('subscriber_phone'), 'page')) . '</td>
					</tr>
					<tr>
						<td><strong>' . letheglobal_company . '</strong></td>
						<td>' . ($sr->Get('subscriber_company') == '' ? '<span class="text-danger glyphicon glyphicon-ban-circle"></span>' : showIn($sr->Get('subscriber_company'), 'page')) . '</td>
					</tr>
					<tr>
						<td><strong>' . subscribers_full_data . '</strong></td>
						<td><pre><code class="language-javascript">' . ($sr->Get('subscriber_full_data') == '' ? '<span class="text-danger glyphicon glyphicon-ban-circle"></span>' : prettyPrint(showIn($buildJSON, 'page'))) . '</code></pre></td>
					</tr>
					<tr>
						<td><strong>' . subscribers_status . '</strong></td>
						<td>' . getBullets($sr->Get('subscriber_active')) . '</td>
					</tr>
					<tr>
						<td><strong>' . letheglobal_verification . '</strong></td>
						<td>' . getBullets($sr->Get('subscriber_verify')) . '</td>
					</tr>
					<tr>
						<td><strong>' . subscribers_subscriber_key . '</strong></td>
						<td><code>' . $sr->Get('subscriber_key') . '</code></td>
					</tr>
					<tr>
						<td><strong>' . letheglobal_created . '</strong></td>
Ejemplo n.º 25
0
            $data = $_REQUEST['theaterdata'];
            //GenerateTheater();
            $filename = $_REQUEST['filename'];
            header('Content-type: text/plain');
            header("Content-Disposition: attachment; filename=\"{$filename}\"");
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . strlen($data));
            echo stripslashes($data);
            exit;
            break;
    }
    if (isset($fetch_data)) {
        header('Content-Type: application/json');
        echo prettyPrint(json_encode($fetch_data));
        exit;
    }
}
/*
<script>
	$(document).ready(function(){
		$(".toggle-section").click(function(){
			var target = "#" + $(this).attr('id').replace("header-","");
			$(target).toggle();
		});
	});
	$('#tbody').on('click', 'td.details-control', function () {
		var tr = $(this).closest('tr');
		var row = table.row( tr );
 
Ejemplo n.º 26
0
// Get one user from the users table
$user = User::getOne(3);
//
echo '<h3>One User</h3>';
prettyPrint($user);
// Create a new user
$user = new User();
$user->name = "Jin Kazama";
$user->age = 21;
$user->address = "525 Kindaruma";
$user->company = "466 Video Productions";
$user->save();
$users = User::getAll();
echo '<h3>All Users</h3>';
prettyPrint($users);
// Edit an existing user
$user = User::find(1000);
$user->name = "Anthony Steven";
$user->save();
$users = User::getAll();
echo '<h3>All Users (3rd edited)</h3>';
prettyPrint($users);
// Delete a user
User::destroy(2);
$user_del = User::getAll();
echo '<h3>All Users (id 2 deleted)</h3>';
prettyPrint($user_del);
function prettyPrint($data)
{
    echo '<pre>' . print_r($data, true);
}
            if ($source_key === "catalog") {
                ?>
                                   Catalog Report
                                <?php 
            } else {
                ?>
                                   Report for identifier: <?php 
                echo !empty($validation['source'][$source_key]->identifier) ? $validation['source'][$source_key]->identifier : '';
                ?>
                                <?php 
            }
            ?>
                            </h4>

                            <pre><code><?php 
            print htmlentities(prettyPrint(str_replace('\\/', '/', json_encode($validation['source'][$source_key]))));
            ?>
</code></pre>
                        </div>

                        <div class="validation-errors col-md-6">
                            <h4>Errors</h4>
                    <?php 
        }
        ?>

                    <?php 
        if (!empty($error['ALL'])) {
            ?>

                            <ul class="validation-full-record">
Ejemplo n.º 28
0
            if ($menu_item->menu_item_parent > 0) {
                $json .= '{' . '"' . 'name' . '":' . '"' . esc_attr($menu_item->title) . '",' . '"' . 'link' . '":' . '"' . esc_attr(fixUrl($menu_item->url)) . '",' . '"' . 'id' . '":' . '"' . $menu_item->db_id . '",' . '"' . 'parent_id' . '":' . '"' . $menu_item->menu_item_parent . '",' . '"Parent":' . '"No"' . '}';
            } else {
                $json .= '{' . '"' . 'name' . '":' . '"' . esc_attr($menu_item->title) . '",' . '"' . 'link' . '":' . '"' . esc_attr(fixUrl($menu_item->url)) . '",' . '"' . 'id' . '":' . '"' . $menu_item->db_id . '",' . '"Parent":' . '"' . $parent . '"' . '}';
            }
            if ($count != $count_menu_items - 1) {
                $json .= ",";
            }
            $count++;
        }
        $json .= '],';
    }
}
$json = rtrim($json, ',');
$json .= '});';
print prettyPrint($json);
function fixUrl($url)
{
    if (false === strpos($url, '//')) {
        $url = home_url($url);
    }
    $url = str_replace(array('http://', 'https://'), '//', $url);
    return $url;
}
/**
 * @param $json
 *
 * @return string
 */
function prettyPrint($json)
{
/**
 * List Matching Products Action Sample
 * ListMatchingProducts can be used to
 * find products that match the given criteria.
 *   
 * @param MarketplaceWebServiceProducts_Interface $service instance of MarketplaceWebServiceProducts_Interface
 * @param mixed $request MarketplaceWebServiceProducts_Model_ListMatchingProducts or array of parameters
 */
function invokeListMatchingProducts(MarketplaceWebServiceProducts_Interface $service, $request)
{
    try {
        $response = $service->listMatchingProducts($request);
        echo "Service Response\n";
        echo "=============================================================================\n";
        echo "        ListMatchingProductsResponse\n";
        if ($response->isSetListMatchingProductsResult()) {
            echo "            ListMatchingProductsResult\n";
            $listMatchingProductsResult = $response->getListMatchingProductsResult();
            if ($listMatchingProductsResult->isSetProducts()) {
                echo "                Products\n";
                $products = $listMatchingProductsResult->getProducts();
                $productList = $products->getProduct();
                foreach ($productList as $product) {
                    echo "                    Product\n";
                    if ($product->isSetIdentifiers()) {
                        echo "                        Identifiers\n";
                        $identifiers = $product->getIdentifiers();
                        if ($identifiers->isSetMarketplaceASIN()) {
                            echo "                            MarketplaceASIN\n";
                            $marketplaceASIN = $identifiers->getMarketplaceASIN();
                            if ($marketplaceASIN->isSetMarketplaceId()) {
                                echo "                                MarketplaceId\n";
                                echo "                                    " . $marketplaceASIN->getMarketplaceId() . "\n";
                            }
                            if ($marketplaceASIN->isSetASIN()) {
                                echo "                                ASIN\n";
                                echo "                                    " . $marketplaceASIN->getASIN() . "\n";
                            }
                        }
                        if ($identifiers->isSetSKUIdentifier()) {
                            echo "                            SKUIdentifier\n";
                            $SKUIdentifier = $identifiers->getSKUIdentifier();
                            if ($SKUIdentifier->isSetMarketplaceId()) {
                                echo "                                MarketplaceId\n";
                                echo "                                    " . $SKUIdentifier->getMarketplaceId() . "\n";
                            }
                            if ($SKUIdentifier->isSetSellerId()) {
                                echo "                                SellerId\n";
                                echo "                                    " . $SKUIdentifier->getSellerId() . "\n";
                            }
                            if ($SKUIdentifier->isSetSellerSKU()) {
                                echo "                                SellerSKU\n";
                                echo "                                    " . $SKUIdentifier->getSellerSKU() . "\n";
                            }
                        }
                    }
                    if ($product->isSetAttributeSets()) {
                        echo "  AttributeSets\n";
                        $attributeSets = $product->getAttributeSets();
                        if ($attributeSets->isSetAny()) {
                            $nodeList = $attributeSets->getAny();
                            echo prettyPrint($nodeList);
                        }
                    }
                    if ($product->isSetRelationships()) {
                        echo "  Relationships\n";
                        $relationships = $product->getRelationships();
                        if ($relationships->isSetAny()) {
                            $nodeList = $relationships->getAny();
                            echo prettyPrint($nodeList);
                        }
                    }
                    if ($product->isSetCompetitivePricing()) {
                        echo "                        CompetitivePricing\n";
                        $competitivePricing = $product->getCompetitivePricing();
                        if ($competitivePricing->isSetCompetitivePrices()) {
                            echo "                            CompetitivePrices\n";
                            $competitivePrices = $competitivePricing->getCompetitivePrices();
                            $competitivePriceList = $competitivePrices->getCompetitivePrice();
                            foreach ($competitivePriceList as $competitivePrice) {
                                echo "                                CompetitivePrice\n";
                                if ($competitivePrice->isSetCondition()) {
                                    echo "                            condition";
                                    echo "\n";
                                    echo "                                    " . $competitivePrice->getCondition() . "\n";
                                }
                                if ($competitivePrice->isSetSubcondition()) {
                                    echo "                            subcondition";
                                    echo "\n";
                                    echo "                                    " . $competitivePrice->getSubcondition() . "\n";
                                }
                                if ($competitivePrice->isSetBelongsToRequester()) {
                                    echo "                            belongsToRequester";
                                    echo "\n";
                                    echo "                                    " . $competitivePrice->getBelongsToRequester() . "\n";
                                }
                                if ($competitivePrice->isSetCompetitivePriceId()) {
                                    echo "                                    CompetitivePriceId\n";
                                    echo "                                        " . $competitivePrice->getCompetitivePriceId() . "\n";
                                }
                                if ($competitivePrice->isSetPrice()) {
                                    echo "                                    Price\n";
                                    $price = $competitivePrice->getPrice();
                                    if ($price->isSetLandedPrice()) {
                                        echo "                                        LandedPrice\n";
                                        $landedPrice = $price->getLandedPrice();
                                        if ($landedPrice->isSetCurrencyCode()) {
                                            echo "                                            CurrencyCode\n";
                                            echo "                                                " . $landedPrice->getCurrencyCode() . "\n";
                                        }
                                        if ($landedPrice->isSetAmount()) {
                                            echo "                                            Amount\n";
                                            echo "                                                " . $landedPrice->getAmount() . "\n";
                                        }
                                    }
                                    if ($price->isSetListingPrice()) {
                                        echo "                                        ListingPrice\n";
                                        $listingPrice = $price->getListingPrice();
                                        if ($listingPrice->isSetCurrencyCode()) {
                                            echo "                                            CurrencyCode\n";
                                            echo "                                                " . $listingPrice->getCurrencyCode() . "\n";
                                        }
                                        if ($listingPrice->isSetAmount()) {
                                            echo "                                            Amount\n";
                                            echo "                                                " . $listingPrice->getAmount() . "\n";
                                        }
                                    }
                                    if ($price->isSetShipping()) {
                                        echo "                                        Shipping\n";
                                        $shipping = $price->getShipping();
                                        if ($shipping->isSetCurrencyCode()) {
                                            echo "                                            CurrencyCode\n";
                                            echo "                                                " . $shipping->getCurrencyCode() . "\n";
                                        }
                                        if ($shipping->isSetAmount()) {
                                            echo "                                            Amount\n";
                                            echo "                                                " . $shipping->getAmount() . "\n";
                                        }
                                    }
                                }
                            }
                        }
                        if ($competitivePricing->isSetNumberOfOfferListings()) {
                            echo "                            NumberOfOfferListings\n";
                            $numberOfOfferListings = $competitivePricing->getNumberOfOfferListings();
                            $offerListingCountList = $numberOfOfferListings->getOfferListingCount();
                            foreach ($offerListingCountList as $offerListingCount) {
                                echo "                                OfferListingCount\n";
                                if ($offerListingCount->isSetCondition()) {
                                    echo "                            condition";
                                    echo "\n";
                                    echo "                                    " . $offerListingCount->getCondition() . "\n";
                                }
                                if ($offerListingCount->isSetValue()) {
                                    echo "                            Value";
                                    echo "\n";
                                    echo "                                    " . $offerListingCount->getValue() . "\n";
                                }
                            }
                        }
                        if ($competitivePricing->isSetTradeInValue()) {
                            echo "                            TradeInValue\n";
                            $tradeInValue = $competitivePricing->getTradeInValue();
                            if ($tradeInValue->isSetCurrencyCode()) {
                                echo "                                CurrencyCode\n";
                                echo "                                    " . $tradeInValue->getCurrencyCode() . "\n";
                            }
                            if ($tradeInValue->isSetAmount()) {
                                echo "                                Amount\n";
                                echo "                                    " . $tradeInValue->getAmount() . "\n";
                            }
                        }
                    }
                    if ($product->isSetSalesRankings()) {
                        echo "                        SalesRankings\n";
                        $salesRankings = $product->getSalesRankings();
                        $salesRankList = $salesRankings->getSalesRank();
                        foreach ($salesRankList as $salesRank) {
                            echo "                            SalesRank\n";
                            if ($salesRank->isSetProductCategoryId()) {
                                echo "                                ProductCategoryId\n";
                                echo "                                    " . $salesRank->getProductCategoryId() . "\n";
                            }
                            if ($salesRank->isSetRank()) {
                                echo "                                Rank\n";
                                echo "                                    " . $salesRank->getRank() . "\n";
                            }
                        }
                    }
                    if ($product->isSetLowestOfferListings()) {
                        echo "                        LowestOfferListings\n";
                        $lowestOfferListings = $product->getLowestOfferListings();
                        $lowestOfferListingList = $lowestOfferListings->getLowestOfferListing();
                        foreach ($lowestOfferListingList as $lowestOfferListing) {
                            echo "                            LowestOfferListing\n";
                            if ($lowestOfferListing->isSetQualifiers()) {
                                echo "                                Qualifiers\n";
                                $qualifiers = $lowestOfferListing->getQualifiers();
                                if ($qualifiers->isSetItemCondition()) {
                                    echo "                                    ItemCondition\n";
                                    echo "                                        " . $qualifiers->getItemCondition() . "\n";
                                }
                                if ($qualifiers->isSetItemSubcondition()) {
                                    echo "                                    ItemSubcondition\n";
                                    echo "                                        " . $qualifiers->getItemSubcondition() . "\n";
                                }
                                if ($qualifiers->isSetFulfillmentChannel()) {
                                    echo "                                    FulfillmentChannel\n";
                                    echo "                                        " . $qualifiers->getFulfillmentChannel() . "\n";
                                }
                                if ($qualifiers->isSetShipsDomestically()) {
                                    echo "                                    ShipsDomestically\n";
                                    echo "                                        " . $qualifiers->getShipsDomestically() . "\n";
                                }
                                if ($qualifiers->isSetShippingTime()) {
                                    echo "                                    ShippingTime\n";
                                    $shippingTime = $qualifiers->getShippingTime();
                                    if ($shippingTime->isSetMax()) {
                                        echo "                                        Max\n";
                                        echo "                                            " . $shippingTime->getMax() . "\n";
                                    }
                                }
                                if ($qualifiers->isSetSellerPositiveFeedbackRating()) {
                                    echo "                                    SellerPositiveFeedbackRating\n";
                                    echo "                                        " . $qualifiers->getSellerPositiveFeedbackRating() . "\n";
                                }
                            }
                            if ($lowestOfferListing->isSetNumberOfOfferListingsConsidered()) {
                                echo "                                NumberOfOfferListingsConsidered\n";
                                echo "                                    " . $lowestOfferListing->getNumberOfOfferListingsConsidered() . "\n";
                            }
                            if ($lowestOfferListing->isSetSellerFeedbackCount()) {
                                echo "                                SellerFeedbackCount\n";
                                echo "                                    " . $lowestOfferListing->getSellerFeedbackCount() . "\n";
                            }
                            if ($lowestOfferListing->isSetPrice()) {
                                echo "                                Price\n";
                                $price1 = $lowestOfferListing->getPrice();
                                if ($price1->isSetLandedPrice()) {
                                    echo "                                    LandedPrice\n";
                                    $landedPrice1 = $price1->getLandedPrice();
                                    if ($landedPrice1->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $landedPrice1->getCurrencyCode() . "\n";
                                    }
                                    if ($landedPrice1->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $landedPrice1->getAmount() . "\n";
                                    }
                                }
                                if ($price1->isSetListingPrice()) {
                                    echo "                                    ListingPrice\n";
                                    $listingPrice1 = $price1->getListingPrice();
                                    if ($listingPrice1->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $listingPrice1->getCurrencyCode() . "\n";
                                    }
                                    if ($listingPrice1->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $listingPrice1->getAmount() . "\n";
                                    }
                                }
                                if ($price1->isSetShipping()) {
                                    echo "                                    Shipping\n";
                                    $shipping1 = $price1->getShipping();
                                    if ($shipping1->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $shipping1->getCurrencyCode() . "\n";
                                    }
                                    if ($shipping1->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $shipping1->getAmount() . "\n";
                                    }
                                }
                            }
                            if ($lowestOfferListing->isSetMultipleOffersAtLowestPrice()) {
                                echo "                                MultipleOffersAtLowestPrice\n";
                                echo "                                    " . $lowestOfferListing->getMultipleOffersAtLowestPrice() . "\n";
                            }
                        }
                    }
                    if ($product->isSetOffers()) {
                        echo "                        Offers\n";
                        $offers = $product->getOffers();
                        $offerList = $offers->getOffer();
                        foreach ($offerList as $offer) {
                            echo "                            Offer\n";
                            if ($offer->isSetBuyingPrice()) {
                                echo "                                BuyingPrice\n";
                                $buyingPrice = $offer->getBuyingPrice();
                                if ($buyingPrice->isSetLandedPrice()) {
                                    echo "                                    LandedPrice\n";
                                    $landedPrice2 = $buyingPrice->getLandedPrice();
                                    if ($landedPrice2->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $landedPrice2->getCurrencyCode() . "\n";
                                    }
                                    if ($landedPrice2->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $landedPrice2->getAmount() . "\n";
                                    }
                                }
                                if ($buyingPrice->isSetListingPrice()) {
                                    echo "                                    ListingPrice\n";
                                    $listingPrice2 = $buyingPrice->getListingPrice();
                                    if ($listingPrice2->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $listingPrice2->getCurrencyCode() . "\n";
                                    }
                                    if ($listingPrice2->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $listingPrice2->getAmount() . "\n";
                                    }
                                }
                                if ($buyingPrice->isSetShipping()) {
                                    echo "                                    Shipping\n";
                                    $shipping2 = $buyingPrice->getShipping();
                                    if ($shipping2->isSetCurrencyCode()) {
                                        echo "                                        CurrencyCode\n";
                                        echo "                                            " . $shipping2->getCurrencyCode() . "\n";
                                    }
                                    if ($shipping2->isSetAmount()) {
                                        echo "                                        Amount\n";
                                        echo "                                            " . $shipping2->getAmount() . "\n";
                                    }
                                }
                            }
                            if ($offer->isSetRegularPrice()) {
                                echo "                                RegularPrice\n";
                                $regularPrice = $offer->getRegularPrice();
                                if ($regularPrice->isSetCurrencyCode()) {
                                    echo "                                    CurrencyCode\n";
                                    echo "                                        " . $regularPrice->getCurrencyCode() . "\n";
                                }
                                if ($regularPrice->isSetAmount()) {
                                    echo "                                    Amount\n";
                                    echo "                                        " . $regularPrice->getAmount() . "\n";
                                }
                            }
                            if ($offer->isSetFulfillmentChannel()) {
                                echo "                                FulfillmentChannel\n";
                                echo "                                    " . $offer->getFulfillmentChannel() . "\n";
                            }
                            if ($offer->isSetItemCondition()) {
                                echo "                                ItemCondition\n";
                                echo "                                    " . $offer->getItemCondition() . "\n";
                            }
                            if ($offer->isSetItemSubCondition()) {
                                echo "                                ItemSubCondition\n";
                                echo "                                    " . $offer->getItemSubCondition() . "\n";
                            }
                            if ($offer->isSetSellerId()) {
                                echo "                                SellerId\n";
                                echo "                                    " . $offer->getSellerId() . "\n";
                            }
                            if ($offer->isSetSellerSKU()) {
                                echo "                                SellerSKU\n";
                                echo "                                    " . $offer->getSellerSKU() . "\n";
                            }
                        }
                    }
                }
            }
        }
        if ($response->isSetResponseMetadata()) {
            echo "            ResponseMetadata\n";
            $responseMetadata = $response->getResponseMetadata();
            if ($responseMetadata->isSetRequestId()) {
                echo "                RequestId\n";
                echo "                    " . $responseMetadata->getRequestId() . "\n";
            }
        }
        echo "            ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n";
    } catch (MarketplaceWebServiceProducts_Exception $ex) {
        echo "Caught Exception: " . $ex->getMessage() . "\n";
        echo "Response Status Code: " . $ex->getStatusCode() . "\n";
        echo "Error Code: " . $ex->getErrorCode() . "\n";
        echo "Error Type: " . $ex->getErrorType() . "\n";
        echo "Request ID: " . $ex->getRequestId() . "\n";
        echo "XML: " . $ex->getXML() . "\n";
        echo "ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n";
    }
}
Ejemplo n.º 30
0
function postFeed($request)
{
    global $db, $url, $username, $password;
    try {
        $end_point = $url . "sellers/skus/listings/bulk";
        $auth_token = base64_encode($username . '-' . $password);
        $body = json_encode($request);
        echo $json_string = prettyPrint($body);
        $ch = curl_init($end_point);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Indusdiva Flipkart StockSync Cron');
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_FAILONERROR, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
        $response = curl_exec($ch);
        echo $response;
        curl_close($ch);
        $response = json_decode($response);
        if ($response->status === 'success') {
            foreach ($request->listings as $listing) {
                $id_sku = $listing->skuId;
                $attr_values = $listing->attributeValues;
                $mrp = $attr_values->mrp;
                $stock_count = $attr_values->stock_count;
                $selling_price = $attr_values->selling_price;
                $procurement_sla = $attr_values->procurement_sla;
                $listing_status = $attr_values->listing_status;
                $usql = "update ps_flipkart_feed_product_info set mrp = '{$mrp}', selling_price = '{$selling_price}', procurement_sla = '{$procurement_sla}', stock_count = '{$stock_count}', listing_status = '{$listing_status}', status = 1 where id_sku = '{$id_sku}'";
                $db->ExecuteS($usql);
            }
            return true;
        } else {
            send_tech_mail('Stock Sync Flipkart Failure', json_encode($request->listings));
            foreach ($request->listings as $listing) {
                $id_sku = $listing->skuId;
                $usql = "update ps_flipkart_feed_product_info set status = 0 where id_sku = '{$id_sku}'";
                $db->ExecuteS($usql);
            }
            return false;
        }
    } catch (Exception $ex) {
        return false;
    }
}