//the function throws an exception which we can catch to fail gracefully.
    $access_token = GetOAuthToken($api_key, $api_secret);
} catch (Exception $e) {
    echo $e->getMessage();
    // For this script we're just echoing the error and stopping the rest of the script.
    exit;
    // in your code you'll want to handle the error and recover appropriately.
}
echo "<p>Access Token = {$access_token}</p>";
// MAKE API CALL
// The next example gets the recent weather observations for the field location that you just created.
// Note we're creating the URL first, using the variables from the header.php file.
echo "<hr><h1>Get Recent Weather Observations</h1>";
$observedWeatherURL = 'https://api.awhere.com/v2/weather/fields/' . $new_field_id . '/observations/' . $observed_weather_start . ',' . $observed_weather_end;
try {
    $observedWeatherResponse = makeAPICall('GET', $observedWeatherURL, $access_token, $observedWeatherStatusCode, $observedWeatherResponseHeaders);
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
if ($observedWeatherStatusCode == 200) {
    // Code 200 means the request was successful
    echo '<p>You requested ' . count($observedWeatherResponse->observations) . " days of historical " . "observed weather. The weather on " . date("F j, Y", strtotime($observedWeatherResponse->observations[0]->date)) . " was a high temperature of " . $observedWeatherResponse->observations[0]->temperatures->max . "&deg;" . $observedWeatherResponse->observations[0]->temperatures->units . " and a low of " . $observedWeatherResponse->observations[0]->temperatures->min . "&deg;" . $observedWeatherResponse->observations[0]->temperatures->units . "</p>";
    echo '<p>Request:</p><pre>GET ' . $observedWeatherURL . '</pre>';
    echo '<p>Content-Range Header:</p>';
    // HTTP transactions return a lot of headers, but in this example we only want the Content-Range header
    // (the parseHTTPHeaders function returns just the headers you want)
    // This API returns a ranged result, which are paginated by default to 50 results per page. The
    // Content-Range header shows which of the results are on this page (e.g., 1-10) and the total number
    // of results. It looks something like this:
    // Content-Range: observations 0-5/5
    }
    ?>
    
    </select>
  </div>
</div>

<!-- Select Basic -->
<div class="control-group">
  <label class="control-label" for="project">to this project:</label>
  <div class="controls">
    <select id="projects" name="projects" class="input-xlarge">
    <?php 
    /// need to call multiple times because only 50 at a time are returned
    for ($j = 1; $j < 6; $j++) {
        $projects = makeAPICall("https://www.producteev.com/api/networks/" . $producteevNetworkID . "/projects?page={$j}");
        $projectsObj = json_decode($projects['content']);
        //print_r($projectsObj);
        $projectsArray = $projectsObj->projects;
        for ($i = 0; $i < count($projectsArray); $i++) {
            ?>
	  <option value="<?php 
            echo $projectsArray[$i]->id;
            ?>
"><?php 
            echo $projectsArray[$i]->title;
            ?>
</option>  
	    <?php 
        }
    }
//We'll set up all three API URLs here.
//Note that the sort order of responses is not guaranteed, and could change in the future.
//In this example we want to compare dates and days, so we'll force the API to sort the
//results based on calendar order, so that we know each object in the range matches the
//correct day and date.
$observedWeatherURL = 'https://api.awhere.com/v2/weather/fields/' . $new_field_id . '/observations/' . $observed_weather_start . ',' . $observed_weather_end . "?sort=-date" . "&units=usa";
// and we're requesting data in units standard to the USA
// (e.g., Fahrenheit & inches)
$threeYearNormsURL = 'https://api.awhere.com/v2/weather/fields/' . $new_field_id . '/norms/' . $month_day_start . ',' . $month_day_end . "/years/" . $three_year_start_year . ',' . $end_year . "?sort=-day" . "&units=usa";
// USA-units
$tenYearNormsURL = 'https://api.awhere.com/v2/weather/fields/' . $new_field_id . '/norms/' . $month_day_start . ',' . $month_day_end . "/years/" . $ten_year_start_year . ',' . $end_year . "?sort=-day" . "&units=usa";
// Next we'll run all three API calls sequentially.
try {
    $observedWeatherResponse = makeAPICall('GET', $observedWeatherURL, $access_token, $observedWeatherStatusCode, $observedWeatherResponseHeaders);
    $threeYearNormsResponse = makeAPICall('GET', $threeYearNormsURL, $access_token, $threeYearNormsStatusCode, $threeYearNormsResponseHeaders);
    $tenYearNormsResponse = makeAPICall('GET', $tenYearNormsURL, $access_token, $tenYearNormsStatusCode, $tenYearNormsResponseHeaders);
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
if ($observedWeatherStatusCode == 200 && $threeYearNormsStatusCode == 200 && $tenYearNormsStatusCode == 200) {
    echo '<table>';
    echo "<tr><th>Weather Attribute</th><th>Current Actual</th><th>3-Year Norm<br><small>{$three_year_start_year}&ndash;{$end_year}</small></th><th>10-Year Norm<br><small>{$ten_year_start_year}&ndash;{$end_year}</small></th></tr>";
    foreach ($observedWeatherResponse->observations as $index => $data) {
        echo '<tr class="date-row"><td colspan="4">Comparing <b>' . date("n-j-Y", strtotime($data->date)) . '</b> to the averages of <b>' . $threeYearNormsResponse->norms[$index]->day . '-' . $three_year_start_year . ' through ' . $threeYearNormsResponse->norms[$index]->day . '-' . $end_year . '</b> and <b>' . $tenYearNormsResponse->norms[$index]->day . '-' . $ten_year_start_year . ' through ' . $tenYearNormsResponse->norms[$index]->day . '-' . $end_year . '</b>' . '</td></tr>';
        echo '<tr>';
        echo '<td>Max Temperature</td>';
        echo '<td>' . round($data->temperatures->max, 1) . '&deg;' . $data->temperatures->units . '</td>';
        echo '<td>' . round($threeYearNormsResponse->norms[$index]->maxTemp->average, 1) . '&deg;' . $threeYearNormsResponse->norms[$index]->maxTemp->units . '</td>';
        echo '<td>' . round($tenYearNormsResponse->norms[$index]->maxTemp->average, 1) . '&deg;' . $tenYearNormsResponse->norms[$index]->maxTemp->units . '</td>';
        echo '</tr><tr>';
<?php

session_start();
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
/*
curl -v -X POST --data '{ "networks":[], "projects":[], "priorities":[4, 5], "statuses":[0], "responsibles":["51e83dd4fa46341808000a58"],"creators":[], "labels":[], "deadline":{}, "created_at":{}, "updated_at":{"from":1372636800, "to":1375315199}, "search":{}}' "https://www.producteev.com/api/tasks/search" --header "Content-Type:application/json" --header "Authorization:Bearer 5Fm-kYL08PpPU3VkYzTbCNO3-Ldzk8-COtjp3_7Xmto"
*/
if ($_REQUEST['labelid']) {
    //print_r($_SESSION);
    include_once "include.php";
    $data = '{ "networks":["' . $producteevNetworkID . '"], "projects":[], "priorities":[], "statuses":[0], "responsibles":[],"creators":[], "labels":["' . $_REQUEST['labelid'] . '"], "deadline":{}, "created_at":{}, "updated_at":{}, "search":{}}';
    ?>
<ol>
<?php 
    for ($j = 1; $j < 3; $j++) {
        $tasks = makeAPICall("https://www.producteev.com/api/tasks/search?sort=created_at&order=desc&page={$j}", $data);
        //	print_r($tasks);
        $tasksObj = json_decode($tasks['content']);
        $tasksArray = $tasksObj->tasks;
        for ($i = 0; $i < count($tasksArray); $i++) {
            ?>
	    <li>
	  <strong><?php 
            echo $tasksArray[$i]->title;
            ?>
</strong> <em>in project <?php 
            echo $tasksArray[$i]->project->title;
            ?>
</em> 
	  <?php 
            echo $tasksArray[$i]->id;
    exit;
    // in your code you'll want to handle the error and recover appropriately.
}
echo "<p>Access Token = {$access_token}</p>";
// MAKE API CALL
// This example gets the forecast for the field location that you just created.
// Forecasts work similarly to observed weather, except that each day of data has its own "forecast"
// object with anything from the hourly to the daily forecast, depending on what you ask for.
// In this example we'll ask for the daily forecast.
// Note we're creating the URL first, using the variables from the header.php file.
echo "<hr><h1>Get Forecast</h1>";
$forecastURL = 'https://api.awhere.com/v2/weather/fields/' . $new_field_id . '/forecasts/' . $forecast_weather_start . ',' . $forecast_weather_end . "?blockSize=24";
//requesting that the forecast block be 24-hours long (daily)
//options are 1 (default), 2, 3, 4, 6, 8, 12, 24
try {
    $forecastResponse = makeAPICall('GET', $forecastURL, $access_token, $forecastStatusCode, $forecastResponseHeaders);
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
if ($forecastStatusCode == 200) {
    // Code 200 means the request was successful
    echo '<p>You requested ' . count($forecastResponse->forecasts) . " days of forecast." . "The forecasted weather on " . date("F j, Y", strtotime($forecastResponse->forecasts[0]->date)) . " is a high temperature of " . $forecastResponse->forecasts[0]->forecast[0]->temperatures->max . "&deg;" . $forecastResponse->forecasts[0]->forecast[0]->temperatures->units . " and a low of " . $forecastResponse->forecasts[0]->forecast[0]->temperatures->min . "&deg;" . $forecastResponse->forecasts[0]->forecast[0]->temperatures->units . "</p>";
    echo '<p>Request:</p><pre>GET ' . $forecastURL . '</pre>';
    echo '<p>Content-Range Header:</p>';
    // HTTP transactions return a lot of headers, but in this example we only want the Content-Range header
    // (the parseHTTPHeaders function returns just the headers you want)
    // This API returns a ranged result, which are paginated by default to 50 results per page. The
    // Content-Range header shows which of the results are on this page (e.g., 1-10) and the total number
    // of results. It looks something like this:
    // Content-Range: observations 0-5/5
      "deadline_timezone":"EST"
      
      
}}';
        //// Update the task to add the label
        $updateTask = makeAPICall("https://www.producteev.com/api/tasks/{$newTaskID}", $updateTaskData, "PUT");
        /// Update the task add the desc
        $newNoteData = '{
  "note":{
    "message":"' . addslashes($_REQUEST['description']) . '",
    "task":{
      "id":"' . $newTaskID . '"
    }
  }
}';
        $updateTaskNotes = makeAPICall("https://www.producteev.com/api/notes", $newNoteData, "POST");
        //api/notes?access_token=OGRlMWI1YmM5MDEyMjM3M2FkZmQ0ZjI2ZWUwYzJmYzZkOGZiMGJmMjZhZDYzMTliZDdhODY0NThkZjQ0M2UwMQ
        //print_r($updateTask);
        //// Update the task to add the attached images
        //// update the task to add Dev Team as a follower  (or Tom King)
    } else {
        ?>
	
	
	There was a problem. Please try again.
	
	<?php 
    }
    //print_r($taskData);
    /*
    //$projectData['content'];
	    </ol>
<?php 
    ///tasks are in $tasksArray
    // for each task, add the project id of $_REQUEST['projectid'] and remove the label id of $_REQUEST['labelid']
    $projectData = makeAPICall("https://www.producteev.com/api/projects/" . $_REQUEST['projectid']);
    //$projectData['content'];
    $projectData['content'] = str_replace("\\/", "/", $projectData['content']);
    for ($i = 0; $i < count($tasksToMove); $i++) {
        $updateTask = "";
        print "Updating...";
        print "<br>Looking to move to project id " . $_REQUEST['projectid'] . ":";
        print "<br>" . $tasksToMove[$i];
        $taskDataToSend = '{"task":' . $projectData['content'] . '}';
        /// move the task into the project
        $updateTask = makeAPICall("https://www.producteev.com/api/tasks/" . $tasksToMove[$i], $taskDataToSend, "PUT");
        //print_r($taskDataToSend);
        //exit();
        //print_r($updateTask);
        //print($taskDataToSend);
        /* {"task":{"labels":["519b6a79bcd3e02c6d0000ba"]}} */
        // remove the label from the task
        $updateTask = makeAPICall("https://www.producteev.com/api/tasks/" . $tasksToMove[$i] . "/labels/" . $_REQUEST['labelid'], "", "DELETE");
        /*
        
        curl -v -X DELETE "https://www.producteev.com/api/tasks/51e83db1fa46341808000075/labels/51e83dd6fa46341808000399" --header "Authorization:Bearer 5Fm-kYL08PpPU3VkYzTbCNO3-Ldzk8-COtjp3_7Xmto"
        */
    }
    // remove the label from the system
    // https://www.producteev.com/api/labels/51e83dd6fa46341808000399
    $removeLabelFromSystem = makeAPICall("https://www.producteev.com/api/labels/" . $_REQUEST['labelid'], "", "DELETE");
}
<?php

include_once "header.php";
//first page of the auth process:
//https://www.producteev.com/oauth/v2/auth?client_id=53518db120bce50455000004_1gphpxybebesgc04s8sw4s8kwooocsw80ocwc04kwkco0wsw4w&response_type=code&redirect_uri=http%3A%2F%2Fwww.pathinteractive.com%2Finternal%2Fproducteev%2Fauth.php
if ($_REQUEST['code']) {
    /// Get the "code" from the auth and save it to the session for later use
    //$_SESSION['producteev_code']=$_REQUEST['code'];
    //https://www.producteev.com/oauth/v2/token?client_id=YOURCLIENTID&client_secret=YOURCLIENTSECRET&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fwww.yoururlencoded.com&code=ARANDOMCODE
    $authFinal = makeAPICall("https://www.producteev.com/oauth/v2/token?client_id=53518db120bce50455000004_1gphpxybebesgc04s8sw4s8kwooocsw80ocwc04kwkco0wsw4w&client_secret=1xsyki0zequ8cckwg0sko00cw40g0oc4ow040go4kkgwkgk4ok&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fwww.pathinteractive.com%2Finternal%2Fproducteev%2Fauth.php&code=" . $_REQUEST['code']);
    $authData = json_decode($authFinal['content']);
    $_SESSION['producteev_access_token'] = $authData->access_token;
    $_SESSION['producteev_expires_in'] = $authData->expires_in;
    $_SESSION['producteev_refresh_token'] = $authData->refresh_token;
    ?>
<div align="center"><h3>Thanks. Redirecting...</h3></div>
<meta http-equiv="refresh" content="2; url=index.php">

<?php 
}
include_once "footer.php";
    //if there is a cURL problem and the API call can't execute at all,
    //the function throws an exception which we can catch to fail gracefully.
    $access_token = GetOAuthToken($api_key, $api_secret);
} catch (Exception $e) {
    echo $e->getMessage();
    // For this script we're just echoing the error and stopping the rest of the script.
    exit;
    // in your code you'll want to handle the error and recover appropriately.
}
echo "<p>Access Token = {$access_token}</p>";
// MAKE API CALL
// Now we'll make a simple API Call to get a list of fields in our account.
// If this is the first time you've used the APIs this list will be empty.
echo "<hr><h1>Get List of Fields</h1>";
try {
    $fieldsListResponse = makeAPICall('GET', 'https://api.awhere.com/v2/fields', $access_token, $fieldsListStatusCode, $fieldsListResponseHeaders);
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
if ($fieldsListStatusCode == 200) {
    // Code 200 means the request was successful
    echo '<p>There are ' . count($fieldsListResponse->fields) . " field locations in the current page of results.</p>";
    echo '<p>Request:</p><pre>GET https://api.awhere.com/v2/fields</pre>';
    echo '<p>Content-Range Header (shows pagination and total results):</p>';
    // HTTP transactions return a lot of headers, but in this example we only want the Content-Range header
    // (the parseHTTPHeaders function returns just the headers you want)
    // This API returns a ranged result, which are paginated by default to 50 results per page. The
    // Content-Range header shows which of the results are on this page (e.g., 1-10) and the total number
    // of results. It looks something like this:
    // Content-Range: fields 0-5/5