Exemple #1
0
function api_getMembers_date($house, $date) {
	if ($date = parse_date($date)) {
		api_getMembers($house, '"' . $date['iso'] . '"');
	} else {
		api_error('Invalid date format');
	}
}
function api_findArticles_invoke($params)
{
    $search = $params['search'];
    if (!$search) {
        api_error("required parameter 'search' is missing");
        return;
    }
    $start = (int) $params['offset'];
    $num = (int) $params['limit'];
    if (!$num) {
        $num = 100;
    }
    if (!$start) {
        $start = 0;
    }
    try {
        $xap = new XapSearch();
        $xap->set_query($search);
        $results = $xap->run($start, $num, 'date');
        //        foreach( $results as &$a ) {
        //            // convert datetime objects to strings
        //            $a['pubdate'] = $a['pubdate']->format('c');
        //        }
        $output = array('results' => $results);
        api_output($output);
    } catch (Exception $e) {
        api_error($e->getMessage());
    }
}
Exemple #3
0
function api_getMSP_constituency($constituency)
{
    $output = _api_getMSP_constituency(array($constituency));
    if (!$output) {
        api_error('Unknown constituency, or no MSP for that constituency');
    }
}
function api_getRepresentatives_postcode($pc)
{
    $pc = preg_replace('#[^0-9]#i', '', $pc);
    if (is_postcode($pc)) {
        $constituency = postcode_to_constituency($pc);
        if ($constituency == 'CONNECTION_TIMED_OUT') {
            api_error('Connection timed out');
        } elseif ($constituency) {
            if (is_array($constituency)) {
                $constituencies = $constituency;
            } else {
                $constituencies = array($constituency);
            }
            $output = array();
            foreach ($constituencies as $c) {
                $output[] = _api_getMP_constituency($c);
            }
            api_output($output);
        } else {
            api_error('Unknown postcode');
        }
    } else {
        api_error('Invalid postcode');
    }
}
Exemple #5
0
function api_getDivisions_postcode($pc)
{
    $pc = preg_replace('#[^0-9]#i', '', $pc);
    $output = array();
    if (is_postcode($pc)) {
        $constituency = postcode_to_constituency($pc);
        if ($constituency == 'CONNECTION_TIMED_OUT') {
            api_error('Connection timed out');
        } elseif ($constituency) {
            if (is_array($constituency)) {
                $constituencies = $constituency;
            } else {
                $constituencies = array($constituency);
            }
            foreach ($constituencies as $c) {
                $output[] = array('name' => html_entity_decode($c));
            }
        } else {
            api_error('Unknown postcode');
        }
    } else {
        api_error('Invalid postcode');
    }
    api_output($output);
}
Exemple #6
0
function api_getBoundary_name($name)
{
    $name = html_entity_decode(normalise_constituency_name($name));
    # XXX
    if (!$name) {
        api_error('Name not recognised');
        return;
    }
    $out = array();
    $areas = _api_cacheCheck('mapit_get_areas_by_type', 'WMC');
    $areas_info = _api_cacheCheck('mapit_get_voting_areas_info', $areas);
    $id = null;
    foreach ($areas_info as $k => $v) {
        if (html_entity_decode(normalise_constituency_name($v['name'])) == $name) {
            $id = $k;
        }
    }
    if (!$id) {
        api_error('No data found for name');
        return;
    }
    $out = mapit_get_voting_area_geometry($id, 'wgs84');
    if (isset($out['polygon'])) {
        api_output($out['polygon']);
    } else {
        api_error('Nothing returned from get_voting_areas_geometry');
    }
}
function api_getArticles_invoke($params)
{
    $article_ids = array();
    if ($params['id36']) {
        $id36s = preg_split("/[\\s,]+/", $params['id36']);
        foreach ($id36s as $id36) {
            $article_ids[] = article_id36_to_id($id36);
        }
    }
    if ($params['url']) {
        // look up article by its original url
        $url = $params['url'];
        $art_id = article_find($url);
        if (is_null($art_id)) {
            api_error("couldn't find article with url: '" . $url . "'");
            return;
        }
        $article_ids[] = $art_id;
    }
    if (!$article_ids) {
        api_error("No articles specified - use 'id36' and/or 'url'");
        return;
    }
    #$brief = $params['brief'] ? TRUE : FALSE;
    $fields = array('title', 'id36', 'srcorgname', 'iso_pubdate', 'permalink', 'journos', 'description');
    $results = array();
    foreach ($article_ids as $id) {
        $raw = article_collect($id);
        $art = array_cherrypick($raw, $fields);
        $results[] = $art;
    }
    $output = array('status' => 0, 'results' => $results);
    api_output($output);
}
function api_getJournoArticles_invoke($params)
{
    $offset = (int) $params['offset'];
    $limit = (int) $params['limit'];
    if (!$limit) {
        $limit = 100;
    }
    if (!$offset) {
        $offset = 0;
    }
    $j = $params['journo'];
    if (!$j) {
        api_error("required parameter 'journo' is missing");
        return;
    }
    $jfield = is_numeric($j) ? 'id' : 'ref';
    $sql = <<<EOT
SELECT a.id, a.title, a.srcorg, a.permalink, a.description, a.pubdate
    FROM ((article a INNER JOIN journo_attr attr ON a.id=attr.article_id)
        INNER JOIN journo j ON j.id=attr.journo_id)
    WHERE a.status='a' AND j.status='a' AND j.{$jfield}=?
    ORDER BY a.pubdate DESC
    LIMIT ?
    OFFSET ?
EOT;
    $articles = db_getAll($sql, $j, $limit, $offset);
    foreach ($articles as &$a) {
        $d = new DateTime($a['pubdate']);
        $a['pubdate'] = $d->format('c');
    }
    $output = array('results' => $articles);
    api_output($output);
}
Exemple #9
0
 function api_checkarg_post_required($arg, $friendly)
 {
     $arg = api_checkarg_post($arg);
     if (empty($arg)) {
         api_error(SN_API_CALL_EMPTY_PARAMETER, sprintf("Field '%s' is required.", $friendly));
     }
     return $arg;
 }
