def handle(request): 
    try:
        myself = siteaction.getLoggedInUser(request)
        if not myself:
            return ajaxian.getFailureResp('not_logged_in')

        comm_id = string.atoi(dataplus.dictGetVal(request.REQUEST,'commId'))
        community = models.Community.objects.get(id=comm_id)
        title = dataplus.dictGetSafeVal(request.REQUEST,'title')
        text = dataplus.dictGetSafeVal(request.REQUEST,'text')
        
        if community.is_moderated:
            if not community.members.filter(id=myself.id):
                return ajaxian.getFailureResp('This is a moderated community. So only members can post.')
        
        topic = models.CommunityTopic()
        topic.community = community
        topic.title = title
        topic.started_by = myself        
        topic.last_post_at = datetime.utcnow()
        topic.save()
        
        post = models.CommunityPost()
        post.topic = topic
        post.posted_by = myself
        post.text = text
        post.save()
        
        return ajaxian.getSuccessResp(me_communities_show.getTopicBoxHtml(topic, True))
    except:
        return ajaxian.getFailureResp('unknown')
Beispiel #2
0
def handle(request): 
    try:
        logged_in_type = siteaction.getLoggedInAccountType(request)
        rcvr_usrname = dataplus.dictGetVal(request.REQUEST,'sendTo')
        
        if logged_in_type == 'U':
            myself = siteaction.getLoggedInUser(request)
        elif logged_in_type == 'R':
            myself = siteaction.getLoggedInRecruiter(request)
        else:
            return ajaxian.getFailureResp('not_logged_in')
        
        rcvr_account = models.Account.objects.get(username=dataplus.dictGetVal(request.REQUEST,'sendTo'))
        text_message = dataplus.dictGetSafeVal(request.REQUEST,'text')
        html_message = dataplus.replaceHtmlLineBreaks(text_message)
        subject = dataplus.dictGetSafeVal(request.REQUEST,'subject')
        
        def internalSender(rcvr_accounts):
            mailman.sendMessage(myself.username, [rcvr.username for rcvr in rcvr_accounts], subject, html_message)
        
        def externalSender(rcvr_accounts):
            sender = '"' + myself.name + '" <' + myself.username + '*****@*****.**>'
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>'  for rcvr in rcvr_accounts]
            mailman.sendMail(sender, receivers, subject, html_message, None, None, text_message, reply_to=myself.email)
            
        mailman.sendBySettings([rcvr_account], internalSender, externalSender, 'TextMessage')
                
        return ajaxian.getSuccessResp('')
    except:
        return ajaxian.getFailureResp('unknown')
def handle(request):
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect('/login.htm')

    if request.method == 'GET':        
        action_result = ''
        if dataplus.dictGetVal(request.REQUEST, 'flashId'):
            action_result = dataplus.dictGetVal(statix.action_messages, dataplus.dictGetVal(request.REQUEST, 'flashId'), '')
            
        return siteaction.render_to_response('me/newcommunity.htm', {'action_result':action_result, 'myself':myself})
    elif request.method == 'POST':
        result, errMsg = codejar_validation.validateCommunityName(dataplus.dictGetVal(request.REQUEST,'communityName'))
        if not result:
            return siteaction.render_to_response('me/showmessage.htm', {'myself':myself, 'msg_heading':'Error', 'msg_html':'Invalid user input.'})

        comm_name = dataplus.dictGetSafeVal(request.REQUEST,'communityName')
        if codejar_network.checkCommunityNameExists(comm_name):
            return siteaction.render_to_response('me/newcommunity.htm', 
                                        {'communityName':comm_name,
                                         'communityDesc':dataplus.dictGetSafeVal(request.REQUEST,'communityDesc'),
                                         'action_result':dataplus.dictGetVal(statix.action_messages,'comm_name_exists') })
            
        community = models.Community()
        community.name = comm_name
        community.desc = dataplus.dictGetSafeVal(request.REQUEST,'communityDesc')
        community.is_moderated = { 'isPublic':False,
                                    'isModerated':True}[dataplus.dictGetVal(request.REQUEST, 'communityType')]
        community.owner_username = myself.username
        community.save()
        
        if request.FILES:
            img_save_success, error_code, img1, img2, img3, img4 = \
                studio.saveImage_x4_ByDate(request, 'comm_' + str(community.id), 'commIcon')

            if img_save_success:
                community.image_file_path = img1
                community.image_size1_file_path = img2
                community.image_size2_file_path = img3
                community.image_size3_file_path = img4
            else:
                return siteaction.render_to_response('me/newcommunity.htm', 
                                            {'communityName':community.name,
                                             'communityDesc':community.desc,
                                             'action_result':dataplus.dictGetVal(statix.action_messages,error_code) })
        else:
            community.image_file_path = config.noimg_comm
            community.image_size1_file_path = config.noimg_comm_50
            community.image_size2_file_path = config.noimg_comm_72
            community.image_size3_file_path = config.noimg_comm_128

        community.save()
        myself.communities.add(community)
        
        return HttpResponseRedirect(config.communities_url + '/' + str(community.id) + '/invite.htm')
Beispiel #4
0
def inviteToChatByEmail(request, session_id):
    try:
        chat_id = dataplus.dictGetVal(request.REQUEST, 'chatId', '')
        if not chat_id:
            return ajaxian.getFailureResp('error:invalid_chatId')
        username = dataplus.dictGetVal(request.REQUEST, 'username', '')
        name = dataplus.dictGetVal(request.REQUEST, 'name', '')
        invited_name = dataplus.dictGetVal(request.REQUEST, 'invitedName', '', lambda x: x.strip())
        invited_email = dataplus.dictGetVal(request.REQUEST, 'invitedEmail', '', lambda x: x.strip())
        text = dataplus.dictGetSafeVal(request.REQUEST, 'text', '')
        
        subject = 'Chat Invitation to Socialray'
        sender = name + '<' + username + '*****@*****.**>'
        html_message = '<p>Hello ' + invited_name + '</p><p>' + name + ' wants to have a chat with you and has sent you the following message ' + \
            'inviting you to a chat session in Socialray.</p><p>"' + text + '"</p>' + \
            '<p>You can <a href="' + config.server_base_url + '/chat/startchat.htm?chatId=' + chat_id + '">join ' + name + '</a> in chat now.</p>' + \
            '<p>Regards,<br />from Socialray</p>'
        text_message = 'Hello ' + invited_name + '\r\n' + name + ' wants to have a chat with you and has sent you the following message ' + \
            'inviting you to a chat session in Socialray.\r\n"' + text + '"\r\n' + \
            'Please visit ' + config.server_base_url + '/chat/startchat.htm?chatId=' + chat_id + ' to join ' + name + ' in chat now.\r\n' + \
            'regards,\r\nfrom Socialray\r\n\r\n'
        mailman.sendOneWayMail(sender, [invited_name + '<' + invited_email + '>'], subject, html_message, None, None, text_message)
        livewire_client.command('inviteByEmail', [session_id, chat_id, invited_name, invited_email])
        return ajaxian.getSuccessResp('')
    except:
        return ajaxian.getFailureResp('error:unknown')
