'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
    post_data = {}
    parts = sms_api.parameters.split('&')
    for p in parts:
        post_data[p.split('=')[0]] = p.split('=')[1]
    mobile = self.sanitise_phone(mobile, channel_id)
    text_latin1 = s3_unicode(text).encode('utf-8').decode('utf-8').encode('iso-8859-1')
    post_data[sms_api.message_variable] = text_latin1
    post_data[sms_api.to_variable] = str(mobile)
    url = sms_api.url
    clickatell = ('clickatell' in url)
    if clickatell:
        text_len = len(text)
        if (text_len > 480):
            current.log.error('Clickatell    messages    cannot    exceed    480    chars')
            return False
        elif (text_len > 320):
            post_data['concat'] = 3
        elif (text_len > 160):
            post_data['concat'] = 2
    request = urllib2.Request(url)
    query = urllib.urlencode(post_data)
    if (sms_api.username and sms_api.password):
        base64string = base64.encodestring(('%s:%s' % (sms_api.username, sms_api.password))).replace('\n', '')
        request.add_header('Authorization', ('Basic    %s' % base64string))
    try:
        result = urllib2.urlopen(request, query)
    except urllib2.HTTPError as e:
        current.log.error(('SMS    message    send    failed:    %s' % e))
        return False
    else:
        output = result.read()
        if clickatell:
            if output.startswith('ERR'):
                current.log.error(('Clickatell    message    send    failed:    %s' % output))
                return False
            elif (message_id and output.startswith('ID')):
                remote_id = output[4:]
                db((s3db.msg_sms.message_id == message_id)).update(remote_id=remote_id)
        elif ('mcommons' in url):
            if ('error' in output):
                current.log.error(('Mobile    Commons    message    send    failed:    %s' % output))
                return False
        return True