/**
 * Gets the file path for the specified package version. Throws an exception if
 * the package version does not exist.
 */
function get_package_path($id, $version)
{
    if (!DB::validateIdAndVersion($id, $version) || strpos($id, '/') !== false || strpos($version, '/') !== false) {
        api_error('404', 'Package version not found');
    }
    // This is safe - These values have been validated via validateIdAndVersion above
    return '/packagefiles/' . $id . '/' . $version . '.nupkg';
}
function api_getConstituency_name($constituency) {
    $constituency = normalise_constituency_name($constituency);
    if (!$constituency) {
        api_error('Could not find anything with that name');
        return;
    }
    return _api_getConstituency_name($constituency);
}
Exemple #12
0
function array_get($array, $key)
{
    global $INVALID_FILE_UPLOAD;
    if (array_key_exists($key, $array)) {
        return $array[$key];
    } else {
        api_error($INVALID_FILE_UPLOAD);
    }
}
function api_getConstituency_name($constituency)
{
    $constituency = MySociety\TheyWorkForYou\Utility\Constituencies::normaliseConstituencyName($constituency);
    if (!$constituency) {
        api_error('Could not find anything with that name');
        return;
    }
    return _api_getConstituency_name($constituency);
}
function api_getGeometry_name($name)
{
    $out = _api_getGeometry_name($name);
    if ($out) {
        api_output($out);
    } else {
        api_error('Name not recognised');
    }
}
Exemple #15
0
function logout($req, $hash, $apiId, $sign)
{
    $af = new AccountManager();
    $result = $af->Logout($hash);
    if ($result) {
        return api_response(array('LoggedOut' => $result));
    } else {
        return api_error(ApiErrorCode::AuthAlreadyLoggedOut, 'Account already logged out!');
    }
}
function argreq($name)
{
    if (isset($_GET[$name])) {
        return $_GET[$name];
    }
    if (isset($_POST[$name])) {
        return $_POST[$name];
    }
    api_error(array("message" => "Parameter missing: " . $name));
}
function api_getPerson_id($id)
{
    $db = new ParlDB();
    $q = $db->query("select * from member\n        where person_id = '" . mysql_real_escape_string($id) . "'\n        order by left_house desc");
    if ($q->rows()) {
        _api_getPerson_output($q);
    } else {
        api_error('Unknown person ID');
    }
}
Exemple #18
0
 function call($methodname, $args)
 {
     Logger::log("XML-RPC call: {$methodname}");
     list($methodname, $func_desc, $php_func) = api_get_function_descriptor($methodname);
     // make sure $args is a 1-elem array containing a hash
     if (gettype($args) != "array") {
         api_error("Parameters should be in an array", 'validation_request_wrapper');
     }
     switch ($func_desc['argstyle']) {
         case 'positional':
             $arg = array();
             $argorder = $func_desc['argorder'];
             if (count($args) != count($argorder)) {
                 api_error("Incorrect number of arguments; expected " . count($argorder), 'validation_incorrect_number_of_arguments');
             }
             for ($i = 0; $i < count($args); ++$i) {
                 $arg[$argorder[$i]] = $args[$i];
             }
             break;
         case 'named':
             if (sizeof($args) != 1) {
                 api_error("You should only send a single parameter in your XML-RPC request: a struct, containing all the required keys.", 'validation_request_wrapper');
             }
             $arg = $args[0];
             if (gettype($arg) != "array") {
                 api_error("Expected a single parameter containing an XML-RPC struct, but got a value of type '" . gettype($arg) . "' instead.", 'validation_request_wrapper');
             }
             break;
         default:
             api_error("Invalid argument style " . $func_desc['argstyle']);
     }
     //	var_dump($func_desc['args']);
     // validate the struct
     validate_content($arg, array("type" => "hash", "content" => $func_desc['args']), "input to XML-RPC function", "auto");
     // call function, capturing any output - which might include errors
     ob_start("xmlrpc_ob_end");
     try {
         $ret = $php_func($arg);
         // check output
         if ($ret['success']) {
             validate_content($ret, $func_desc['return'], "XML-RPC response - not your fault!", "auto");
         }
     } catch (PAException $e) {
         $ret = api_err_from_exception($e);
         Logger::log("An exception occurred in an API call: code " . $e->getCode() . ", message " . $e->getMessage() . "\n" . $e->getTraceAsString(), LOGGER_ERROR);
     }
     return $ret;
 }