Beispiel #5
0
def handle(request):
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect('/login.htm')            
            
    action_result = ''
    if dataplus.dictGetVal(request.REQUEST, 'flashId'):
        action_result = dataplus.dictGetVal(statix.action_messages, dataplus.dictGetVal(request.REQUEST, 'flashId'), '')
    
    if request.method == 'GET':        
        return siteaction.render_to_response('me/editmedia.htm',
            {'media_table_html':getMediaTableHtml(myself), 
             'action_result':action_result,
             'myself': myself
            })
    
    elif request.method == 'POST':
        action = dataplus.dictGetVal(request.REQUEST, 'action')
        if action == 'new':
            media = models.MediaLink()
            media.media_type = 'VID'
            media.media_host = 'youtube'
            media.user = myself

            url = dataplus.dictGetSafeVal(request.REQUEST, 'media_url')
            #Check if a valid youtube video url
            if re.match('^.*[/|\.]youtube.com\/watch\?v=.*$', url) is None:
                return siteaction.render_to_response('me/showmessage.htm', {'myself':myself, 'msg_heading':'Error', 'msg_html': 'Invalid user input.'})
            
            media.url = url
            media.description = dataplus.dictGetSafeVal(request.REQUEST, 'media_desc','')
            media.is_featured = dataplus.dictGetVal(request.REQUEST, 'is_featured', False, lambda x:True)
            media.save()
            flashId = 'ytvid_added'
        elif action == 'delete':
            media_id = dataplus.dictGetVal(request.REQUEST, 'media_id', 0, string.atoi)
            media = dataplus.returnIfExists(models.MediaLink.objects.filter(id=media_id))
            if not media:
                return siteaction.render_to_response('me/showmessage.htm', 
                                        {'myself':myself, 
                                        'msg_heading':'Error',
                                        'msg_html': 'Invalid Url'})
            media.delete()
            flashId = 'media_del'
        
        return HttpResponseRedirect('/me/editmedia.htm?flashId=' + flashId)
def handle(request, comm_id):
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect('/login.htm')
    
    community = models.Community.objects.select_related().get(id=comm_id)
    if myself.username != community.owner_username:
        return siteaction.render_to_response('me/showmessage.htm', {'msg_heading':'Error', 'msg_html':'Unauthorized access.'})

    if request.method == 'GET':
        action_result = ''
        if dataplus.dictGetVal(request.REQUEST, 'flashId'):
            action_result = dataplus.dictGetVal(statix.action_messages, dataplus.dictGetVal(request.REQUEST, 'flashId'), '')
            
        community.image_url = dataplus.getStaticUrl(community.image_size2_file_path)
        return siteaction.render_to_response('communities/editinfo.htm', 
                    {'community':community,
                     'action_result':action_result,
                     'myself':myself})
                    
    elif request.method == 'POST':
        comm_name = dataplus.dictGetSafeVal(request.REQUEST, 'name')
        comm_desc = dataplus.dictGetSafeVal(request.REQUEST, 'desc')
        if comm_name != community.name:
            result, errMsg = codejar_validation.validateCommunityName(comm_name)
            if not result:
                return siteaction.render_to_response('communities/editinfo.htm', 
                        {'community':community,
                         'myself':myself, 
                         'action_result':'Invalid Community Name. ' + errMsg,})
            
            if codejar_network.checkCommunityNameExists(comm_name):
                return siteaction.render_to_response('communities/editinfo.htm', 
                        {'community':community,
                         'myself':myself, 
                         'action_result':dataplus.dictGetVal(statix.action_messages, 'comm_name_exists', ''), })
            
        community.name = comm_name
        community.desc = comm_desc
        community.save()
            
        return HttpResponseRedirect('./?flashId=comm_settings_chnged')
def handle(request):
    q_id = dataplus.dictGetVal(request.REQUEST, 'qid', '0', string.atoi)
    if q_id == 0:
        return HttpResponseRedirect('/login.htm')
    question = get_object_or_404(models.ResumeQuestion, id=q_id)
    
    myself = siteaction.getLoggedInUser(request)
    if not myself or myself.id != question.receiver.id:
        return HttpResponseRedirect('/login.htm?' + urllib.urlencode(
                {'returnUrl':'/me/answerresumequestion.htm?qid=' + str(q_id)}))
    
        
    if question.receiver.id != myself.id:
        return siteaction.render_to_response('me/showmessage.htm', 
            {'myself':myself, 
            'msg_heading': 'Error',
            'msg_html': 'Access Denied.'})
    
    if request.method == 'GET':
        return siteaction.render_to_response('me/answerresumequestion.htm',
            {'myself':myself,
            'question':question,
            'is_public_checked':dataplus.conditionalValue(lambda: question.is_public == True, 'checked="checked"', '')})
            
    elif request.method == 'POST':
        question.answer = dataplus.dictGetSafeVal(request.REQUEST, 'answer')
        question.is_public = dataplus.dictGetVal(request.REQUEST, 'is_public')
        question.is_answered = True
        question.save()

        html_message = myself.name + ' has answered your question (' + question.question + ').<br />' + \
            '<strong>Answer: </strong> ' + question.answer
            
        text_message = myself.name + ' has answered your question (' + question.question + ').\r\n' + \
            'Answer: ' + question.answer
        
        subject = myself.name + ' has answered your question'
        def internalSender(rcvr_accounts):
            rcvr = rcvr_accounts[0]
            mailman.sendToInbox(myself.username, rcvr.username, subject, html_message, 'TM', 'H')
        
        def externalSender(rcvr_accounts):
            sender = '"' + myself.name + '" <' + myself.username + '*****@*****.**>'
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>'  for rcvr in rcvr_accounts]
            mailman.sendMail(sender, receivers, subject, html_message, 
                None, None, text_message, reply_to=myself.email)
        
        mailman.sendBySettings([question.sender], internalSender, externalSender, 'AnswerToResumeQuestion')
        
        return HttpResponseRedirect('/me/?flashId=rqa_saved')
Beispiel #8
0
def handle(request):   
    if request.method == 'GET':
        socialray_invite = dataplus.dictGetSafeVal(request.REQUEST,'inviteId','')
        comm_invite = dataplus.dictGetSafeVal(request.REQUEST,'commInviteId','')
        comm_friend_invite = dataplus.dictGetSafeVal(request.REQUEST,'commFriendInviteId','')
        invitation = ''
        if socialray_invite:
            invitation = 'inviteId=' + socialray_invite
        elif comm_invite:
            invitation = 'commInviteId=' + comm_invite
        elif comm_friend_invite:
            invitation = 'commFriendInviteId=' + comm_friend_invite
        
        countries = models.Country.objects.all().order_by('name')
        country_select_html = hotmetal.elemSelect([('Select', '')], countries,
            lambda x:x.name, lambda x:x.code, '', 'name="country" id="country" style="width:160px"')   
        
        return siteaction.render_to_response('me/signup.htm', 
            {'invitation':invitation,
            'cid':dataplus.getUniqueId(),
            'country_select_html':country_select_html})
    elif request.method == 'POST':
        result, response = validateRequest(request)
        if not result:
            return response
        
        username = dataplus.dictGetVal(request.REQUEST, 'username')
        if username.lower() in config.reserved_words or models.Account.objects.filter(username=username).count() > 0:
            return siteaction.render_to_response('me/signup.htm', 
                {'error_html': '<p class="error-note">Username already exists. Please choose another.</p>',
                'name':dataplus.dictGetVal(request.REQUEST, 'name'),
                'username':dataplus.dictGetVal(request.REQUEST, 'username'),
                'email':dataplus.dictGetVal(request.REQUEST, 'email'),
                'cid':dataplus.getUniqueId()})
        else:
            username = dataplus.dictGetVal(request.REQUEST,'username').lower()
            siteaction.createUser(username, dataplus.dictGetSafeVal(request.REQUEST, 'name'), 
                dataplus.dictGetSafeVal(request.REQUEST, 'password1'), dataplus.dictGetSafeVal(request.REQUEST, 'email'), 
                dataplus.dictGetSafeVal(request.REQUEST, 'country'), 'Software/IT', 0, dataplus.dictGetVal(request.REQUEST, 'invitation'))
            
            account = models.Account.objects.get(username=username)
            session_id = sessions_client.query('addNewSession', [account.username])
            if session_id:
                chat_settings = models.ChatSettings.objects.get(account=account)
                livewire_client.command('updateUserSession', [session_id, account.username, account.name, chat_settings.online_status, 
                    chat_settings.custom_message, chat_settings.invite_preference, chat_settings.ignore_list, 
                    dataplus.getStaticUrl(chat_settings.image_size1_file_path), dataplus.getStaticUrl(chat_settings.image_size2_file_path), 
                    dataplus.getStaticUrl(chat_settings.image_size3_file_path)])
    
            return siteaction.redirectWithCookie('createresume.htm', 'session_id', session_id)
