desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Find referenced elements in the tree @param element: the element @param table: the DB table @param fields: the FK fields in the table @param tree: the import tree @param directory: a dictionary to lookup elements in the tree (will be filled in by this function)'
def lookahead(self, element, table=None, fields=None, tree=None, directory=None, lookup=None):
db = current.db s3db = current.s3db xml = current.xml import_uid = xml.import_uid ATTRIBUTE = xml.ATTRIBUTE TAG = xml.TAG UID = xml.UID reference_list = [] root = None if (tree is not None): if isinstance(tree, etree._Element): root = tree else: ...
'Load an item from the item table (counterpart to add_item when restoring a job from the database)'
def load_item(self, row):
item = S3ImportItem(self) if (not item.restore(row)): self.error = item.error if (item.load_parent is None): self.error_tree.append(deepcopy(item.element)) item_id = item.item_id self.items[item_id] = item return item_id
'Resolve the reference list of an item @param item_id: the import item UID @param import_list: the ordered list of items (UIDs) to import'
def resolve(self, item_id, import_list):
item = self.items[item_id] if (item.lock or (item.accepted is False)): return False references = [] for reference in item.references: ritem_id = reference.entry.item_id if (ritem_id and (ritem_id not in import_list)): references.append(ritem_id) for ritem_id in re...
'Commit the import job to the DB @param ignore_errors: skip any items with errors (does still report the errors) @param log_items: callback function to log import items before committing them'
def commit(self, ignore_errors=False, log_items=None):
ATTRIBUTE = current.xml.ATTRIBUTE METHOD = S3ImportItem.METHOD import_list = [] for item_id in self.items: self.resolve(item_id, import_list) if (item_id not in import_list): import_list.append(item_id) items = self.items count = 0 mtime = None created = [] ...
'Define the database tables for jobs and items'
def __define_tables(self):
self.job_table = self.define_job_table() self.item_table = self.define_item_table()
'Store this job and all its items in the job table'
def store(self):
db = current.db self.__define_tables() jobtable = self.job_table query = (jobtable.job_id == self.job_id) row = db(query).select(jobtable.id, limitby=(0, 1)).first() if row: record_id = row.id else: record_id = None record = Storage(job_id=self.job_id) try: ta...
'Reconstruct the element tree of this job'
def get_tree(self):
if (self.tree is not None): return self.tree else: xml = current.xml ATTRIBUTE = xml.ATTRIBUTE UID = xml.UID root = etree.Element(xml.TAG.root) for item in self.items.values(): element = item.element if ((element is not None) and (not item....
'Delete this job and all its items from the job table'
def delete(self):
db = current.db self.__define_tables() item_table = self.item_table query = (item_table.job_id == self.job_id) db(query).delete() job_table = self.job_table query = (job_table.job_id == self.job_id) db(query).delete()
'Restore the job\'s reference structure after loading items from the item table'
def restore_references(self):
db = current.db UID = current.xml.UID for item in self.items.values(): for citem_id in item.load_components: if (citem_id in self.items): item.components.append(self.items[citem_id]) item.load_components = [] for ritem in item.load_references: ...
'Constructor @param primary: list or tuple of primary fields to find a match, must always match (mandatory, defaults to "name" field) @param secondary: list or tuple of secondary fields to find a match, must match if values are present in the import item @param ignore_case: ignore case for string/text fields @param ign...
def __init__(self, primary=None, secondary=None, ignore_case=True, ignore_deleted=False):
if (not primary): primary = ('name',) self.primary = set(primary) if (not secondary): self.secondary = set() else: self.secondary = set(secondary) self.ignore_case = ignore_case self.ignore_deleted = ignore_deleted
'Entry point for importer @param item: the import item @return: the duplicate Row if match found, otherwise None @raise SyntaxError: if any of the query fields doesn\'t exist in the item table'
def __call__(self, item):
data = item.data table = item.table query = None error = 'Invalid field for duplicate detection: %s (%s)' match = self.match primary = self.primary for fname in primary: if (fname not in table.fields): raise SyntaxError((error % (fname, table))) ...
'Helper function to generate a match-query @param field: the Field @param value: the value @return: a Query'
def match(self, field, value):
ftype = str(field.type) ignore_case = self.ignore_case if (ignore_case and hasattr(value, 'lower') and (ftype in ('string', 'text'))): query = (field.lower() == s3_unicode(value).lower().encode('utf-8')) else: query = (field == value) return query
'Constructor'
def __init__(self):
import csv from xml.sax.saxutils import unescape self.csv = csv self.unescape = unescape self.tasks = [] self.alternateTables = {'hrm_group_membership': {'tablename': 'pr_group_membership', 'prefix': 'pr', 'name': 'group_membership'}, 'hrm_person': {'tablename': 'pr_person', 'prefix': 'pr', 'nam...
'Load the descriptor file and then all the import tasks in that file into the task property. The descriptor file is the file called tasks.cfg in path. The file consists of a comma separated list of: module, resource name, csv filename, xsl filename.'
def load_descriptor(self, path):
source = open(os.path.join(path, 'tasks.cfg'), 'r') values = self.csv.reader(source) for details in values: if (details == []): continue prefix = details[0][0].strip('" ') if (prefix == '#'): continue if (prefix == '*'): self.extract_oth...
'Extract the details for a CSV Import Task'
def extract_csv_import_line(self, path, details):
argCnt = len(details) if ((argCnt == 4) or (argCnt == 5)): mod = details[0].strip('" ') res = details[1].strip('" ') folder = current.request.folder csvFileName = details[2].strip('" ') if (csvFileName[:7] == 'http://'): csv = csvFileName else...
'Store a single import job into the tasks property *,function,filename,*extraArgs'
def extract_other_import_line(self, path, details):
function = details[1].strip('" ') filepath = None if (len(details) >= 3): filename = details[2].strip('" ') if (filename != ''): (subfolder, filename) = os.path.split(filename) if (subfolder != ''): path = os.path.join(current.request.folder, 'mo...
'Execute each import job, in order'
def execute_import_task(self, task):
start = datetime.now() if (task[0] == 1): s3db = current.s3db response = current.response errorString = 'prepopulate error: file %s missing' view = response.view prefix = task[1] name = task[2] tablename = ('%s_%s' % (prefix, name)) if ...
'Execute import tasks which require a custom function, such as import_role'
def execute_special_task(self, task):
start = datetime.now() s3 = current.response.s3 if (task[0] == 2): fun = task[1] filepath = task[2] extraArgs = task[3] if (filepath is None): if (extraArgs is None): error = s3[fun]() else: error = s3[fun](*extraArgs) ...
'Convert an Organisation Name to a pe_id - helper for import_role'
@staticmethod def _lookup_pe(entity):
table = current.s3db.org_organisation org = current.db((table.name == entity)).select(table.pe_id, limitby=(0, 1)).first() try: pe_id = org.pe_id except: current.log.warning(('import_role cannot find pe_id for %s' % entity)) pe_id = None return pe_id
'Import Roles from CSV'
def import_role(self, filename):
try: openFile = open(filename, 'r') except IOError: return ('Unable to open file %s' % filename) auth = current.auth acl = auth.permission create_role = auth.s3_create_role def parseACL(_acl): permissions = _acl.split('|') aclValue = 0 for perm...
'Import Users from CSV with an import Prep'
def import_user(self, filename):
current.response.s3.import_prep = current.auth.s3_import_prep user_task = [1, 'auth', 'user', filename, os.path.join(current.request.folder, 'static', 'formats', 's3csv', 'auth', 'user.xsl'), None] self.execute_import_task(user_task)
'Import RSS Feeds from CSV with an import Prep'
def import_feed(self, filename):
stylesheet = os.path.join(current.request.folder, 'static', 'formats', 's3csv', 'msg', 'rss_channel.xsl') current.response.s3.import_prep = current.s3db.pr_import_prep user_task = [1, 'pr', 'contact', filename, stylesheet, None] self.execute_import_task(user_task) user_task = [1, 'msg', 'rss_channel...
'Import images, such as a logo or person image filename a CSV list of records and filenames tablename the name of the table idfield the field used to identify the record imagefield the field to where the image will be added Example: bi.import_image ("org_logos.csv", "org_organisation", "name", "logo") and...
def import_image(self, filename, tablename, idfield, imagefield):
try: openFile = open(filename, 'r') except IOError: return ('Unable to open file %s' % filename) (prefix, name) = tablename.split('_', 1) reader = self.csv.DictReader(openFile) db = current.db s3db = current.s3db audit = current.audit table = s3db[tablename] ...
'Install a Font'
def import_font(self, url):
if (url == 'unifont'): url = 'http://unifoundry.com/pub/unifont-7.0.06/font-builds/unifont-7.0.06.ttf' filename = 'unifont.ttf' extension = 'ttf' else: filename = url.split('/')[(-1)] (filename, extension) = filename.rsplit('.', 1) if (extension not in ('ttf', 'gz...
'Import CSV files from remote servers'
def import_remote_csv(self, url, prefix, resource, stylesheet):
extension = url.split('.')[(-1)] if (extension not in ('csv', 'zip')): current.log.error(('error importing remote file %s: invalid extension' % url)) return cwd = os.getcwd() TEMP = os.path.join(cwd, 'temp') if (not os.path.exists(TEMP)): import tempfile ...
'Run a custom Import Script @ToDo: Report Errors during Script run to console better'
@staticmethod def import_script(filename):
from gluon.cfs import getcfs from gluon.compileapp import build_environment from gluon.restricted import restricted environment = build_environment(current.request, current.response, current.session) environment['current'] = current environment['auth'] = current.auth environment['db'] = curr...
'Import XML data using an XSLT: static/formats/<format>/import.xsl Setting the source_type is possible'
def import_xml(self, filepath, prefix, resourcename, format, source_type=None):
prefix = prefix.strip('" ') resourcename = resourcename.strip('" ') errorString = 'prepopulate error: file %s missing' try: File = open(filepath, 'r') except IOError: self.errorList.append((errorString % filepath)) return stylesheet = os.path.join(curren...
'Load and then execute the import jobs that are listed in the descriptor file (tasks.cfg)'
def perform_tasks(self, path):
self.load_descriptor(path) for task in self.tasks: if (task[0] == 1): self.execute_import_task(task) elif (task[0] == 2): self.execute_special_task(task)
'Strip out unnecessary characters from the string: +()- & space'
@staticmethod def sanitise_phone(phone, channel_id=None):
settings = current.deployment_settings table = current.s3db.msg_sms_outbound_gateway if channel_id: row = current.db((table.channel_id == channel_id)).select(limitby=(0, 1)).first() default_country_code = row['msg_sms_outbound_gateway.default_country_code'] else: default_country_...
'Decode an RFC2047-encoded email header (e.g. "Dominic =?ISO-8859-1?Q?K=F6nig?=") and return it as unicode. @param header: the header'
@staticmethod def decode_email(header):
import re header = re.sub('(=\\?.*\\?=)(?!$)', '\\1 ', header) from email.header import decode_header decoded = decode_header(header) return ' '.join([s3_unicode(part[0], (part[1] or 'ASCII')) for part in decoded])
'Helper method to sort messages according to sender priority.'
@staticmethod def sort_by_sender(row):
s3db = current.s3db db = current.db ptable = s3db.msg_parsing_status mtable = s3db.msg_message stable = s3db.msg_sender try: pmessage = db((ptable.id == row.id)).select(ptable.message_id) m_id = pmessage.message_id message = db((mtable.id == m_id)).select(mtable.from_addr...
'Parse unparsed Messages from Channel with Parser - called from Scheduler @param channel_id: Channel @param function_name: Parser'
@staticmethod def parse(channel_id, function_name):
from s3parser import S3Parsing parser = S3Parsing.parser stable = current.s3db.msg_parsing_status query = ((stable.channel_id == channel_id) & (stable.is_parsed == False)) messages = current.db(query).select(stable.id, stable.message_id) for message in messages: reply_id = parser(functio...
'Form to Compose a Message @param type: The default message type: None, EMAIL, SMS or TWITTER @param recipient_type: Send to Persons or Groups? (pr_person or pr_group) @param recipient: The pe_id of the person/group to send the message to - this can also be set by setting one of (in priority order, if multiple found): ...
def compose(self, type='SMS', recipient_type=None, recipient=None, subject='', message='', url=None):
if (not url): url = URL(c='msg', f='compose') auth = current.auth if (auth.is_logged_in() or auth.basic()): pass else: redirect(URL(c='default', f='user', args='login', vars={'_next': url})) if (not auth.permission.has_permission('update', c='msg')): current.session.e...
'Send a single message to an Address @param recipient: "email@address", "+4412345678", "@nick" @param message: message body @param subject: message subject (Email only)'
@staticmethod def send(recipient, message, subject=None):
if recipient.startswith('@'): tablename = 'msg_twitter' elif ('@' in recipient): tablename = 'msg_email' else: tablename = 'msg_sms'
'Send a single message to a Person Entity (or list thereof) @ToDo: contact_method = ALL - look up the pr_contact options available for the pe & send via all @ToDo: This is not transaction safe - power failure in the middle will cause no message in the outbox'
@staticmethod def send_by_pe_id(pe_id, subject='', message='', contact_method='EMAIL', document_ids=None, from_address=None, system_generated=False):
s3db = current.s3db if (contact_method == 'EMAIL'): if (not from_address): from_address = current.deployment_settings.get_mail_sender() table = s3db.msg_email _id = table.insert(body=message, subject=subject, from_address=from_address, inbound=False) record = dict(id=...
'Send pending messages from outbox (usually called from scheduler) @param contact_method: the output channel (see pr_contact.method) @todo: contact_method = "ALL"'
def process_outbox(self, contact_method='EMAIL'):
db = current.db s3db = current.s3db lookup_org = False channels = {} outgoing_sms_handler = None channel_id = None if (contact_method == 'SMS'): table = s3db.msg_sms_outbound_gateway etable = db.msg_channel query = ((table.deleted == False) & (table.channel_id == etab...
'Push the message relating to google cloud messaging server @param title: The title for notification @param message: The message to be sent to GCM server @param api_key: The API key for GCM server @param registration_ids: The list of id that will be notified @param channel_id: The specific channel_id to use for GCM pus...
def gcm_push(self, title=None, uri=None, message=None, registration_ids=None, channel_id=None):
if ((not title) or (not uri) or (not message) or (not len(registration_ids))): return from gcm import GCM gcmtable = current.s3db.msg_gcm_channel if channel_id: query = (gcmtable.channel_id == channel_id) else: query = ((gcmtable.enabled == True) & (gcmtable.deleted != True))...
'Function to send Email - simple Wrapper over Web2Py\'s Email API'
def send_email(self, to, subject, message, attachments=None, cc=None, bcc=None, reply_to=None, sender=None, encoding='utf-8'):
if (not to): return False settings = current.deployment_settings default_sender = settings.get_mail_sender() if (not default_sender): current.log.warning('Email sending disabled until the Sender address has been set in models/000_config.py') retur...
'Sanitize the email sender string to prevent MIME-encoding of the from-address (RFC2047) @param: the sender-string @returns: the sanitized sender-string'
@staticmethod def sanitize_sender(sender):
if (not sender): return sender match = SENDER.match(sender) if match: (sender_name, from_address) = match.groups() if any((((32 > ord(c)) or (ord(c) > 127)) for c in sender_name)): from email.header import Header sender_name = Header(sender_name.strip(), 'utf-...
'API wrapper over send_by_pe_id'
def send_email_by_pe_id(self, pe_id, subject='', message='', from_address=None, system_generated=False):
return self.send_by_pe_id(pe_id, subject, message, 'EMAIL', from_address, system_generated)
'Function to create an OpenGeoSMS @param: location_id - reference to record in gis_location table @param: code - the type of OpenGeoSMS: S = Sahana SI = Incident Report ST = Task Dispatch @param: map: "google" or "osm" @param: text - the rest of the message Returns the formatted OpenGeoSMS or None if it can\'t find an ...
@staticmethod def prepare_opengeosms(location_id, code='S', map='google', text=''):
if (not location_id): return text db = current.db s3db = current.s3db table = s3db.gis_location query = (table.id == location_id) location = db(query).select(table.lat, table.lon, limitby=(0, 1)).first() if (not location): return text lat = location.lat lon = location...
'Function to parse an OpenGeoSMS @param: message - Inbound message to be parsed for OpenGeoSMS. Returns the lat, lon, code and text contained in the message.'
@staticmethod def parse_opengeosms(message):
lat = '' lon = '' code = '' text = '' words = message.split(' ') if ('http://maps.google.com/?q' in words[0]): pwords = words[0].split('?q=')[1].split(',') lat = pwords[0] lon = pwords[1].split('&')[0] code = pwords[1].split('&')[1].split('=')[1] text =...
'Function to send SMS via Web API'
def send_sms_via_api(self, mobile, text='', message_id=None, channel_id=None):
db = current.db s3db = current.s3db table = s3db.msg_sms_webapi_channel if channel_id: sms_api = db((table.channel_id == channel_id)).select(limitby=(0, 1)).first() else: sms_api = db((table.enabled == True)).select(limitby=(0, 1)).first() if (not sms_api): return False ...
'Function to send SMS via locally-attached Modem - needs to have the cron/sms_handler_modem.py script running'
def send_sms_via_modem(self, mobile, text='', channel_id=None):
mobile = self.sanitise_phone(mobile, channel_id) mobile = ('+%s' % mobile) try: self.modem.send_sms(mobile, text) return True except KeyError: current.log.error('s3msg', 'Modem not available: need to have the cron/sms_handler_modem.py script running') ...
'Function to send SMS via SMTP NB Different Gateways have different requirements for presence/absence of International code http://en.wikipedia.org/wiki/List_of_SMS_gateways http://www.obviously.com/tech_tips/SMS_Text_Email_Gateway.html'
def send_sms_via_smtp(self, mobile, text='', channel_id=None):
table = current.s3db.msg_sms_smtp_channel if channel_id: query = (table.channel_id == channel_id) else: query = (table.enabled == True) settings = current.db(query).select(limitby=(0, 1)).first() if (not settings): return False mobile = self.sanitise_phone(mobile, channel...
'Send a URL request to Tropo to pick a message up'
def send_sms_via_tropo(self, row_id, message_id, recipient, message, network='SMS', channel_id=None):
db = current.db s3db = current.s3db table = s3db.msg_tropo_channel base_url = 'http://api.tropo.com/1.0/sessions' action = 'create' if channel_id: query = (table.channel_id == channel_id) else: query = (table.enabled == True) tropo_settings = db(query).select(table.token_...
'API wrapper over send_by_pe_id'
def send_sms_by_pe_id(self, pe_id, message='', from_address=None, system_generated=False):
return self.send_by_pe_id(pe_id, message, 'SMS', from_address, system_generated, subject='')
'Only keep characters that are legal for a twitter account: letters, digits, and _'
@staticmethod def _sanitise_twitter_account(account):
return account.translate(IDENTITYTRANS, NOTTWITTERCHARS)
'Breaks text to <=chunk_size long chunks. Tries to do this at a space. All chunks, except for last, end with suffix. All chunks, except for first, start with prefix.'
@staticmethod def _break_to_chunks(text, chunk_size=TWITTER_MAX_CHARS, suffix=TWITTER_HAS_NEXT_SUFFIX, prefix=TWITTER_HAS_PREV_PREFIX):
from s3 import s3_str res = [] current_prefix = '' while text: if (len((current_prefix + text)) <= chunk_size): res.append((current_prefix + text)) return res else: c = text[:((chunk_size - len(current_prefix)) - len(suffix))] i = c.rfind('...
'Initialize Twitter API'
@staticmethod def get_twitter_api(channel_id=None):
try: import tweepy except ImportError: current.log.error('s3msg', 'Tweepy not available, so non-Tropo Twitter support disabled') return None table = current.s3db.msg_twitter_channel if (not channel_id): query = (table.enabled == True) limitby ...
'Function to tweet. If a recipient is specified then we send via direct message if the recipient follows us. - falls back to @mention (leaves less characters for the message). Breaks long text to chunks if needed. @ToDo: Option to Send via Tropo'
def send_tweet(self, text='', recipient=None):
twitter_settings = self.get_twitter_api() if (not twitter_settings): return False import tweepy twitter_api = twitter_settings[0] twitter_account = twitter_settings[1] from_address = twitter_api.me().screen_name db = current.db s3db = current.s3db table = s3db.msg_twitter ...
'Posts a message on Facebook https://developers.facebook.com/docs/graph-api @ToDo: Log messages in msg_facebook'
def post_to_facebook(self, text='', channel_id=None):
table = current.s3db.msg_facebook_channel if (not channel_id): query = (table.enabled == True) else: query = (table.channel_id == channel_id) c = current.db(query).select(table.app_id, table.app_secret, table.page_id, table.page_access_token, limitby=(0, 1)).first() import facebook ...
'Poll a Channel for New Messages'
def poll(self, tablename, channel_id):
channel_type = tablename.split('_', 2)[1] function_name = ('poll_%s' % channel_type) try: fn = getattr(S3Msg, function_name) except: error = ('Unsupported Channel: %s' % channel_type) current.log.error(error) return error result = fn(channel_id) return resul...
'This is a simple mailbox polling script for the Messaging Module. It is normally called from the scheduler. @ToDo: If there is a need to collect from non-compliant mailers then suggest using the robust Fetchmail to collect & store in a more compliant mailer! @ToDo: If delete_from_server is false, we don\'t want to dow...
@staticmethod def poll_email(channel_id):
db = current.db s3db = current.s3db table = s3db.msg_email_channel query = (table.channel_id == channel_id) channel = db(query).select(table.username, table.password, table.server, table.protocol, table.use_ssl, table.port, table.delete_from_server, limitby=(0, 1)).first() if (not channel): ...
'Fetches the inbound SMS from Mobile Commons API http://www.mobilecommons.com/mobile-commons-api/rest/#ListIncomingMessages'
@staticmethod def poll_mcommons(channel_id):
db = current.db s3db = current.s3db table = s3db.msg_mcommons_channel query = (table.channel_id == channel_id) channel = db(query).select(table.url, table.campaign_id, table.username, table.password, table.query, table.timestmp, limitby=(0, 1)).first() if (not channel): return ('No Su...
'Fetches the inbound SMS from Twilio API http://www.twilio.com/docs/api/rest'
@staticmethod def poll_twilio(channel_id):
db = current.db s3db = current.s3db table = s3db.msg_twilio_channel query = (table.channel_id == channel_id) channel = db(query).select(table.account_sid, table.auth_token, table.url, limitby=(0, 1)).first() if (not channel): return ('No Such Twilio Channel: %s' % channel_id)...
'Fetches all new messages from a subscribed RSS Feed'
@staticmethod def poll_rss(channel_id):
db = current.db s3db = current.s3db table = s3db.msg_rss_channel query = (table.channel_id == channel_id) channel = db(query).select(table.date, table.etag, table.url, table.content_type, table.username, table.password, limitby=(0, 1)).first() if (not channel): return ('No Such RSS...
'Function to call to fetch tweets into msg_twitter table - called via Scheduler or twitter_inbox controller http://tweepy.readthedocs.org/en/v3.3.0/api.html'
@staticmethod def poll_twitter(channel_id):
try: import tweepy except ImportError: current.log.error('s3msg', 'Tweepy not available, so non-Tropo Twitter support disabled') return False db = current.db s3db = current.s3db twitter_settings = S3Msg.get_twitter_api(channel_id) if twitter_settings:...
'Update the Status for a Channel'
@staticmethod def update_channel_status(channel_id, status, period=None):
db = current.db stable = current.s3db.msg_channel_status query = (stable.channel_id == channel_id) old_status = db(query).select(stable.status, limitby=(0, 1)).first() if old_status: if (status and (status[0] == '+')): old_status = old_status.status try: ...
'Fetch Results for a Twitter Search Query'
@staticmethod def twitter_search(search_id):
try: import TwitterSearch except ImportError: error = 'Unresolved dependency: TwitterSearch required for fetching results from twitter keyword queries' current.log.error('s3msg', error) current.session.error = error redirect(URL(f='index')) ...
'Process results of twitter search with KeyGraph.'
@staticmethod def process_keygraph(search_id):
import subprocess import os import tempfile db = current.db s3db = current.s3db curpath = os.getcwd() preprocess = S3Msg.preprocess_tweet def generateFiles(): dirpath = tempfile.mkdtemp() os.chdir(dirpath) rtable = s3db.msg_twitter_search_results tweets = ...
'Preprocesses tweets to remove URLs, RTs, extra whitespaces and replace hashtags with their definitions.'
@staticmethod def preprocess_tweet(tweet):
import re tagdef = S3Msg.tagdef tweet = tweet.lower() tweet = re.sub('((www\\.[\\s]+)|(https?://[^\\s]+))', '', tweet) tweet = re.sub('@[^\\s]+', '', tweet) tweet = re.sub('[\\s]+', ' ', tweet) tweet = re.sub('#([^\\s]+)', (lambda m: tagdef(m.group(0))), tweet) tweet = tweet.strip('\'...
'Returns the definition of a hashtag.'
@staticmethod def tagdef(hashtag):
hashtag = hashtag.split('#')[1] turl = ('http://api.tagdef.com/one.%s.json' % hashtag) try: hashstr = urllib2.urlopen(turl).read() hashdef = json.loads(hashstr) except: return hashtag else: return hashdef['defs']['def']['text']
'API entry point @param r: the S3Request instance @param attr: controller attributes for the request'
def apply_method(self, r, **attr):
if (r.http in ('GET', 'POST')): output = self.compose(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) return output
'Generate a form to send a message @param r: the S3Request instance @param attr: controller attributes for the request'
def compose(self, r, **attr):
T = current.T auth = current.auth self.url = url = r.url() if (auth.is_logged_in() or auth.basic()): pass else: redirect(URL(c='default', f='user', args='login', vars={'_next': url})) if (not current.deployment_settings.has_module('msg')): current.session.error = T('Canno...
'Set the sender Route the message'
def _compose_onvalidation(self, form):
post_vars = current.request.post_vars settings = current.deployment_settings if settings.get_mail_default_subject(): system_name_short = ('%s - ' % settings.get_system_name_short()) else: system_name_short = '' if settings.get_mail_auth_user_in_subject(): user = current...
'Creates the form for composing the message'
def _compose_form(self):
T = current.T db = current.db s3db = current.s3db request = current.request get_vars = request.get_vars mtable = s3db.msg_message otable = s3db.msg_outbox mtable.body.label = T('Message') mtable.body.default = self.message mtable.inbound.default = False mtable.inbound.writabl...
'Constructor @param label: the label @param c: the controller @param f: the function @param args: the arguments list @param vars: the variables Storage @param extension: the request extension @param a: the application (defaults to current.request.application) @param r: the request to default to @param m: the URL method...
def __init__(self, label=None, c=None, f=None, args=None, vars=None, extension=None, a=None, r=None, m=None, p=None, t=None, url=None, tags=None, parent=None, translate=True, layout=None, check=None, restrict=None, link=True, mandatory=False, ltr=False, **attributes):
if (isinstance(label, basestring) and translate): self.label = current.T(label) else: self.label = label if tags: if (type(tags) is not list): tags = [tags] self.tags = tags else: self.tags = [] if (r is not None): self.r = r if (a ...
'Check whether the current theme has a custom layout for this class, and if so, store it in current.layouts @param: the name of the custom layout @return: the layout or None if not present'
@staticmethod def get_layout(name):
if hasattr(current, 'layouts'): layouts = current.layouts else: layouts = {} if (layouts is False): return None if (name in layouts): return layouts[name] application = current.request.application settings = current.deployment_settings theme = settings.get_the...
'Clone this item and its components'
def clone(self):
item = self.__class__() item.label = self.label item.tags = self.tags item.r = self.r item.application = self.application item.controller = self.controller item.function = self.function item.match_controller = [c for c in self.match_controller] item.match_function = [f for f in self....
'Check whether this item belongs to the requested page (request). If this check returns False, then the item will be deactivated entirely, i.e. no further checks will be run and the renderer will never be called. @param request: the request object (defaults to current.request)'
def check_active(self, request=None):
c = self.get('controller') if c: return current.deployment_settings.has_module(c) return True if (request is None): request = current.request parent = self.parent if (parent is not None): return parent.check_active(request) elif self.mandatory: return True ...
'Check whether this item is enabled. This check does not directly disable the item, but rather sets the enabled-flag in the item which can then be used by the renderer. This function is called as the very last action immediately before rendering the item. If it returns True, then the enabled-flag of the item remains un...
def check_enabled(self):
return True
'Check whether the user is permitted to access this item. This check does not directly disable the item, but rather sets the authorized-flag in the item which can then be used by the renderer.'
def check_permission(self):
has_role = current.auth.s3_has_role authorized = False restrict = self.restrict if restrict: for role in restrict: if has_role(role): authorized = True break else: authorized = True if (self.accessible_url() == False): authorize...
'Check whether this item is in the selected path (i.e. whether it is or contains the item used to trigger the request). This check doesn\'t change the processing of the item, but rather sets the selected-flag which can then be used by the renderer If this is a top-level item, then this check sets the selected-flags for...
def check_selected(self, request=None):
if (self.selected is not None): return self.selected if (request is None): request = current.request if (self.parent is None): branch = self.branch(request) if (branch is not None): branch.select() if (not self.selected): self.selected = False ...
'Run hooked-in checks'
def check_hook(self):
cond = True check = self.check if (check is not None): if (not isinstance(check, (list, tuple))): check = [check] for condition in check: if (callable(condition) and (not condition(self))): cond = False elif (not condition): ...
'Check whether a tag is present in any item of the subtree'
def __contains__(self, tag):
components = self.components for i in components: if ((tag in i.tags) or (tag in i)): return 1 return 0
'Find all items within the tree with the specified tag @param tag: the tag'
def findall(self, tag):
items = [] if (tag in self.tags): items.append(self) components = self.components for c in components: _items = c.findall(tag) items.extend(_items) return items
'Enable items @param tag: enable all items in the subtree with this tag (no tag enables only this item)'
def enable(self, tag=None):
if (tag is not None): items = self.findall(tag) for item in items: item.enable() else: self.enabled = True return
'Disable items @param tag: disable all items in the subtree with this tag (no tag disables only this item)'
def disable(self, tag=None):
if (tag is not None): items = self.findall(tag) for item in items: item.disable() else: self.enabled = False return
'Select an item. If given a tag, this selects the first matching descendant (depth-first search), otherwise selects this item. Propagates the selection up the path to the root item (including the root item) @param tag: a string'
def select(self, tag=None):
selected = None if (tag is None): parent = self.parent if parent: parent.select() else: self.deselect_all() selected = True else: for item in self.components: if (not selected): selected = item.select(tag=tag) ...
'De-select this item and all its descendants'
def deselect_all(self):
self.selected = None for item in self.components: item.deselect_all() return
'Alter the renderer for a tagged subset of items in the subtree. @param layout: the layout (renderer) @param recursive: set this layout recursively for the subtree @param tag: set this layout only for items with this tag'
def set_layout(self, layout, recursive=False, tag=None):
if (layout is not None): if ((tag is None) or (tag in self.tags)): self.renderer = layout if recursive: for c in self.components: if ((tag is None) or (tag in c.tags)): c.set_layout(layout, recursive=recursive, tag=tag) return
'Get a Python-attribute of this item instance, falls back to the same attribute in the parent item if not set in this instance, used to inherit attributes to components @param name: the attribute name'
def get(self, name, default=None):
if (name in self.__dict__): value = self.__dict__[name] else: value = None if (value is not None): return value if (name[:2] == '__'): raise AttributeError parent = self.parent if (parent is not None): return parent.get(name) return default
'Match this item against request (uses GET vars) @param request: the request object (defaults to current.request) @return: the match level (integer): 0=no match 1=controller 2=controller+function 3=controller+function+args 4=controller+function+args+vars @note: currently ignores numerical arguments in the request, whic...
def match(self, request=None):
level = 0 args = self.args link_vars = self.vars if ((self.application is not None) and (self.application != request.application)): return 0 if (self.opts.selectable is False): return 0 check = self.check_hook() if check: enabled = self.check_enabled() if (not...
'Get the matching branch item for request @param request: the request object (defaults to current.request)'
def branch(self, request=None):
if (request is None): request = current.request (leaf, level) = self.__branch(request) if level: return leaf else: return None
'Find the best match for request within the subtree, recursive helper method for branch(). @param request: the request object'
def __branch(self, request):
items = self.get_all(enabled=True) l = self.match(request) if (not items): return (self, l) else: (match, maxlevel) = (None, (l - 1)) for i in items: (item, level) = i.__branch(request) if ((item is not None) and (level > maxlevel)): match ...
'String representation of this item'
def __repr__(self):
components = [str(c) for c in self.components] if self.enabled: label = str(self.label) else: label = ('%s (disabled)' % self.label) label = ('%s:%s' % (self.__class__.__name__, label)) if components: return ('<%s {%s}>' % (label, ','.join(components))) else: ...
'Return the target URL for this item, doesn\'t check permissions @param extension: override the format extension @param kwargs: override URL query vars'
def url(self, extension=None, **kwargs):
if (not self.link): return None if self.override_url: return self.override_url args = self.args if self.vars: link_vars = Storage(self.vars) link_vars.update(kwargs) else: link_vars = Storage(kwargs) if (extension is None): extension = self.extensi...
'Return the target URL for this item if accessible by the current user, otherwise False @param extension: override the format extension @param kwargs: override URL query vars'
def accessible_url(self, extension=None, **kwargs):
aURL = current.auth.permission.accessible_url if (not self.link): return None args = self.args if self.vars: link_vars = Storage(self.vars) link_vars.update(kwargs) else: link_vars = Storage(kwargs) if (extension is None): extension = self.extension a ...
'Append the format extension to the last argument @param f: the function @param args: argument list @param ext: the format extension @return: tuple (f, args)'
@staticmethod def __format(f, args, ext):
if ((not ext) or (ext == 'html')): return (f, args) items = [f] if args: items += args items = [i.rsplit('.', 1)[0] for i in items] items.append(('%s.%s' % (items.pop(), ext))) return (items[0], items[1:])
'Perform the checks and render this item. @param request: the request object (defaults to current.request)'
def render(self, request=None):
renderer = self.renderer output = None if (request is None): request = current.request if self.check_active(request): self.authorized = self.check_permission() self.selected = self.check_selected() cond = self.check_hook() if cond: enabled = self.check...
'Render the components of this item and return the results as list'
def render_components(self):
items = [] for c in self.components: i = c.render() if (i is not None): if (type(i) is list): items.extend(i) else: items.append(i) return items
'Invokes the renderer and serializes the output for the web2py template parser, returns a string to be written to the response body, uses the xml() method of the renderer output, if present.'
def xml(self):
output = self.render() if (output is None): return '' elif hasattr(output, 'xml'): return output.xml() else: return str(output)
'Set a parent for this item, base method for tree construction @param p: the parent @param i: the list index where to insert the item'
def set_parent(self, p=None, i=None):
if (p is None): p = self.parent if (p is None): return parent = self.parent if ((parent is not None) and (parent != p)): while (self in parent.components): parent.components.remove(self) if (i is not None): p.component.insert(i, self) else: p.c...
'Append a component @param item: the component'
def append(self, item=None):
if (item is not None): if (type(item) is list): for i in item: self.append(i) else: item.set_parent(self) return self
'Insert a component item at position i @param i: the index position @param item: the component item'
def insert(self, i, item=None):
if (item is not None): item.set_parent(self, i=i) return self
'Extend this item with a list of components @param items: list of component items'
def extend(self, items):
if items: for item in items: self.append(item) return self
'Convenience shortcut for extend @param components: list of components'
def __call__(self, *components):
self.extend(components) return self
'Append component items to this item @param items: the items to append'
def __add__(self, items):
if isinstance(items, (list, tuple)): self.extend(items) else: self.append(items) return self
'Get the component item at position i @param i: the index of the component item'
def __getitem__(self, i):
return self.components.__getitem__(i)