Exemple #19
0
function api_getconstituency_postcode($pc)
{
    $pc = preg_replace('#[^a-z0-9 ]#i', '', $pc);
    if (validate_postcode($pc)) {
        $constituency = postcode_to_constituency($pc);
        if ($constituency == 'CONNECTION_TIMED_OUT') {
            api_error('Connection timed out');
        } elseif ($constituency) {
            $output['name'] = html_entity_decode($constituency);
            api_output($output);
        } else {
            api_error('Unknown postcode');
        }
    } else {
        api_error('Invalid postcode');
    }
}
Exemple #20
0
 private function doRequests()
 {
     try {
         $this->callFunc($this->beforeFunc);
         foreach ($this->Requests[self::$method] as &$request) {
             #dump($request);
             $response = $request->Run($this);
             #dump($response);
             if ($response) {
                 return $response;
             }
         }
         $this->callFunc($this->afterFunc);
         return render_to_response(array('Code' => 404, 'Message' => 'Page not found!'), 'error');
     } catch (Exception $e) {
         return api_error(ApiErrorCode::ServerError, "Server error occurred: " . $e->getMessage());
     }
 }
function api_getconstituency_postcode($pc) {
	$pc = preg_replace('#[^a-z0-9 ]#i', '', $pc);

  if (get_http_var('future')) {

    $new_areas = mapit_get_voting_areas($pc, 13); # Magic number 13
    if (is_object($new_areas)) { # rabx_is_error throws Notice
        api_error('Unknown postcode, or problem with lookup');
    } elseif (!isset($new_areas['WMC'])) {
        api_error('Unknown postcode, or problem with lookup');
    } else {
        $new_info = mapit_get_voting_area_info($new_areas['WMC']);
        $output['name'] = $new_info['name'];
        api_output($output);
    }

  } else {

	if (validate_postcode($pc)) {
		$constituency = postcode_to_constituency($pc);
		if ($constituency == 'CONNECTION_TIMED_OUT') {
			api_error('Connection timed out');
		} elseif ($constituency) {
                    $db = new ParlDB;
                    $q = $db->query("select constituency, data_key, data_value from consinfo
                                     where constituency = '" . mysql_real_escape_string($constituency) . "'");
                    if ($q->rows()) {
                        for ($i=0; $i<$q->rows(); $i++) {
                            $data_key = $q->field($i, 'data_key');
                            $output[$data_key] = $q->field($i, 'data_value');
                        }
                        ksort($output);
		    }
                    $output['name'] = $constituency;
		    api_output($output);
		} else {
			api_error('Unknown postcode');
		}
	} else {
		api_error('Invalid postcode');
	}

  }
}
Exemple #22
0
function api_getLord_id($id)
{
    $db = new ParlDB();
    $q = $db->query("select * from member\n\t\twhere house=2 and person_id = '" . mysql_real_escape_string($id) . "'\n\t\torder by left_house desc");
    if ($q->rows()) {
        $output = array();
        $last_mod = 0;
        for ($i = 0; $i < $q->rows(); $i++) {
            $out = _api_getLord_row($q->row($i));
            $output[] = $out;
            $time = strtotime($q->field($i, 'lastupdate'));
            if ($time > $last_mod) {
                $last_mod = $time;
            }
        }
        api_output($output, $last_mod);
    } else {
        api_error('Unknown person ID');
    }
}
function api_getMPinfo_id($id)
{
    $db = new ParlDB();
    $last_mod = 0;
    $q = $db->query("select data_key, data_value, lastupdate from personinfo\n\t\twhere person_id = '" . mysql_escape_string($id) . "'");
    if ($q->rows()) {
        $output = array();
        for ($i = 0; $i < $q->rows(); $i++) {
            $output[$q->field($i, 'data_key')] = $q->field($i, 'data_value');
            $time = strtotime($q->field($i, 'lastupdate'));
            if ($time > $last_mod) {
                $last_mod = $time;
            }
        }
        $q = $db->query("select * from memberinfo\n\t\t\twhere member_id in (select member_id from member where person_id = '" . mysql_escape_string($id) . "')");
        if ($q->rows()) {
            $oldmid = 0;
            $count = -1;
            for ($i = 0; $i < $q->rows(); $i++) {
                $mid = $q->field($i, 'member_id');
                if (!isset($output['by_member_id'])) {
                    $output['by_member_id'] = array();
                }
                if ($oldmid != $mid) {
                    $count++;
                    $oldmid = $mid;
                    $output['by_member_id'][$count]['member_id'] = $mid;
                }
                $output['by_member_id'][$count][$q->field($i, 'data_key')] = $q->field($i, 'data_value');
                $time = strtotime($q->field($i, 'lastupdate'));
                if ($time > $last_mod) {
                    $last_mod = $time;
                }
            }
        }
        ksort($output);
        api_output($output, $last_mod);
    } else {
        api_error('Unknown person ID');
    }
}
function api_converturl_url($url)
{
    $db = new ParlDB();
    $url_nohash = preg_replace('/#.*/', '', $url);
    $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url = :url order by gid limit 1', array(':url' => $url));
    if ($q->rows()) {
        return api_converturl_url_output($q);
    }
    $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url like :url order by gid limit 1', array(':url' => $url_nohash . '%'));
    if ($q->rows()) {
        return api_converturl_url_output($q);
    }
    $url_bound = str_replace('cmhansrd/cm', 'cmhansrd/vo', $url_nohash);
    if ($url_bound != $url_nohash) {
        $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url like :url order by gid limit 1', array(':url' => $url_bound . '%'));
        if ($q->rows()) {
            return api_converturl_url_output($q);
        }
    }
    api_error('Sorry, URL could not be converted');
}
Exemple #25
0
function api_converturl_url($url)
{
    $db = new ParlDB();
    $url_nohash = preg_replace('/#.*/', '', $url);
    $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url = "' . mysql_real_escape_string($url) . '" order by gid limit 1');
    if ($q->rows()) {
        return api_converturl_url_output($q);
    }
    $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url like "' . mysql_real_escape_string($url_nohash) . '%" order by gid limit 1');
    if ($q->rows()) {
        return api_converturl_url_output($q);
    }
    $url_bound = str_replace('cmhansrd/cm', 'cmhansrd/vo', $url_nohash);
    if ($url_bound != $url_nohash) {
        $q = $db->query('select gid,major,htype,subsection_id from hansard where source_url like "' . mysql_real_escape_string($url_bound) . '%" order by gid limit 1');
        if ($q->rows()) {
            return api_converturl_url_output($q);
        }
    }
    api_error('Sorry, URL could not be converted');
}
 public function post($rest)
 {
     // Originally added by Richard Vinke
     $req = $rest->request();
     $info = $req->post();
     // ToDo Check if loc_code already exists
     // Validate Required Fields
     if (!isset($info['loc_code'])) {
         api_error(412, 'Stock Id is required');
     }
     if (!isset($info['location_name'])) {
         api_error(412, 'Stock Id is required');
     }
     if (!isset($info['delivery_address'])) {
         $info['delivery_address'] = '';
     }
     if (!isset($info['phone'])) {
         $info['phone'] = '';
     }
     if (!isset($info['phone2'])) {
         $info['phone2'] = '';
     }
     if (!isset($info['fax'])) {
         $info['fax'] = '';
     }
     if (!isset($info['email'])) {
         $info['email'] = '';
     }
     if (!isset($info['contact'])) {
         $info['contact'] = '';
     }
     add_item_location($info['loc_code'], $info['location_name'], $info['delivery_address'], $info['phone'], $info['phone2'], $info['fax'], $info['email'], $info['contact']);
     $itm = get_item_location($info['loc_code']);
     if ($itm != null) {
         api_create_response(json_encode($itm));
     } else {
         api_error(500, 'Could Not Save to Database');
     }
 }
function api_getBoundary_name($name)
{
    $name = normalise_constituency_name($name);
    if (!$name) {
        api_error('Name not recognised');
        return;
    }
    $out = array();
    $areas_info = _api_cacheCheck('areas', 'WMC');
    $id = null;
    foreach ($areas_info as $k => $v) {
        if (normalise_constituency_name($v['name']) == $name) {
            $id = $k;
        }
    }
    if (!$id) {
        api_error('No data found for name');
        return;
    }
    header("Location: http://mapit.mysociety.org/area/4326/{$id}.kml");
    exit;
}
function api_getconstituency_postcode($pc)
{
    $pc = preg_replace('#[^a-z0-9 ]#i', '', $pc);
    if (!validate_postcode($pc)) {
        api_error('Invalid postcode');
        return;
    }
    if (get_http_var('future')) {
        $xml = simplexml_load_string(file_get_contents(POSTCODE_API_URL . urlencode($pc)));
        if (!$xml || $xml->error) {
            api_error('Unknown postcode, or problem with lookup');
            return;
        }
        $output['name'] = iconv('utf-8', 'iso-8859-1//TRANSLIT', (string) $xml->future_constituency);
        api_output($output);
    } else {
        $constituency = postcode_to_constituency($pc);
        if ($constituency == 'CONNECTION_TIMED_OUT') {
            api_error('Connection timed out');
            return;
        }
        if (!$constituency) {
            api_error('Unknown postcode');
            return;
        }
        $db = new ParlDB();
        $q = $db->query("select constituency, data_key, data_value from consinfo\n                         where constituency = '" . mysql_real_escape_string($constituency) . "'");
        if ($q->rows()) {
            for ($i = 0; $i < $q->rows(); $i++) {
                $data_key = $q->field($i, 'data_key');
                $output[$data_key] = $q->field($i, 'data_value');
            }
            ksort($output);
        }
        $output['name'] = $constituency;
        api_output($output);
    }
}
function _api_getHansard_search($array)
{
    $search = isset($array['s']) ? trim($array['s']) : '';
    $pid = trim($array['pid']);
    $type = isset($array['type']) ? $array['type'] : '';
    $search = filter_user_input($search, 'strict');
    if ($pid) {
        $search .= ($search ? ' ' : '') . 'speaker:' . $pid;
    }
    if ($type) {
        $search .= " section:" . $type;
    }
    $o = get_http_var('order');
    if ($o == 'p') {
        $data = \MySociety\TheyWorkForYou\Utility\Search::searchByUsage($search);
        $out = array();
        if (!isset($data['speakers'])) {
            $data['speakers'] = array();
        }
        foreach ($data['speakers'] as $pid => $s) {
            $out[$pid] = array('house' => $s['house'], 'name' => $s['name'], 'party' => $s['party'], 'count' => $s['count'], 'mindate' => substr($s['pmindate'], 0, 7), 'maxdate' => substr($s['pmaxdate'], 0, 7));
        }
        api_output($out);
        return;
    }
    global $SEARCHENGINE;
    $SEARCHENGINE = new SEARCHENGINE($search);
    if (!$SEARCHENGINE->valid) {
        api_error('Invalid search term');
        return;
    }
    #    $query_desc_short = $SEARCHENGINE->query_description_short();
    $pagenum = get_http_var('page');
    $args = array('s' => $search, 'p' => $pagenum, 'num' => get_http_var('num'), 'pop' => 1, 'o' => $o == 'd' || $o == 'r' ? $o : 'd');
    $LIST = new HANSARDLIST();
    $LIST->display('search', $args, 'api');
}
function api_call_user_func_or_error($function, $params, $error, $type) {
	if (function_exists($function))
		call_user_func_array($function, $params);
	elseif ($type == 'api')
		api_error($error);
	else
		print "<p style='color:#cc0000'>$error</p>";
}