Beispiel #9
0
def signupUser(request):
    result, response = validateRequest(request)
    if not result:  return response
        
    params = {}
    params['name'] = dataplus.dictGetSafeVal(request.REQUEST, 'name')
    params['username'] = dataplus.dictGetSafeVal(request.REQUEST, 'user-name')
    params['email'] = dataplus.dictGetSafeVal(request.REQUEST, 'email')
    params['password'] = dataplus.dictGetSafeVal(request.REQUEST, 'password1')
    params['country'] = dataplus.dictGetSafeVal(request.REQUEST, 'country')
    params['industry_category'] = dataplus.dictGetSafeVal(request.REQUEST, 'industry_category')
    params['experience'] = int(dataplus.dictGetSafeVal(request.REQUEST, 'experience'))
    request.session['signup-params'] = params
    
    return HttpResponseRedirect('idxcaptcha.htm')
def handle(request): 
    try:
        account = siteaction.getLoggedInAccount(request)
        if not account:
            return ajaxian.getFailureResp('not_logged_in')
        
        status = dataplus.dictGetSafeVal(request.REQUEST,'status','everyone')
        cs = models.ChatSettings.objects.get(account=account)
        cs.online_status = status
        cs.save()
        
        session_id = request.COOKIES['session_id']
        siteaction.updateLivewireData(session_id, account)
        
        return ajaxian.getSuccessResp('')
    except:
        return ajaxian.getFailureResp('unknown')
Beispiel #11
0
def sendMessage(request, session_id):
    try:
        chat_id = dataplus.dictGetVal(request.REQUEST, 'chatId', '')
        text = dataplus.dictGetSafeVal(request.REQUEST, 'text', '')
        receivers = dataplus.dictGetVal(request.REQUEST, 'receivers', '')
        last_message_id = dataplus.dictGetVal(request.REQUEST, 'lastMessageId','0')
        
        if not chat_id:
            return ajaxian.getFailureResp('error:invalid_chatId')
        if receivers:
            receivers = dataplus.listToString(receivers.split(','))
        data = livewire_client.query('getChatMessages', [session_id, chat_id, last_message_id])
        if data.startswith('error:'):
            return ajaxian.getFailureResp(data)
        data = cPickle.loads(data)
        result = livewire_client.command('sendMessage',[session_id, chat_id, text, receivers])
        if result.startswith('error:'):
            return ajaxian.getFailureResp(result)
        return ajaxian.getSuccessResp(data)
    except:
        return ajaxian.getFailureResp('error:unknown')
Beispiel #12
0
def saveSocialProfile(request, user):
    personal_desc = dataplus.dictGetSafeVal(request.REQUEST, 'personaldesc', '')
    
    user.personal_desc = personal_desc
    
    if request.FILES:
        img_save_success, error_code, img1, img2, img3, img4 = \
            studio.saveImage_x4_ByDate(request, 'user_' + user.username, 'photograph')
        if img_save_success:
            if user.image_file_path != img1:
                iolib.deleteFiles([user.image_file_path, user.image_size1_file_path, 
                    user.image_size2_file_path, user.image_size3_file_path])
                user.image_file_path = img1
                user.image_size1_file_path = img2
                user.image_size2_file_path = img3
                user.image_size3_file_path = img4
                
                chat_settings = models.ChatSettings.objects.get(account=user.account)
                chat_settings.image_size1_file_path = img2
                chat_settings.image_size2_file_path = img3
                chat_settings.image_size3_file_path = img4
                chat_settings.save()
        else:
            return img_save_success, error_code

    if not dataplus.isNullOrEmpty(user.personal_desc):
        user.hilite = dataplus.getPreviewText(personal_desc, 512)
        user.small_desc = dataplus.getPreviewText(personal_desc, 256)
    else:
        #if personal_desc is null AND resume_contents.text is ALSO null
        if dataplus.isNullOrEmpty(user.resume_contents.text):
            user.hilite = config.no_details_text
            user.small_desc = config.no_details_text
    if personal_desc:
        codejar_resume.updatePlainTextResume(user)
                
    user.last_updated_time = datetime.datetime.utcnow()
    user.save()
    
    return True, ''
Beispiel #13
0
def handle(request):  
    account = siteaction.getLoggedInAccount(request)
    if not account:
        return HttpResponseRedirect('/login.htm')
    
    #TODO: notify user about success, success_page will change
    logged_in_type = siteaction.getLoggedInAccountType(request)
    if logged_in_type == 'U':
        entry_page = 'me/changeemail.htm'
        success_page = '/me/editsettings.htm?flashId=email_chnged'
        error_page = 'me/showmessage.htm'
        myself = siteaction.getLoggedInUser(request)
    elif logged_in_type == 'R':
        entry_page = 'recruiters/changeemail.htm'    
        success_page = '/recruiters/'
        error_page = 'recruiters/showmessage.htm'
        myself = siteaction.getLoggedInRecruiter(request)
    
    if request.method == 'GET':
        return siteaction.render_to_response(entry_page, {'myself':myself})

    elif request.method == 'POST':
        #Password Check
        if (siteaction.validatePassword(myself.account.id, dataplus.dictGetVal(request.REQUEST, 'password'))):
            
            result, errMsg = codejar_validation.validateEmail(dataplus.dictGetVal(request.REQUEST,'email'))
            if not result:
                return siteaction.render_to_response(error_page, {'myself':myself, 'msg_heading':'Error', 'msg_html':'Invalid user input.'})
            
            email_address = dataplus.dictGetSafeVal(request.REQUEST, 'email')
            account.email = email_address
            account.save()
            myself.email = email_address
            myself.save()
            return HttpResponseRedirect(success_page)
        else:
            return siteaction.render_to_response(entry_page, 
                {'error_html': '<p class="error-note">Password was incorrect. Try again.</p>'})
