Skip to content

Instantly share code, notes, and snippets.

@dvaisman dvaisman/4-7 HUAC
Last active Aug 29, 2015

Embed
What would you like to do?
DH HUAC Code Gist for 4-7-15
//PHP ACTION FORM
//conditional statement to execute block
//Example: if user selects 'witness type'(key) and 'friendly'(value), send query to DocCloud API
//QUESTIONS ON CONDITIONALS IN PHP:
// Knowing that the function: if (condition) {
// code to be executed if condition is true;
// if ($x == $y) {
//will this be read as: if x and y have same key/value pair, return true?
//Do we want a nesting if-statement? Pseudocode Example:
//if $witness_type is chosen
if witness_type chosen == "friendly"
execute block..
<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Witness Type: <br />
<select multiple name="witness_type[]">
<option value="friendly">Friendly</option>
<option value="unfriendly">Unfriendly</option>
</select><br />
<input type="submit" value="submit me!" />
</form>
<?php if (isset($witness_type) && $witness_type=="friendly") echo "checked";?>
value="friendly">Friendly //How to assign variable in PHP to read in JSON?
<input type="dropdown" name="witness_type"
<?php if (isset($witness_type) && $witness_type=="unfriendly") echo "checked";?>
value="unfriendly">Unfriendly //How to assign variable in PHP to read in JSON
//COMMENTS AND QUESTIONS:
//PHP uses objects and arrays. Arrays (lists) are indexed numerically
//Example of list: witness_occupation = [writer, producer, playwright, actor]
//Search will return value based on location in the list (eg, [0] will --> 'writer')
//But is this what we want? Key-value pairs seems a better solution. Can that be done
//simply by creating different values for the same keys (DocumentCloud allows this)
//Example: witness_type --> friendly; witness_type --> unfriendly
//In other words: We need an associative array: user-named keys that we've assigned to them
//*Note: pseudocode above is not parsed in appropriate syntax (json, php); meant only to provide examples
//More examples of tinkering with PHP action form script. QUESTIONS:
//Assigning variables: how to assign two values to a single variable (eg, $witness_type) in
//an associative array? Assigning multiple values to a single variable is more intuitive for lists
//eg: $witness_type = [friendly, unfriendly]
//but this changes how PHP interacts with JSON. In this case, the only way to retrieve all instances
//of [friendly], for example, is to retrive via numerical index.
//Should we be using an associative array or a numerical index? If numerical index, is the best JSON format:
//Each document scripted as an object within a larger object (or array?) documents
//Each document contains built-in metadata tags and our metadata tags
//For example, each document coded as $witness_type == friendly or ==unfriendly
//Would the pseudocode then be: [if $witness_type == friendly], return all $witness_type[0]?
<?php
//assign variables (in PHP or JSON?)
$witness_type == "friendly";
//conditional statement
if ($witness_type == "friendly") {
echo "SOMETHING"; //(eg, every document with $witness_type == "friendly")
} elseif ($witness_type == "unfriendly") {
echo "SOMETHING"; //(eg, every document with $witness_type == "unfriendly")
//if want error handling
} else {
echo "Please try again";
}
?>
//USE CURL TO ISSUE NETWORK REQUEST
//initialize curl session using request URL as a parameter
//use function curl_init to return a session handle
//Several ways to connect API to database
//DocCloud uses REST API
//This was adapted from REST API code
$url = 'http://www.documentcloud.org/api/';
$ch = curl_init($url);
//is this the right format for request url from DocCloud API?
//DocCloud API not reading user-built metadata tags, only built-in metadata tags
//SET CURL OPTIONS
//Questions: What curl options do we want? If DocCloud doesn't require an API authentication key,
//do we still need to include authorization in the curl setup?
//This example tells curl that we don't want the HTTP headers returned, but do want request data returned
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//response is returned by running curl_exec on session handle
//curl_close will close curl after executing the session
$response = curl_exec($session);
curl_close($session);
//Another example
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type: application/json',
'Authorization: token ' . $access_token)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
//METHOD CALL: ENCODE PHP INTO JSON STRING
//json_encode: returns JSON representative of a value
//Option #1: return as list
<?php
// Returns: ["friendly", "unfriendly"]
json_encode(array("friendly", "unfriendly"));
?>
//Option #2: return as associative array
//Will two values on the same key work with DocumentCloud? DC says yes, but has not worked for me
<?php
// Returns: {"witness_type":"friendly","witness_type":"unfriendly"}
json_encode(array("witness_type" => "friendly", "witness_type" => "unfriendly"));
?>
//SEARCH THROUGH JSON
//RETURN OBJECTS THAT MATCH SOME KEY AND VALUE IN JSON
//Search function written in JS
//Problem is that the JSON notation for our documents do not contain our created metadata tags
//Started playing with various search functions. Below is example of starting to tweak code
//this will return an array of objects according to key, value, or key and value matching
//Do we just need the code for key/value matching?
//Set JSON schema. Example below. Working on json schema using parser.
//Questions on using lists vs arrays
//Including search query taxonomy as word document
var json = '{"witness_type": "friendly", "witness_type": "unfriendly"}';
var js = JSON.parse(json);
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
//example to retrieve objects that match some key and value in JSON
console.log(getObjects(js,'witness_type','friendly'));
//returns objects where a key named witness_type has the value friendly
//RETURN JSON to PHP: DECODE JSON INTO PHP
//DISPLAY RESULTS
<?php
$json = '{"witness_type":"friendly","witness_type":"unfriendly"}'; //the json string being decoded
var_dump(json_decode($json));
var_dump(
json_decode($json)
);
?>
//Pseudocode: friendly/unfriendly
//If user submits "friendly", retrieve all documents tagged "friendly"
//PHP --> JSON --> PHP
// HTML --> PHP User submits data, gets parsed into PHP
//PHP --> API PHP calls the API using curl
//search JSON Encode JSON into PHP, search query
//JSON --> PHP Decode JSON into PHP
//Should I use an object or array?
//Each document as an object, coded with key-value pairs?
//Should I, and how, structure nested data in JSON?
//DocumentCloud JSON not reading user-inputed (eg,our) metadata tags.
//DocumentCloud JSON only reading built-in metadata tags (eg, doc title, doc ID)
//Should I conduct the specific search in PHP or JSON? I've seen both.
//JSON object v array—for two values (or more) on same key, should I use array and search
//through string objects (“friendly”, “unfriendly”) or match by key-value pair?
//If so, how to notate and search through? Eg:
{witnesses:
{witness_type:
//User form --> submit to PHP script
//HTML FORMS: GET or POST
//
//Use PHP to get data from client
//form action
//HTML and PHP
//Make request to DocumentCloud API from PHP*
//requires curl (?) or (url)
DocumentCloud API: http://www.documentcloud.org/api/
//Process the resulting JSON string
$json = json_encode(something)
Convert PHP Array or Object to JSON String
<?php
// Array
$someArray = [
[
"witness_type" => "friendly",
"witness_occupation" => "writer"
],
[
"witness_type" => "unfriendly",
"witness_occupation" => "musician"
]
];
// Convert Array to JSON String
$someJSON = json_encode($someArray);
echo $someJSON;
?>
Convert JSON String to PHP Array or Object
PHP >= 5.2.0 features a function, json_decode, that decodes a JSON string into a PHP variable.
By default it returns an object. The second parameter accepts a boolean that when set as true,
tells it to return the objects as associative arrays. You can learn more about the json_decode
function from PHP’s documentation.
<?php
// JSON string
$someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
// Convert JSON string to Object
$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data
?>
Loop through PHP Array or Object
<?php
// Loop through Object
$someObject = ...; // Replace ... with your PHP Object
foreach($someObject as $key => $value) {
echo $value->name . ", " . $value->gender . "<br>";
}
?>
DocumentCloud API Information
SPECS
API Provider http://www.documentcloud.org/homeAPI
Endpoint http://www.documentcloud.org/api/
API Homepage http://www.documentcloud.org/help/api
Primary Category News Services
Secondary Categories Cloud
Protocol/Formats JSON, REST
APIhub URL
Twitter Url http://twitter.com/documentcloud
Authentication Mode HTTP Basic Authentication
DH HUAC SEARCH TAXONOMY
DOCUMENTS:
DOCUMENT:
• ID: “ID”
• DATE: “DATE”
• SESSION #: “#”
• HEARING
o SUBJECT OF HEARING: “SUBJECT”
o HEARING LOCATION: “LOCATION”
o TYPE OF HEARING: “OPEN”/”CLOSED”
• INVESTIGATOR
o INVESTIGATOR TYPE:
• STAFF
• STAFFER NAME: “NAME”
• CONGRESS
• CONGRESS NAME: “NAME”
• CONGRESS STATE: “STATE”
• CONGRESS PARTY:
-“REPUBLICAN”
-“DEMOCRAT”
-“INDEPENDENT”
• WITNESS
o WITNESS PROFESSION:
• “PROFESSION” [drop-down list]
o WITNESS ORGANIZATION:
• “ORGANIZATION” [drop-down list]
o WITNESS ATTORNEY:
• “ATTORNEY” [drop-down list]
o REASON FOR APPEARANCE:
• “REASON” [drop-down list]
o WITNESS TYPE:
• “FRIENDLY
• "UNFRIENDLY”
o RESULT OF APPEARANCE:
• “RESULT” (drop-down list] (E.G., CONTEMPT, BLACKLIST, CONVINCTION”)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.