### Get LegiScan Configuration Source: https://api.legiscan.com/docs/source-class-LegiScan_Push.html Retrieves the configuration array or a specific key from it. If the configuration is not yet loaded, it will be parsed from 'config.php'. ```php // {{{ getConfig() /** * Get the configuation array or a specific key from it * * @param string|null $key * (**OPTIONAL**) Return `$key` from config array * * @param mixed|null $default * (**OPTIONAL**) If `$key` does not exist return `$default` * * @return mixed * Either the configuration array or a specific `$key` value */ static function getConfig($key = null, $default = null) { static $config = array(); if (empty($config)) $config = parse_ini_file(realpath(__DIR__ . '/' . 'config.php')); if ($key !== null) { // Look for a specific key if (isset($config[$key])) { return $config[$key]; } else { if ($default !== null) return $default; else return null; } } else { // Return the entire config array return $config; } } // }}} ``` -------------------------------- ### LegiScan Import Command Line Options Source: https://api.legiscan.com/docs/source-class-LegiScan_Import.html Defines the available command-line options for the LegiScan import utility and provides usage examples. This is used to configure and control the import process. ```php $options = array( 'bulk', 'scan', 'state:', 'year:', 'file:', 'session:', 'skip:', 'special', 'regular', 'import', 'yes', 'verbose', 'debug', 'dry-run', ); $extra_help = ''; $extra_help .= "Command line interface to the LegiScan API that is capable of importing data, examples:\n"; $extra_help .= " " . basename($argv[0]) . " --bulk --import\n"; $extra_help .= " " . basename($argv[0]) . " --scan\n"; $extra_help .= " " . basename($argv[0]) . " --scan --state CA\n"; $extra_help .= " " . basename($argv[0]) . " --scan --year 2020 --import\n"; $extra_help .= " " . basename($argv[0]) . " --scan --session 1639\n"; legiscan_getopt($options, $extra_help); ``` -------------------------------- ### Start a Named Timer Source: https://api.legiscan.com/docs/source-function-expect_user.html Starts a named timer. If the timer is started and stopped multiple times, the intervals will be accumulated. This function requires a global $timers array to be set. ```PHP function timer_start($name) { global $timers; $timers[$name]['start'] = microtime(true); $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1; } ``` -------------------------------- ### Display Command Help Source: https://api.legiscan.com/docs/class-LegiScan_CommandLine.html Use this command to view all available options and usage instructions for the legiscan-cli.php script. ```bash php legiscan-cli.php --help ``` -------------------------------- ### Get LegiScan Version Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Retrieves the current version number of the LegiScan API. ```php static function getVersion() { return self::VERSION; } ``` -------------------------------- ### Display Legiscan Help Information Source: https://api.legiscan.com/docs/source-function-expect_user.html Prints command-line help text for Legiscan options and exits. Accepts a list of valid parameters and optional extra text. ```php function legiscan_help($parameters, $extra = '') { global $argv; $help = array( "monitoredlist" => "--monitoredlist \tRetrieve monitored list for GAITS account", "sessionlist:" => "--sessionlist STATE \tRetrieve session list info for STATE or ALL", "masterlist:" => "--masterlist STATE \tRetrieve master list for STATE", "bill:" => "--bill BILL_ID \tRetrieve bill detail payload for BILL_ID", "text:" => "--text DOC_ID \tRetrieve text payload for DOC_ID", "amendment:" => "--amendment AMEND_ID\tRetrieve amendment payload for AMEND_ID", "supplement:" => "--supplement SUP_ID \tRetrieve supplement payload for SUP_ID", "vote:" => "--vote ROLL_CALL_ID \tRetrieve roll call detail payload for ROLL_CALL_ID", "people:" => "--people PEOPLE_ID \tRetrieve people detail payload for PEOPLE_ID", "search:" => "--search QUERY \tRetrieve search results for QUERY", "state:" => "--state STATE \tSet STATE for query, defaults to all states", "score:" => "--score RELEVANCE \tSet RELEVANCE score cutoff (0-100) defaults to 50", "import:" => "--import ACTION \tTake ACTION on search/masterlist results: New, Changed, All", "key:" => "--key API_KEY \tOverride legiscan.conf api_key with API_KEY to use for request", "sync" => "--sync \tSync local monitor/ignore operations to GAITS account", "monitor:" => "--monitor BILL_ID \tAdd BILL_ID to ls_monitor list", "unmonitor:" => "--unmonitor BILL_ID \tRemove BILL_ID from ls_monitor list", "ignore:" => "--ignore BILL_ID \tAdd BILL_ID to ls_ignore list", "unignore:" => "--unignore BILL_ID \tRemove BILL_ID from ls_ignore list", "stance:" => "--stance STANCE \tStance of monitored bill (0=watch,1=support,2=oppose)", "clean" => "--clean \tClean the API cache of stale records", "bulk" => "--bulk \tRun a bulk update based on config.php settings", "scan" => "--scan \tScan the available dataset archives", "import" => "--import \tImport selected bulk dataset archives", "year:" => "--year YEAR \tSet YEAR for filtering results", "session:" => "--session SESSION_ID\tFilter for specific SESSION_IDs", "skip:" => "--skip SESSION_ID \tFilter against specific SESSION_IDs", "file:" => "--file ZIP \tDataset zip archive to process", "regular" => "--regular \tFlag only regular session datasets", "special" => "--special \tFlag only special session datasets", "reset-db" => "--reset-db \tTruncate and reset database tables back to clean production install", "dry-run" => "--dry-run \tDon't take action only print out what would have been done", "yes" => "--yes \tAutomatically answer Yes to any Yes/No prompts", "verbose" => "--verbose \tBe verbose in general", "debug" => "--debug \tBe more verbose specifically, maybe dump some JSON payload", "version" => "--version \tShow the application version number", "daemon" => "--daemon \tRun infinitely (otherwise update and exit)", "help" => "--help \tDisplay this help text", ); echo "Usage: " . basename($argv[0]) . " [OPTIONS]\n\n"; if ($extra) echo trim($extra) . "\n\n"; foreach ($parameters as $opt) { if (isset($help[$opt])) echo " {$help[$opt]}\n"; else echo sprintf(" --%-16s\t ***** NO HELP AVAILABLE *****\n", $opt); } exit(0); } ``` -------------------------------- ### LegiScan Worker Initialization and Execution Source: https://api.legiscan.com/docs/source-class-LegiScan_Worker.html This snippet demonstrates how to set up command-line options and instantiate the LegiScan_Worker class to run its main worker method. ```PHP // Sort out the command line options $options = array( 'daemon', ); legiscan_getopt($options); $daemon = 0; if (legiscan_option('daemon')) $daemon = 42; // just 'cause $worker = new LegiScan_Worker(); $worker->worker($daemon); ``` -------------------------------- ### Get LegiScan Version Source: https://api.legiscan.com/docs/class-LegiScan.html Retrieves the version number of the LegiScan API client. ```php LegiScan::getVersion(); ``` -------------------------------- ### Get Person Record Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Retrieves a basic person record using the internal LegiScan people_id. ```php public function getPerson($people_id) { $params = array('id'=>$people_id); return $this->apiRequest('getPerson', $params); } ``` -------------------------------- ### Display Command Help Source: https://api.legiscan.com/docs/class-LegiScan_Import.html Shows the help information for the legiscan-bulk.php script. Use this to understand all available command-line options. ```bash php legiscan-bulk.php --help ``` -------------------------------- ### Instantiate and Run LegiScan Command Line Source: https://api.legiscan.com/docs/source-class-LegiScan_CommandLine.html This snippet shows the instantiation of the LegiScan_CommandLine class and the execution of its commands method. This is the entry point for processing CLI arguments. ```php $cli = new LegiScan_CommandLine(); $cli->commands(); ``` -------------------------------- ### Get Bill Supplement Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Retrieves a bill supplement by its ID. The supplement data is base64 encoded. ```php public function getSupplement($supplement_id) { $params = array('id'=>$supplement_id); if (LegiScan::getConfig('prefer_pdf')) $params['prefer'] = 'pdf'; return $this->apiRequest('getSupplement', $params); } ``` -------------------------------- ### Get Cache Entry Source: https://api.legiscan.com/docs/source-class-APIException.html Retrieves data from the in-memory cache if the key exists and the entry has not expired. ```php if (isset(self::$cache[$key]) && self::$cache[$key]['expires'] > time()) { $data = self::$cache[$key]['data']; } ``` -------------------------------- ### __construct Source: https://api.legiscan.com/docs/source-class-APIException.html Initializes the API client, optionally overriding the API key and performing a sanity check on its format. It also sets up the cache layer. ```APIDOC ## __construct() ### Description Class constructor that nominally validates the API key. It initializes the cache and retrieves the API key from configuration, throwing an APIException if the key is invalid. ### Method `__construct` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Example of instantiating the class (API key is handled internally) $api = new API(); ``` ### Response #### Success Response None (constructor does not return a value) #### Response Example None ``` -------------------------------- ### Initialize LegiScan API Client Source: https://api.legiscan.com/docs/source-class-LegiScan_CommandLine.html This snippet demonstrates how to include the LegiScan API client and check for the minimum required PHP version. Ensure the 'LegiScan.php' file is accessible. ```php * @license https://opensource.org/licenses/BSD-2-Clause * @copyright 2010-2020 LegiScan LLC * */ // I say thee nay! if (version_compare(PHP_VERSION, '5.4.0') < 0) die('PHP 5.4.0 or higher is required'); // Include the LegiScan API Client require_once('LegiScan.php'); ``` -------------------------------- ### Get Session List Source: https://api.legiscan.com/docs/source-class-LegiScan_Bulk.html Retrieves a list of sessions for a given state. Requires a valid state abbreviation. ```php public function getSessionList($state) { $params = array('state'=>strtoupper($state)); return $this->apiRequest('getSessionList', $params); } ``` -------------------------------- ### Get Decoded Payload Array Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Returns the decoded payload associative array from the most recently processed record. ```PHP public function getPayload() { return $this->payload; } ``` -------------------------------- ### LegiScan_Bulk Constructor Source: https://api.legiscan.com/docs/source-class-LegiScan_Bulk.html Initializes the LegiScan_Bulk class, sets up the cache, and validates the API key. Throws an APIException if the API key is invalid. ```php function __construct() { $this->cache = new LegiScan_Cache_File('api'); $this->api_key = LegiScan::getConfig('api_key'); // Sanity checks to avoid sending junk requests if (!preg_match('/^[0-9a-f]{32}$/i', $this->api_key)) throw new APIException('Invalid API key'); } ``` -------------------------------- ### __construct() Source: https://api.legiscan.com/docs/source-class-APIAccessException.html Class constructor, initializes necessary LegiScan_Process instances. ```APIDOC ## __construct() ### Description Initializes the LegiScan_Process instances. ### Method __construct ### Parameters None ### Response None ``` -------------------------------- ### Get Cache Instance Source: https://api.legiscan.com/docs/source-class-APIException.html Retrieves a singleton instance of the cache handler, either using Memcache/Memcached if configured, or a memory-based cache. ```php self::$instance = new LegiScan_Cache_Memory($lifetime); ``` -------------------------------- ### Check for Missing Options and API Key Source: https://api.legiscan.com/docs/source-class-LegiScan_CommandLine.html This code checks if essential command-line options are provided. If 'key' is missing and the API key is not configured, it displays help information and exits. ```php if (empty($legiscan_options)) legiscan_help($options, "Missing OPTIONS\n" . $extra_help); // Make sure the base options are there if (!legiscan_option('key') && !preg_match('/^[0-9a-f]{32}$/i', LegiScan::getConfig('api_key'))) legiscan_help($options, "Missing API Key (set in legiscan.conf or use --key)\n"); ``` -------------------------------- ### LegiScan getConfig() Method Source: https://api.legiscan.com/docs/source-class-LegiScan_Cache_Memory.html Retrieves configuration settings from the 'config.php' file. It can return the entire configuration array or a specific key's value, with an option to provide a default value if the key is not found. ```php /** * Get the configuation array or a specific key from it * * @param string|null $key * (**OPTIONAL**) Return `$key` from config array * * @param mixed|null $default * (**OPTIONAL**) If `$key` does not exist return `$default` * * @return mixed * Either the configuration array or a specific `$key` value */ static function getConfig($key = null, $default = null) { static $config = array(); if (empty($config)) $config = parse_ini_file(realpath(__DIR__ . '/' . 'config.php')); if ($key !== null) { // Look for a specific key if (isset($config[$key])) { return $config[$key]; } else { if ($default !== null) return $default; else return null; } } else { // Return the entire config array return $config; } } ``` -------------------------------- ### APIException Get Method Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Retrieves a cached entry by its key, returning the data if it exists and has not expired. Otherwise, it returns false. ```php // {{{ get() /** * Get an entry from the cache * * @param string $key * Cache key to retrieve * * @return mixed * The contents of the file or FALSE for missing/stale */ public function get($key) { $data = false; if (isset(self::$cache[$key]) && self::$cache[$key]['expires'] > time()) { $data = self::$cache[$key]['data']; } return $data; } // }}} ``` -------------------------------- ### LegiScan_Worker Initialization and Configuration Check Source: https://api.legiscan.com/docs/source-class-LegiScan_Worker.html Initializes LegiScan_Pull and LegiScan_Process, retrieves database handle, and validates configuration settings. ```php function worker($daemon) { try { // Create an instance to generate pull requests $legiscan = new LegiScan_Pull(); // Create an instance to write to database $logic = new LegiScan_Process(); // Grab a handle to the database $db = $logic->getDB(); // {{{ Check and validate config $error_msg = ''; $update_type = strtolower(LegiScan::getConfig('update_type')); $states = LegiScan::getConfig('states'); $searches = LegiScan::getConfig('searches'); $interval = LegiScan::getConfig('interval', 3600); $default_relevance = (int) LegiScan::getConfig('relevance', 50); $ignore_table = (bool) LegiScan::getConfig('use_ignore_table'); $valid_types = array('monitored','state','search','state_search'); if (!$update_type) $error_msg .= "Configuration value update_type is missing\n"; elseif (!in_array($update_type, $valid_types)) $error_msg .= "Invalid configuration value for update_type $update_type\n"; if (!$default_relevance || !($default_relevance >= 0 && $default_relevance <= 100)) $error_msg .= "Invalid configuration value for default_relevance $default_relevance\n"; // At some point it would be better to run from cron... if ($interval < 3600) $interval = 3600; if ($interval > 86400) $interval = 86400; if ($error_msg) { $msg = "Invalid Configuration\n\n$error_msg\nExiting\n"; echo $msg; LegiScan::sendMail("LegiScan Daemon Error", $msg); exit(1); } // }}} ``` -------------------------------- ### Get Bill Detail by Bill ID Source: https://api.legiscan.com/docs/source-class-APIAccessException.html Fetches the detailed record for a specific bill using its internal bill ID. ```php public function getBill($bill_id) { $params = array('id'=>$bill_id); return $this->apiRequest('getBill', $params); } ``` -------------------------------- ### Bulk Import with Configuration Source: https://api.legiscan.com/docs/class-LegiScan_Import.html Performs a bulk import of datasets using settings from config.php. Automatically answers 'yes' to any prompts during the process. ```bash php legiscan-bulk.php --bulk --import --yes ``` -------------------------------- ### Get Legiscan Option Value Source: https://api.legiscan.com/docs/source-function-expect_user.html Retrieves the value of a specific Legiscan option. Returns a default value if the option is not set. ```php function legiscan_option($option, $default = false) { global $legiscan_options; if (isset($legiscan_options[$option])) return $legiscan_options[$option]; else return $default; } ``` -------------------------------- ### LegiScan_Pull::getPerson Source: https://api.legiscan.com/docs/class-LegiScan_Pull.html Get a basic people record for the specified id. Returns a basic people record for the specified id. ```APIDOC ## getPerson( integer $people_id ) ### Description Get a basic people record for the specified id. ### Parameters #### Path Parameters - **people_id** (integer) - Required - The internal LegiScan people_id to be retrieved ### Returns array - A basic people record ``` -------------------------------- ### LegiScan_Pull::getSessionList Source: https://api.legiscan.com/docs/class-LegiScan_Pull.html Get a session list for a specified state. Returns a list of state sessions and their corresponding session_id numbers. ```APIDOC ## getSessionList( string $state ) ### Description Get a session list for a specified state. ### Parameters #### Path Parameters - **state** (string) - Required - State to pull the session list for ### Returns array - The list of state sessions and their corresponding session_id numbers ``` -------------------------------- ### LegiScan_Process::__construct Source: https://api.legiscan.com/docs/class-LegiScan_Process.html Class constructor that connects to the database and caching layers. ```APIDOC ## __construct() ### Description Class constructor, connects to database and caching layers. ### Method `__construct` ### Parameters None ### Throws `PDOException` ``` -------------------------------- ### Get Configuration Value Source: https://api.legiscan.com/docs/class-LegiScan.html Retrieves a specific configuration value or the entire configuration array. Useful for accessing API settings. ```php LegiScan::getConfig( 'api_key' ); ``` -------------------------------- ### Basic Memory Cache Operations Source: https://api.legiscan.com/docs/class-LegiScan_Cache_Memory.html Demonstrates how to get a singleton instance of the memory cache, set a key-value pair, and retrieve the value. This is useful for simple caching of frequently accessed data. ```php $memcache = LegiScan_Cache_Memory::getInstance(); $key = "key-sample-1"; $memcache->set($key, 12345); $value = $memcache->get($key); var_dup($value); ``` -------------------------------- ### Get Bills Sponsored by Legislator Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Retrieves a list of bills sponsored by a specific legislator. Requires the internal LegiScan people ID. ```PHP public function getSponsoredList($people_id) { $params = array('id'=>$people_id); return $this->apiRequest('getSponsoredList', $params); } ``` -------------------------------- ### Instantiate and Process POST Request Source: https://api.legiscan.com/docs/source-class-LegiScan_WebTest.html Creates an instance of the LegiScan_WebTest class and calls its processPOST method. ```php $webtest = new LegiScan_WebTest(); // Do the thing! $webtest->processPOST(); ``` -------------------------------- ### Provide Extra Help Text for CLI Source: https://api.legiscan.com/docs/source-class-LegiScan_CommandLine.html This variable constructs additional help text for the command-line interface, providing usage examples for various commands. It's displayed when the --help option is used or if options are missing. ```php $extra_help = ''; $extra_help .= "Command line interface to the LegiScan API that is capable of importing data, examples:\n"; $extra_help .= " " . basename($argv[0]) . " --monitorlist --import changed\n"; $extra_help .= " " . basename($argv[0]) . " --masterlist CA --import new\n"; $extra_help .= " " . basename($argv[0]) . " --bill 823201\n"; $extra_help .= " " . basename($argv[0]) . " --text 1565693\n"; $extra_help .= " " . basename($argv[0]) . " --search \"citizens ADJ united\" --import new --score 75\n"; $extra_help .= " " . basename($argv[0]) . " --monitor 852213 --stance support\n"; $extra_help .= " " . basename($argv[0]) . " --clean --verbose\n"; legiscan_getopt($options, $extra_help); ``` -------------------------------- ### Get API Request URL Source: https://api.legiscan.com/docs/source-class-APIAccessException.html Retrieves the most recent API request URL generated by the apiRequest() method. This is useful for debugging or logging. ```php function getURL() { return $this->request_url; } ``` -------------------------------- ### LegiScan_Pull::getBill Source: https://api.legiscan.com/docs/class-LegiScan_Pull.html Get the bill detail record for a specified bill. Returns a record containing a summary of the bill detail information. ```APIDOC ## getBill( integer $bill_id ) ### Description Get the bill detail record for a specified bill. ### Parameters #### Path Parameters - **bill_id** (integer) - Required - The internal bill id for the requested bill ### Returns array - The record containing a summary of the bill detail information ``` -------------------------------- ### respondOk() Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Wrapper function around respond() that creates a valid OK response. Optionally includes a list of missing objects. ```APIDOC ## respondOk() ### Description Wrapper function around respond() that creates a valid OK response. Optionally includes a list of missing objects. ### Method public function respondOk(array $missing = array()) ### Parameters #### Parameters - **missing** (array) - Optional - Array listing missing objects to request in the response ### Returns None ``` -------------------------------- ### Configure State Synchronization Source: https://api.legiscan.com/docs/class-LegiScan_Worker.html Edit the config.php file to specify which states to track. It is recommended to pre-load state datasets using legiscan-bulk.php before the first run. ```php states[] = CA states[] = US ``` -------------------------------- ### Reset Missing Objects List Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Resets the list of missing objects. This is typically used to clear the list after processing or when starting a new cycle. ```php public function resetMissing() { $this->missing = array(); return true; } ``` -------------------------------- ### Get All State Records Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Fetches a list of state table records for all substitutions. The results are cached statically to improve performance on subsequent calls. ```php public function getStateList() { static $state_list = array(); if (empty($state_list)) { $sql = 'SELECT * FROM ls_state ORDER BY state_abbr'; $rs = $this->db->query($sql); while ($r = $rs->fetch()) { $state_list[$r['state_id']] = $r; } } return $state_list; } ``` -------------------------------- ### respondOk() Source: https://api.legiscan.com/docs/source-class-APIException.html Wrapper function around respond() that creates a valid OK response. ```APIDOC ## respondOk() ### Description Sends a successful API response (status: LegiScan::API_OK) back to the client. Optionally includes a list of missing objects. ### Method `public function respondOk(array $missing = array())` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **missing** (array) - Optional - An array listing missing objects to request in the response. ``` -------------------------------- ### Get Database Connection Handle Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Returns the PDO database connection handle. This allows external components to interact directly with the database if necessary. ```php public function getDB() { return $this->db; } ``` -------------------------------- ### Initialize APIStatusException Class Source: https://api.legiscan.com/docs/source-class-APIStatusException.html Initializes the APIStatusException class by creating an instance of LegiScan_Process. This is the constructor method. ```php function __construct() { $this->logic = new LegiScan_Process(); } ``` -------------------------------- ### Get Bill Text by Document ID Source: https://api.legiscan.com/docs/source-class-APIAccessException.html Retrieves the text content of a bill, which is base64 encoded. Optionally prefers PDF format if configured. ```php public function getBillText($text_id) { $params = array('id'=>$text_id); if (LegiScan::getConfig('prefer_pdf')) $params['prefer'] = 'pdf'; return $this->apiRequest('getBillText', $params); } ```