def handle(request):
    try:
        logged_in_type = siteaction.getLoggedInAccountType(request)
        if logged_in_type == "U":
            myself = siteaction.getLoggedInUser(request)
        elif logged_in_type == "R":
            myself = siteaction.getLoggedInRecruiter(request)
        else:
            return ajaxian.getFailureResp("not_logged_in")

        quest_to_user = dataplus.dictGetVal(request.REQUEST, "questToUser")
        question_text = dataplus.dictGetSafeVal(request.REQUEST, "question")

        question = models.ResumeQuestion()
        question.sender = myself.account
        question.receiver = models.User.objects.get(username=quest_to_user)
        question.question = question_text
        question.answer = ""
        question.is_answered = False
        question.is_public = False
        question.sent_at = datetime.datetime.utcnow()
        question.save()

        html_message = (
            myself.name
            + ' wants to know more about your resume and has asked this question, <strong>"'
            + question_text
            + '"</strong><br /><br />You may want to <a href="'
            + config.server_base_url
            + "/me/answerresumequestion.htm?qid="
            + str(question.id)
            + '">Answer this question</a>'
        )

        text_message = (
            myself.name
            + ' wants to know more about your resume and has asked this question, "'
            + question_text
            + '"\r\n\r\nYou can answer this question by visiting this url: '
            + config.server_base_url
            + "/me/answerresumequestion.htm?qid="
            + str(question.id)
        )

        def internalSender(rcvr_accounts):
            mailman.sendToInbox(
                myself.username, rcvr_accounts[0].username, "A question for you!", html_message, "TM", "H"
            )

        def externalSender(rcvr_accounts):
            sender = '"' + myself.name + '" <' + myself.username + "*****@*****.**>"
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + ">" for rcvr in rcvr_accounts]
            mailman.sendMail(
                sender, receivers, "A question for you!", html_message, None, None, text_message, reply_to=myself.email
            )

        mailman.sendBySettings([question.receiver.account], internalSender, externalSender, "ResumeQuestion")

        return ajaxian.getSuccessResp("")
    except:
        return ajaxian.getFailureResp("unknown")
def handle(request, comm_id):
    community = models.Community.objects.get(id=comm_id)
    community.image_url = dataplus.getStaticUrl(community.image_size3_file_path)
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect("/login.htm")

    if community.members.filter(id=myself.id).count() == 0:
        return siteaction.render_to_response(
            "me/showmessage.htm", {"myself": myself, "msg_heading": "Error", "msg_html": "Access denied"}
        )

    action = dataplus.dictGetVal(request.REQUEST, "action")

    if request.method == "GET":
        action_result = ""
        if dataplus.dictGetVal(request.REQUEST, "flashId"):
            action_result = dataplus.dictGetVal(
                statix.action_messages, dataplus.dictGetVal(request.REQUEST, "flashId"), ""
            )

        return siteaction.render_to_response(
            "communities/invite.htm",
            {
                "community": community,
                "friend_count": myself.friends.count(),
                "friends_html": getFriendsTable(myself, community),
                "invite_more": (action == "invite_more"),
                "action_result": action_result,
                "myself": myself,
            },
        )

    elif request.method == "POST":
        if action == "external_invite":
            message = dataplus.dictGetSafeVal(request.REQUEST, "msgToMembers", "")
            add_to_friend_list = dataplus.dictGetVal(request.REQUEST, "add_to_friend_list", False, lambda x: True)
            has_valid_emails = False

            for i in range(1, 6):
                email = dataplus.dictGetVal(request.REQUEST, "email" + str(i), "").strip()
                success, error = codejar_validation.validateEmail(email)

                if success:
                    has_valid_emails = True

                    invitation = models.FriendInvitation(sent_by=myself, sent_to_email=email)
                    invitation.invite_random_key = dataplus.getUniqueId()
                    invitation.save()

                    comm_invite = models.CommunityInvitation(sent_by=myself, community=community)
                    comm_invite.invite_random_key = invitation.invite_random_key
                    comm_invite.save()

                    sender = '"' + myself.name + '" <' + myself.username + "*****@*****.**>"
                    subject = myself.name + " has invited you to join " + community.name + " - Socialray"
                    if add_to_friend_list:
                        accept_url = (
                            config.server_base_url
                            + "/me/acceptinvite.htm?commFriendInviteId="
                            + str(invitation.invite_random_key)
                        )
                    else:
                        accept_url = (
                            config.server_base_url
                            + "/me/acceptinvite.htm?commInviteId="
                            + str(invitation.invite_random_key)
                        )

                    html_message = (
                        '<p><a href="'
                        + config.server_base_url
                        + "/profiles/"
                        + myself.username
                        + '">'
                        + myself.name
                        + "</a>"
                        + " feels that you will be interested in joining the "
                        + community.name
                        + " Community in Socialray and has sent you the following message:</p>"
                        + "<p>"
                        + dataplus.replaceHtmlLineBreaks(message)
                        + "</p>"
                        + '<p>To accept this invitation and create an account, visit <a href="'
                        + accept_url
                        + '">'
                        + accept_url
                        + "</a> "
                        + "<br />Once you create your account, "
                        + myself.name
                        + " will be connected to you as a friend.</p>"
                        + "<p>Regards,<br />from Socialray</p>"
                    )

                    text_message = (
                        myself.name
                        + " feels that you will be interested in joining the "
                        + community.name
                        + " Community in Socialray and has sent you the following message:\r\n"
                        + message
                        + "\r\n\r\n"
                        + "To accept this invitation and create an account, visit - "
                        + accept_url
                        + " \r\n"
                        + "Once you create your account, "
                        + myself.name
                        + " will be connected to you as a friend.\r\n"
                        + "You can check "
                        + myself.name
                        + "'s profile at "
                        + config.server_base_url
                        + "/profiles/"
                        + myself.username
                        + "\r\n\r\n"
                        + "Regards,\r\n"
                        + "from Socialray\r\n\r\n"
                    )

                    mailman.sendMail(
                        sender, [email], subject, html_message, None, None, text_message, reply_to=myself.email
                    )
            if not has_valid_emails:
                return siteaction.render_to_response(
                    "communities/invite.htm",
                    {
                        "community": community,
                        "friend_count": myself.friends.count(),
                        "friends_html": getFriendsTable(myself, community),
                        "myself": myself,
                    },
                )

        elif action == "internal_invite":
            message = dataplus.dictGetSafeVal(request.REQUEST, "msgToFriends", "")
            friend_count = dataplus.dictGetVal(request.REQUEST, "friendCount", 0, string.atoi)

            has_selected_users = False
            for i in range(1, friend_count + 1):
                chk_id = dataplus.dictGetVal(request.REQUEST, "checkbox" + str(i))
                if chk_id:
                    user = models.User.objects.get(id=chk_id)
                    has_selected_users = True
                    sendCommunityInvitationToUser(community, user, myself, message)

            if not has_selected_users:
                return siteaction.render_to_response(
                    "communities/invite.htm",
                    {
                        "community": community,
                        "friend_count": myself.friends.count(),
                        "friends_html": getFriendsTable(myself, community),
                        "myself": myself,
                    },
                )

        if community.is_moderated:
            flash_id = "mod_comm_invites_sent"
        else:
            flash_id = "comm_invites_sent"

        return HttpResponseRedirect(
            "/communities/" + str(community.id) + "/invite.htm?flashId=" + flash_id + "&amp;action=invite_more"
        )
def handle(request):    
    if request.method == 'GET':
        #there cannot be get requests to this page.....
        return siteaction.render_to_response('showmessage.htm', 
            {'msg_heading': 'Error',
              'msg_html': 'Invalid URL'})
    
    elif request.method == 'POST':
        if (dataplus.dictGetVal(request.REQUEST,'action') == 'page2'):
            industry_cat = dataplus.dictGetVal(request.REQUEST,'industry_category')
            
            if not (dataplus.dictGetVal(request.REQUEST,'postedby') and dataplus.dictGetVal(request.REQUEST,'industry_category') \
                and dataplus.dictGetVal(request.REQUEST,'company')  and dataplus.dictGetVal(request.REQUEST,'location') \
                and dataplus.dictGetVal(request.REQUEST,'phone') and dataplus.dictGetVal(request.REQUEST,'email')):
                return siteaction.render_to_response('showmessage.htm', {'msg_heading':'Invalid request', \
                    'msg_html':'Required fields were not supplied. Please fill all the required fields and try again.'})
                    
            salary_ranges = codejar_resume.getSalaryRanges(dataplus.dictGetVal(request.REQUEST,'country'))
            salary_range_select_html = hotmetal.elemSelect([('Select', '0-0')], salary_ranges,
                lambda x:x[1], lambda x:x[0], '0-0', 'name="salary_range" id="salary_range" style="width:160px"')
            currency_code = models.Country.objects.get(code=dataplus.dictGetVal(request.REQUEST,'country')).currency_code
            
            return siteaction.render_to_response('recruiters/postjobsnow2.htm',
                {'postedby': dataplus.dictGetVal(request.REQUEST,'postedby'),
                 'industry_category': cgi.escape(dataplus.dictGetVal(request.REQUEST,'industry_category')),
                 'company': dataplus.dictGetVal(request.REQUEST,'company'),
                 'location': dataplus.dictGetVal(request.REQUEST,'location'),
                 'country': dataplus.dictGetVal(request.REQUEST,'country'),
                 'email': dataplus.dictGetVal(request.REQUEST,'email'),
                 'phone': dataplus.dictGetVal(request.REQUEST,'phone'),
                 'salary_range_select_html': salary_range_select_html,
                 'currency_code':currency_code,
                 'cid':dataplus.getUniqueId(),})

        elif (dataplus.dictGetVal(request.REQUEST,'action') == 'save'):
            if dataplus.dictGetVal(request.REQUEST,'captcha_text') != request.session['postjob_captcha_text']:
                return siteaction.render_to_response('recruiters/postjobsnow2.htm',
                    {'postedby': dataplus.dictGetVal(request.REQUEST,'postedby'),
                     'industry_category': cgi.escape(dataplus.dictGetVal(request.REQUEST,'industry_category')),
                     'company': dataplus.dictGetVal(request.REQUEST,'company'),
                     'location': dataplus.dictGetVal(request.REQUEST,'location'),
                     'country': dataplus.dictGetVal(request.REQUEST,'country'),
                     'email': dataplus.dictGetVal(request.REQUEST,'email'),
                     'phone': dataplus.dictGetVal(request.REQUEST,'phone'),
                     'designation': dataplus.dictGetVal(request.REQUEST,'designation'),
                     'jobdescription': dataplus.dictGetVal(request.REQUEST,'jobdescription'),
                     'location': dataplus.dictGetVal(request.REQUEST,'location'),
                     'exact_salary': dataplus.dictGetVal(request.REQUEST,'exact_salary'),
                     'mandatory_skills': dataplus.dictGetVal(request.REQUEST,'mandatory_skills'),
                     'desired_skills': dataplus.dictGetVal(request.REQUEST,'desired_skills'),
                     'title': dataplus.dictGetVal(request.REQUEST,'title'),
                     'error_html':'<p class="error-note">The captcha(verification) text entered doesn\'t match.</p>'})
            
            job_pos = models.JobPosition()
            job_pos.tag = 'name=' + dataplus.dictGetSafeVal(request.REQUEST, 'postedby') + ';'
            job_pos.company_name = dataplus.dictGetSafeVal(request.REQUEST, 'company')
                    
            industry_category = models.IndustryCategory.objects.get(name=dataplus.dictGetVal(request.REQUEST,'industry_category'))
            job_pos.industry_category = industry_category
            
            job_pos.designation = dataplus.dictGetSafeVal(request.REQUEST, 'designation')
            job_pos.job_description = dataplus.dictGetSafeVal(request.REQUEST, 'jobdescription','')
            job_pos.num_positions = 1 #one for now.
            job_pos.closing_date = config.max_date
            job_pos.location = dataplus.dictGetSafeVal(request.REQUEST, 'location')
            job_pos.country = dataplus.dictGetSafeVal(request.REQUEST, 'country')
            
            exact_salary = dataplus.dictGetVal(request.REQUEST,'exact_salary')
            if exact_salary:
                exact_salary = string.atoi(exact_salary)
                job_pos.min_compensation = exact_salary
                job_pos.max_compensation = exact_salary
            else:            
                #salary in the format 'min_salary-max_salary'
                #this string needs to be split into min and max
                sal = string.split(dataplus.dictGetVal(request.REQUEST,'salary_range'),'-')
                job_pos.min_compensation = string.atoi(sal[0])
                job_pos.max_compensation = string.atoi(sal[1])
            
            job_pos.min_exp_years = dataplus.dictGetVal(request.REQUEST,'min_exp_years',0)
            job_pos.mandatory_skills = dataplus.dictGetSafeVal(request.REQUEST, 'mandatory_skills')
            job_pos.desired_skills = dataplus.dictGetSafeVal(request.REQUEST, 'desired_skills')
            job_pos.educational_qualifications = dataplus.dictGetSafeVal(request.REQUEST,'edu_qualifications')
            job_pos.contact_email = dataplus.dictGetSafeVal(request.REQUEST,'email')
            job_pos.contact_phone = dataplus.dictGetSafeVal(request.REQUEST,'phone')
            if dataplus.dictGetVal(request.REQUEST,'title') != '':
                job_pos.title = dataplus.dictGetSafeVal(request.REQUEST,'title')
            else:
                job_pos.title = (job_pos.designation + ' - ' + job_pos.mandatory_skills + ' (' + str(job_pos.min_exp_years) + ' years)')[:30] + '...'
            
            job_pos.currency = config.default_currency
            job_pos.url = ''
            
            job_pos.save()
            
            return siteaction.render_to_response('showmessage.htm', 
                                    { 'msg_heading':'Success',
                                       'msg_html':'The job was added successfully. <a href="/recruiters/postjobsnow1.htm">Add Another</a>.'})
Beispiel #17
0
def handle(request):
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect('/login.htm')
    
    action = dataplus.dictGetVal(request.REQUEST, 'action')
    email_ids = []
    
    if request.method == 'GET':
        
        current_pane = dataplus.dictGetVal(request.REQUEST, 'current_pane')
        return siteaction.render_to_response('me/addfriends.htm', 
                {'invite_more': (action == 'invite_more'),
                'action_result': ('','Do you want to invite more people? <a href="' + config.server_base_url + '/me">Nope</a>')[action == 'invite_more'],
                'invite_by_search_box': ((not current_pane) or current_pane == 'invite_by_search'),
                'invite_by_email_box': (current_pane == 'email_invite'),
                'bulk_invite_box': (current_pane == 'bulk_invite'),
                'myself':myself })
    
    elif request.method == 'POST':
        has_valid_emails = False
        if action == 'email_invite':
            message = dataplus.dictGetSafeVal(request.REQUEST, 'msgToMembers', '')
            email_ids = dataplus.dictGetSafeVal(request.REQUEST, 'emailIds', '')
            add_to_friend_list = True
            
            if email_ids:
                email_ids = email_ids.split()
                if(len(email_ids) < 2): 
                    email_ids = email_ids[0].split(',')
                    if(len(email_ids) < 2): 
                        email_ids = email_ids[0].splitlines() 
                                        
                has_valid_emails = processEmails(email_ids, message, myself)                                                                                
                return HttpResponseRedirect('/me/addfriends.htm?action=invite_more&current_pane=email_invite') 
         
            if not has_valid_emails:
                return siteaction.render_to_response('me/addfriends.htm', 
                {'myself':myself ,
                'invite_by_email_invalid': 'Please enter valid emails'}) 
                
            return HttpResponseRedirect('/me/addfriends.htm?action=invite_more&current_pane=email_invite')
                   
        elif action == 'bulk_invite':
            message = dataplus.dictGetSafeVal(request.REQUEST, 'msgToFriends', '')
            file = request.FILES.getlist('csvEmailIds')[0]
            lines = file['content'].splitlines()
            if lines:            
                for line in lines:
                    for email_id in line.split(','):
                        email_ids.append(email_id.strip('"'))
                                       
                has_valid_emails = processEmails(email_ids, message, myself)
                            
            return HttpResponseRedirect('/me/addfriends.htm?action=invite_more&current_pane=bulk_invite')
            
        elif action == 'invite_by_search':
            keywords = dataplus.dictGetVal(request.REQUEST,'keywords')

            if dataplus.dictGetVal(request.REQUEST,'actionplus') == 'display':
                page = dataplus.dictGetVal(request.REQUEST,'page',0,string.atoi)
                
                pickled_match_list = dataplus.dictGetVal(request.REQUEST,'matches')
                match_list = cPickle.loads(str(pickled_match_list))
                
                start_num = page * config.user_matches_per_page
                end_num = ((page + 1) * config.user_matches_per_page)
                display_list = match_list[start_num:end_num]
                users_bulk_dict = models.User.objects.in_bulk(display_list)
                
                matching_users = dataplus.getOrderedList(users_bulk_dict, display_list)
                for user in matching_users:
                    user.image_url = dataplus.getStaticUrl(user.image_size2_file_path)
                
                message = 'Showing ' + str(start_num + 1) + ' - ' + str(start_num + len(matching_users)) + ' of ' + str(len(match_list)) + ' matches.'
                num_pages = ((len(match_list)-1)/config.user_matches_per_page) + 1
                
                return siteaction.render_to_response('me/addfriends.htm', 
                    {'showing_search_results': True,
                     'myself': myself,
                     'message': message,
                     'matching_users': matching_users,
                     'matches': cgi.escape(pickled_match_list),
                     'keywords': cgi.escape(keywords, True),
                     'page_links_html': getPageLinksHtml(num_pages, page),
                     'invite_by_search_box': True,
                    })
            else:
                keywords = keywords.strip()
                if not keywords:
                    return siteaction.render_to_response('me/addfriends.htm', 
                        {'showing_search_results': True,
                         'myself': myself,
                         'message': 'Please enter a valid search query.',
                         'invite_by_search_box': True,})
                    
                matching_userids = searchpeople.getMatches(keywords)
                if matching_userids:
                    display_list = matching_userids[:config.user_matches_per_page]
                    users_bulk_dict = models.User.objects.in_bulk(display_list)
                    matching_users = dataplus.getOrderedList(users_bulk_dict, display_list)
                    for user in matching_users:
                        user.image_url = dataplus.getStaticUrl(user.image_size2_file_path)
                        
                    message = 'Showing 1 - ' + str(len(matching_users)) + ' of ' + str(len(matching_userids)) + ' matches.'
                    
                    num_pages = ((len(matching_userids)-1)/config.user_matches_per_page) + 1
                    
                    return siteaction.render_to_response('me/addfriends.htm', 
                        {'matching_users': matching_users,
                         'keywords': cgi.escape(keywords, True),
                         'myself': myself,
                         'message':message,
                         'matches': cgi.escape(cPickle.dumps(matching_userids)),
                         'page_links_html': getPageLinksHtml(num_pages, 0),
                         'showing_search_results': True,
                         'invite_by_search_box': True,})
                else:
                    return siteaction.render_to_response('me/addfriends.htm', 
                        {'matching_users': None,
                         'keywords': cgi.escape(keywords, True),
                         'message': 'Your search did not return any results.',
                         'myself': myself,
                         'showing_search_results': True,
                         'invite_by_search_box': True,})           
def handle(request):
    myself = siteaction.getLoggedInUser(request)
    if not myself:
        return HttpResponseRedirect('/login.htm')
    
    user_settings = models.UserSettings.objects.get(user=myself)
    chat_settings = models.ChatSettings.objects.get(account=myself.account)
        
    if request.method == 'GET':
        action_result = ''
        if dataplus.dictGetVal(request.REQUEST, 'flashId'):
            action_result = dataplus.dictGetVal(statix.action_messages, dataplus.dictGetVal(request.REQUEST, 'flashId'), '')
        
        online_status_select_html = hotmetal.elemSelect([('Everyone', 'everyone'), ('Friends only', 'friends'), ('Nobody', 'nobody')], [],
            lambda x:x[0], lambda x:x[1], chat_settings.online_status, 'name="online_status" id="online_status" style="width:160px;"')
        
        invite_preference_select_html = hotmetal.elemSelect([('Everyone', 'everyone'), ('Friends only', 'friends'), ('Nobody', 'nobody')], [],
            lambda x:x[0], lambda x:x[1], chat_settings.invite_preference, 'name="invite_preference" id="invite_preference" style="width:160px;"')
            
        ignored_usernames = chat_settings.ignore_list.split(',')
        ignored_accounts = []
        for username in ignored_usernames:
            try:
                ignored_accounts.append(models.Account.objects.get(username=username))
            except:
                pass
        
        ignore_list_select_html = hotmetal.elemSelect([], ignored_accounts,
            lambda x:x.name + ' (' + x.username + ')', lambda x:x.username, '', 'name="ignore_list_select" id="ignore_list_select" size="8" multiple="multiple" style="width:240px;"')
            
        skype_username = ''
        yahoo_username = ''
        for msnger in models.WebMessenger.objects.filter(account=myself.account):
            if msnger.provider == 'skype':  skype_username = msnger.username
            elif msnger.provider == 'yahoo':  yahoo_username = msnger.username
        
        return siteaction.render_to_response('me/editconnectsettings.htm',
        {'online_status_select_html': online_status_select_html,
         'custom_message': chat_settings.custom_message,
         'invite_preference_select_html': invite_preference_select_html, 
         'ignore_list_select_html': ignore_list_select_html, 
         'phone': dataplus.replaceNull(myself.phone, ''),
         'enable_voip_dial': dataplus.conditionalValue(lambda: user_settings.enable_voip_dial == True, 'checked="checked"', ''),
         'skype_username':skype_username,
         'yahoo_username':yahoo_username,
         'blog_url': dataplus.replaceNull(myself.blog_url, ''),
         'action_result':action_result,
         'myself': myself})
        
    elif request.method == 'POST':            
        action = dataplus.dictGetVal(request.REQUEST, 'action')
        if action == 'save_chat_settings':
            chat_settings.online_status = dataplus.dictGetSafeVal(request.REQUEST, 'online_status')
            chat_settings.custom_message = dataplus.dictGetSafeVal(request.REQUEST, 'custom_message')
            chat_settings.invite_preference = dataplus.dictGetSafeVal(request.REQUEST, 'invite_preference')
            chat_settings.ignore_list = dataplus.dictGetSafeVal(request.REQUEST, 'ignore_list')
            chat_settings.save()
        
            session_id = request.COOKIES['session_id']
            siteaction.updateLivewireData(session_id, myself.account)
        
        elif action == 'save_telephone_settings':
            myself.phone = dataplus.dictGetSafeVal(request.REQUEST, 'phone')
            myself.save()
            user_settings.enable_voip_dial = dataplus.dictGetVal(request.REQUEST, 'enable_voip_dial', False, lambda x:True)
            user_settings.save()
        
        elif action == 'save_messengers_settings':
            for msnger in models.WebMessenger.objects.filter(account=myself.account):
                msnger.delete()
                
            if dataplus.dictGetSafeVal(request.REQUEST, 'skype_username'):
                skype_profile = models.WebMessenger(provider='skype')
                skype_profile.account=myself.account
                skype_profile.username = dataplus.dictGetSafeVal(request.REQUEST, 'skype_username')
                skype_profile.save()
            
            if dataplus.dictGetSafeVal(request.REQUEST, 'yahoo_username'):
                #remove '@yahoo.com' if its there
                yahoo_username = dataplus.dictGetSafeVal(request.REQUEST, 'yahoo_username').partition('@')[0]
                yahoo_profile = models.WebMessenger(provider='yahoo')
                yahoo_profile.account=myself.account
                yahoo_profile.username = yahoo_username
                yahoo_profile.save()
        
        elif action == 'save_blog_settings':
            myself.blog_url = dataplus.dictGetSafeVal(request.REQUEST, 'blog_url')
            if myself.blog_url and not myself.blog_url.lower().startswith('http://'):
                myself.blog_url = 'http://' + myself.blog_url
            myself.save()
            
        return HttpResponseRedirect('/me/editconnectsettings.htm?flashId=connectset_saved')
def handle(request): 
    try:
        myself = siteaction.getLoggedInUser(request)
        if not myself:
            return ajaxian.getFailureResp('not_logged_in')
        
        comm_id = dataplus.dictGetVal(request.REQUEST, 'communityId')
        community = models.Community.objects.get(id=comm_id)
        
        if community.members.filter(id=myself.id):
            return ajaxian.getFailureResp('already_member')

        elif not community.is_moderated:            
            myself.communities.add(community)
            myself.save()
            return ajaxian.getSuccessResp('joined_community')
                
        else:
            join_reqs = community.join_requests.filter(sent_by__id=myself.id)
            if join_reqs.count() > 0:
                return ajaxian.getFailureResp('request_pending')            
            
            if dataplus.dictGetVal(request.REQUEST, 'message', '') == '':
                return ajaxian.getFailureResp('community_moderated')
            
            message_to_admin = dataplus.dictGetSafeVal(request.REQUEST, 'message','')
            
            join_req = models.CommunityJoinRequest()
            join_req.sent_by = myself
            join_req.community = community
            join_req.sent_on = datetime.datetime.utcnow()
            join_req.msg_to_admin = message_to_admin
            join_req.save()
            
            msg_to_admin_html = '<p><a href="' + config.server_base_url + '/profiles/' + myself.username + '">' + myself.name + '</a>' + \
                ' wants to join ' + community.name + ' and has sent you a message:<br />' + \
                dataplus.replaceHtmlLineBreaks(message_to_admin) + '</p>' + \
                '<p>To allow/deny membership to this user , <a href="/me/approvecommjoinreq.htm?reqId=' + \
                str(join_req.id) + '">Click Here</a></p>' 
            
            msg_to_admin_text = myself.name + ' wants to join ' + community.name + ' and has sent you a message:\r\n' + \
                message_to_admin + '\r\n\r\nVisit ' + config.server_base_url + '/me/approvecommjoinreq.htm?reqId=' + str(join_req.id) + \
                ' to allow/deny membership to this user.\r\n\r\n'   
            
            def internalSender(rcvr_accounts):
                mailman.sendToInbox(myself.username, rcvr_accounts[0].username, 'Request to join ' + community.name, msg_to_admin_html, 'TM', 'H')
            
            def externalSender(rcvr_accounts):    
                sender = '"' + myself.name + '" <' + myself.username + '*****@*****.**>'
                receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>'  for rcvr in rcvr_accounts]                
                ext_msg_to_admin_html = msg_to_admin_html + \
                    '<br /><br /><br /><br /><br />' + \
                    'If you don\'t want to receive notification emails, change your Account Settings ' + \
                    '<a href="' + config.server_base_url + '/me/editsettings.htm">here</a>'                
                ext_msg_to_admin_text = msg_to_admin_text + \
                    '\r\n\r\n\r\n\r\n\r\n' + \
                    'If you don\'t want to receive notification emails, change your Account Settings here\r\n' + \
                    config.server_base_url + '/me/editsettings.htm'                                
                mailman.sendMail(sender, receivers, 'Request to join ' + community.name, ext_msg_to_admin_html, 
                    None, None, ext_msg_to_admin_text, reply_to=myself.email)

            admin_account = models.Account.objects.get(username=community.owner_username)
            mailman.sendBySettings([admin_account], internalSender, externalSender, 'SocialrayAlert')
            
            return ajaxian.getSuccessResp('request_sent')
        
    except:
        return ajaxian.getFailureResp('unknown')
def handle(request):
    myself = siteaction.getLoggedInUser(request)    
    if not myself:
        return HttpResponseRedirect('/login.htm')
    
    rcvr = rcvr_comm = None    
    rcvr_id = dataplus.dictGetVal(request.REQUEST, 'rcvrId', 0, string.atoi)
    rcvr_type = dataplus.dictGetVal(request.REQUEST,'rcvrType')
    
    if rcvr_type == 'u':
        rcvr = dataplus.returnIfExists(models.User.objects.filter(id=rcvr_id))
        if not rcvr:
            return  siteaction.render_to_response('me/showmessage.htm', 
                                {'myself':myself, 'msg_heading':'Error', 'msg_html':'Invalid Request'})
        receivers =  [rcvr]
    elif rcvr_type == 'c':
        rcvr_comm = dataplus.returnIfExists(models.Community.objects.filter(id=rcvr_id))
        if not rcvr_comm:
            return  siteaction.render_to_response('me/showmessage.htm', 
                                {'myself':myself, 'msg_heading':'Error', 'msg_html':'Invalid Request'})
    
    if request.method == 'GET':
        if rcvr:
            receiver_html = '<a href="' + config.profiles_url + '/' + rcvr.username + '" >' + rcvr.name + '</a>'
        elif rcvr_comm:
            receiver_html = 'Members of <a href="' + config.communities_url + '/' + str(rcvr_comm.id) + '" >' + rcvr_comm.name + '</a>' 
        
        experience_select_html = hotmetal.elemSelect([('Select', '-1')], range(0,30),
            lambda x:x, lambda x:x, '', 'name="experience" id="experience" style="width:80px"')
        
        industry_categories_select_html = hotmetal.elemSelect([('Select', '-1')], models.IndustryCategory.objects.all().order_by('name'),
            lambda x:x.name, lambda x:x.name, '', 'name="industry_category" id="industry_category" style="width:180px"')
            
        old_referrals = myself.posted_referrals.order_by('-created_at')[:20]
        old_referrals_select_html = hotmetal.elemSelect([('Select', '0')], old_referrals,
            lambda x:x.subject + ' (' + dataplus.getStrDate(x.created_at) + ')', lambda x:x.id, '', 'name="old_referral" id="old_referral" style="width:280px;" onchange="resetReferral();"')
            
        return siteaction.render_to_response('me/sendjobreferral.htm',
            {'myself': myself,
            'rcvrId':rcvr_id,
            'rcvrType':rcvr_type,
            'receiver_html':receiver_html,
            'has_old_referrals': (old_referrals.count() > 0),
            'old_referrals_select_html':old_referrals_select_html,
            'experience_select_html':experience_select_html,
            'sending_to_user': (rcvr_type == 'u'),
            'industry_categories_select_html':industry_categories_select_html,})
            
    elif request.method == 'POST':
        job_ref_id = dataplus.dictGetVal(request.REQUEST, 'referral_id', 0, string.atoi)
        if job_ref_id > 0:
            job_ref = models.JobReferral.objects.get(id=job_ref_id)
        else:
            job_ref = models.JobReferral()
            job_ref.sender = myself        
            if rcvr:
                receivers = [rcvr]
                job_ref.industry_category = rcvr.industry_category
                if rcvr.working_since:
                    job_ref.min_experience_years = (datetime.datetime.utcnow() - rcvr.working_since).days/365
            else:
                receivers = [x for x in rcvr_comm.members.all() if x.username != myself.username]
                job_ref.industry_category = models.IndustryCategory.objects.get(name=dataplus.dictGetVal(request.REQUEST, 'industry_category'))
                job_ref.min_experience_years = dataplus.dictGetVal(request.REQUEST, 'experience', 0, string.atoi)
                
            job_ref.subject = dataplus.dictGetSafeVal(request.REQUEST, 'subject')
            job_ref.reply_to_email = dataplus.dictGetSafeVal(request.REQUEST, 'reply_to')
            job_ref.text = dataplus.dictGetSafeVal(request.REQUEST, 'text')
            job_ref.save()
        
        for receiver in receivers:
            job_ref.receivers.add(receiver)
        
        html_message = dataplus.replaceHtmlLineBreaks(job_ref.text) + '<p><a href="' + config.server_base_url + '/me/viewreferral.htm?id=' + str(job_ref.id) + '">Forward your resume</a></p>'
        text_message = job_ref.text + '\r\n Visit ' + config.server_base_url + '/me/viewreferral.htm?id=' + str(job_ref.id) + ' to forward your resume.\r\n\r\n'
        
        subject = 'Job Referral: ' + job_ref.subject
        def internalSender(rcvr_accounts):
            mailman.sendMessage(myself.username, [rcvr.username for rcvr in rcvr_accounts], subject, html_message)
            
        def externalSender(rcvr_accounts):
            sender = '"' + myself.name + '" <' + myself.username + '*****@*****.**>'
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>' for rcvr in rcvr_accounts]
            ext_html_message = html_message + \
                '<br /><br /><br /><br /><br />' + \
                'If you don\'t want to receive notification emails, change your Account Settings ' + \
                '<a href="' + config.server_base_url + '/me/editsettings.htm">here</a>'                
            ext_text_message = text_message + \
                '\r\n\r\n\r\n\r\n\r\n' + \
                'If you don\'t want to receive notification emails, change your Account Settings here\r\n' + \
                config.server_base_url + '/me/editsettings.htm'
            mailman.sendMail(sender, receivers, subject, ext_html_message, None, None, ext_text_message, reply_to=myself.email)
        
        mailman.sendBySettings([rcvr.account for rcvr in receivers], internalSender, externalSender, 'JobReferral')
        
        return HttpResponseRedirect('/me/?flashId=jobref_sent')
def handle(request):
    testimonial_id = dataplus.dictGetVal(request.REQUEST,'testimonialId')
    test_req = dataplus.returnIfExists(models.TestimonialRequest.objects.filter(req_random_key=testimonial_id))
    if test_req is None:
        return siteaction.render_to_response('me/showmessage.htm',
            { 'msg_heading':'Error', 'msg_html':'This testimonial request does not exist.' })
    
    if request.method == 'GET':       
        return siteaction.render_to_response('me/writetestimonial.htm',
            {'from_name':test_req.sent_to_name,
             'to_name':test_req.sent_by.name})
            
    elif request.method == 'POST':                
        testimonial = models.Testimonial()
        testimonial.written_by = dataplus.dictGetSafeVal(request.REQUEST, 'name')
        testimonial.written_for = test_req.sent_by
        testimonial.text = dataplus.dictGetSafeVal(request.REQUEST, 'body')
        testimonial.designation = dataplus.dictGetSafeVal(request.REQUEST, 'designation')
        testimonial.company = dataplus.dictGetSafeVal(request.REQUEST, 'company')
        testimonial.relationship = dataplus.dictGetSafeVal(request.REQUEST, 'relationship')
        testimonial.written_on = datetime.datetime.utcnow()
        testimonial.writer_email = test_req.sent_to_email
        testimonial.save()
        
        #we need to delete the test-request since it should not be re-used
        test_req.delete()
        

        html_message = '<p>You can see the testimonial ' + testimonial.written_by + ' has written on ' + \
            '<a href="' + config.server_base_url + '/profiles/' +  testimonial.written_for.username + '">your profile</a>.</p>' + \
            '<p>Regards,<br />Socialray</p>'
            
        text_message = 'To see the testimonial ' + testimonial.written_by + ' has written, you can visit your profile at ' + \
            config.server_base_url + '/profiles/' +  testimonial.written_for.username + '.\r\n' + \
            'Regards,\r\nSocialray\r\n\r\n'
        
        subject = testimonial.written_by + ' has written a testimonial'
        def internalSender(rcvr_accounts):
            mailman.sendToInbox(None, rcvr_accounts[0].username, subject, html_message, 'SA', 'H')
        
        def externalSender(rcvr_accounts):
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>'  for rcvr in rcvr_accounts]
            ext_html_message = html_message + \
                '<br /><br /><br /><br /><br />' + \
                'If you don\'t want to receive notification emails, change your Account Settings ' + \
                '<a href="' + config.server_base_url + '/me/editsettings.htm">here</a>'                
            ext_text_message = text_message + \
                '\r\n\r\n\r\n\r\n\r\n' + \
                'If you don\'t want to receive notification emails, change your Account Settings here\r\n' + \
                config.server_base_url + '/me/editsettings.htm'
            mailman.sendOneWayMail(config.system_email, receivers, subject, ext_html_message, 
                None, None, ext_text_message)
        
        mailman.sendBySettings([testimonial.written_for.account], internalSender, externalSender, 'SocialrayAlert')
        
        myself = siteaction.getLoggedInUser(request)
        if myself:
            return HttpResponseRedirect('/me/?flashId=test_added')
        else:
            return siteaction.render_to_response('me/showmessage.htm',
            { 'msg_heading':'Testimonial Added', 
              'msg_html': '<p>Thanks for adding a testimonial.</p>' + \
              '<p><strong>Have you joined Socialray?</strong><br />Socialray is a Professional Networking and Jobs site. ' + \
              'But There is a lot more to Socialray than just being a place where people post their resumes and ' + \
              'hunt for jobs. You can\'t call Socialray a regular Social Networking site either.</p>' + \
              '<p>We invite you to <a href="' + config.server_base_url + '/me/signup.htm">Join us</a>.</p>' + \
              '<p>To find out more, you can start with the <a href="' + config.server_base_url + '">Home Page</a>.</p>'            
            })