Advertisement
Guest User

Untitled

a guest
Apr 10th, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.38 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # coding=utf-8
  3.  
  4. import cgitb; cgitb.enable()
  5. import cgi, re, os, sys, socket, datetime, pymysql, locale, random, subprocess
  6. from datetime import datetime, timedelta
  7. from http import cookies
  8.  
  9.  
  10. # get some enviromental VALUES
  11. locale.setlocale(locale.LC_ALL, 'el_GR')
  12. form = cgi.FieldStorage()
  13.  
  14. htmlpage = form.getvalue('htmlpage')
  15. page = form.getvalue('page')
  16.  
  17. # detect how 'index.html' is called and validate variables 'htmlpage' & 'page'
  18. if page and os.path.isfile( '/home/nikos/www/cgi-bin/' + page ):
  19. page = page
  20. elif form.getvalue('show') and os.path.isfile( htmlpage ):
  21. page = htmlpage.replace( '/home/nikos/public_html/', '' )
  22. else:
  23. page = 'index.html'
  24.  
  25. FROM = form.getvalue('from')
  26. MESSAGE = form.getvalue('message')
  27. userform = form.getvalue('userform')
  28.  
  29. try:
  30. host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0]
  31. except KeyError:
  32. host = 'Not Available'
  33. date = ( datetime.utcnow() + timedelta(hours=2) ).strftime( '%y-%m-%d %H:%M:%S' )
  34. userinfo = os.environ['HTTP_USER_AGENT']
  35.  
  36.  
  37. # identification of user browser
  38. # ==============================
  39. browser = userinfo.lower()
  40. if 'chrome' in browser:
  41. browser = 'Chrome'
  42. elif 'firefox' in browser:
  43. browser = 'Firefox'
  44. elif 'opera' in browser:
  45. browser = 'Opera'
  46. elif 'safari' in browser:
  47. browser = 'Safari'
  48. elif 'msie' in browser:
  49. browser = 'Explorer'
  50. else:
  51. browser = 'Unknown Browser'
  52.  
  53. # identification of user OS
  54. # ==============================
  55. useros = userinfo.lower()
  56. if 'windows' in useros:
  57. useros = 'Windows'
  58. elif 'mac' in useros:
  59. useros = 'MacOS'
  60. elif 'linux' in useros:
  61. useros = 'Linux'
  62. elif 'unix' in useros:
  63. useros = 'Unix'
  64. elif 'bsd' in useros:
  65. useros = 'FreeBSD'
  66. else:
  67. useros = 'Unknown OS'
  68.  
  69.  
  70. # initialize cookie
  71. cookie = cookies.SimpleCookie( os.environ.get('HTTP_COOKIE') )
  72. cookie.load( cookie )
  73. nikos = cookie.get('nikos')
  74.  
  75. # connect to database
  76. con = pymysql.connect( db = 'metrites', host = 'localhost', user = 'nikos', passwd = 'somepassword', init_command='SET NAMES UTF8' )
  77. cur = con.cursor()
  78.  
  79. print ( "Content-type: text/html; charset=utf-8\n" )
  80.  
  81.  
  82. # =================================================================================================================
  83. # if extra string is attached to the URL is 'stats' then show statistics for all HTML pages and exit
  84. # =================================================================================================================
  85. if form.getvalue('show') == 'stats':
  86.  
  87. print(''' <center><h2><font color=lime> LOG </font> όλων των <font color=red> HTML </font> σελίδων</h2><br>
  88. <table border=5 cellpadding=5 bgcolor=black>
  89. <th><font color=orange size=5> Σελίδα </th> <th><font color=orange size=5> Επισκέψεις </th>
  90. ''')
  91.  
  92. try:
  93. cur.execute( '''SELECT url, hits FROM counters ORDER BY hits DESC''' )
  94.  
  95. data = cur.fetchall()
  96. for row in data:
  97. (url, hits) = row
  98.  
  99. print( "<tr><td><center><a href='http://superhost.gr/?show=log&page=%s'><font color=tomato size=5> %s </a></td>" ) % (url, url)
  100. print( "<td><center><font color=cyan size=5> %s </a></td></tr>" ) % (hits)
  101. except pymysql.ProgrammingError as e:
  102. print( repr(e) )
  103.  
  104. sys.exit(0)
  105.  
  106.  
  107. # =================================================================================================================
  108. # if extra string is attached to the URL is 'log' then show explicit page log and exit
  109. # =================================================================================================================
  110. if form.getvalue('show') == 'log':
  111.  
  112. cur.execute('''SELECT hits FROM counters WHERE url = "?"''', (page,) )
  113. data = cur.fetchone() #URL is unique, so should only be one
  114.  
  115. print(''' <center><h2> <font color=lime> LOG </font> της σελιδας <font color=red> %s </font> => <font color=magenta> %s </font> </h2><br>
  116. <table border=5 cellpadding=5 bgcolor=blue>
  117. <th><font color=yellow> Επισκέπτης </th> <th><font color=yellow> Λειτουργικό </th> <th><font color=yellow> Πλοηγός </th> <th><font color=yellow> Επανάληψη </th> <th><font color=yellow> Ημερομηνία </th>
  118. ''') % (page, data[0])
  119.  
  120. try:
  121. cur.execute( '''SELECT host, userOS, browser, hits, lastvisit FROM visitors
  122. WHERE counterID = (SELECT ID FROM counters WHERE url = "?") ORDER BY lastvisit DESC''', (page,) )
  123.  
  124. data = cur.fetchall()
  125. for row in data:
  126. (host, userOS, hits, browser, lastvisit) = row
  127. lastvisit = lastvisit.strftime('%A %e %b, %H:%M').encode('utf8')
  128.  
  129. print( "<tr>" )
  130. for item in (host, userOS, hits, browser, lastvisit):
  131. print( "<td><center><b><font color=white> %s </td>" ) % item
  132. except pymysql.ProgrammingError as e:
  133. print( repr(e) )
  134.  
  135. sys.exit(0)
  136.  
  137.  
  138. # =================================================================================================================
  139. # if html form is submitted then send user mail
  140. # =================================================================================================================
  141. if( userform ):
  142.  
  143. if (FROM is None) or (MESSAGE is None) or ('@' not in FROM) or ('Γράψε μου εδώ το σχόλιο σου!' in MESSAGE):
  144. print( "<h2><font color=red>Συμπλήρωσε σωστά το mail σου και δώσε το σχολιασμό σου!</font></h2>" )
  145. else:
  146. sp = subprocess.Popen(['mail', '-f', FROM, '-s', 'Πιθανός Πελάτης', 'support@superhost.gr'], stdin=subprocess.PIPE)
  147. sp.communicate(MESSAGE)
  148. res = sp.wait()
  149. if res:
  150. print( "<h2><font color=lime>Ευχαριστώ πολύ για το ενδιαφέρον! Θα επικοινωνήσω μαζί σου άμεσα :-)</font></h2>" )
  151. else:
  152. print( "<h2><font color=red>Δυστυχώς δεν μπόρεσε να αποσταλεί το e-mail :-(" )
  153.  
  154. sys.exit(0)
  155.  
  156.  
  157. # =================================================================================================================
  158. # DATABASE INSERTS - do not increment the counter if a Cookie is set to the visitors browser already
  159. # =================================================================================================================
  160. if( ( not nikos ) and ( re.search( r'(msn|ovh|yandex|13448|kimsufi|corbina|spider|google|crawl|wowrack)', host ) is None ) ):
  161.  
  162. try:
  163. #find the needed counter for the page URL
  164. cur.execute('''SELECT ID FROM counters WHERE url = "?"''', (page,) )
  165. data = cur.fetchone() #URL is unique, so should only be one
  166.  
  167. if not data:
  168. #first time for page; primary key is automatic, hit is defaulted
  169. cur.execute('''INSERT INTO counters (url) VALUES ("?")''', (page,) )
  170. cID = cur.lastrowid #get the primary key value of the new record
  171. else:
  172. #found the page, save primary key and use it to issue hit UPDATE
  173. cID = data[0]
  174. cur.execute('''UPDATE counters SET hits = hits + 1 WHERE ID = "?"''', (cID,) )
  175.  
  176. #find the visitor record for the (saved) cID and current host
  177. cur.execute('''SELECT * FROM visitors WHERE counterID = "?" and host = "?"''', (cID, host) )
  178. data = cur.fetchone() #cID&host are unique
  179.  
  180. if not data:
  181. #first time for this host on this page, create new record
  182. cur.execute('''INSERT INTO visitors (counterID, host, userOS, browser, lastvisit) VALUES ("?", "?", "?", "?", "?")''', (cID, host, useros, browser, date) )
  183. else:
  184. #found the page, save its primary key for later use
  185. vID = data[0]
  186. #UPDATE record using retrieved vID
  187. cur.execute('''UPDATE visitors SET userOS = "?", browser = "?", hits = hits + 1, lastvisit = "?"
  188. WHERE counterID = "?" and host = "?"''', (useros, browser, date, vID, host) )
  189.  
  190. con.commit() #if we made it here, the transaction is complete
  191.  
  192. except pymysql.ProgrammingError as e:
  193. con.rollback() #something failed, rollback the entire transaction
  194. print( repr(e) )
  195.  
  196.  
  197. # =================================================================================================================
  198. # return general counter, render html page and print or invoke a python script
  199. # =================================================================================================================
  200. cur.execute('''SELECT hits FROM counters WHERE url = "?"''', (page,) )
  201. data = cur.fetchone()
  202.  
  203. # pick a random mp3 from the the music directory
  204. quote = random.choice( list( open( "/home/nikos/www/data/private/quotes.txt", encoding="utf-8" ) ) )
  205. # pick a random line from the quote text file
  206. music = random.choice( os.listdir( "/home/nikos/www/data/private/music" ) )
  207.  
  208.  
  209. if cur.rowcount:
  210. if page.endswith('.html'):
  211. f = open( "/home/nikos/www/" + page, encoding="utf-8" )
  212. htmldata = f.read()
  213. htmldata = htmldata % (quote, music)
  214.  
  215. counter = ''' <center>
  216. <a href="mailto:support@superhost.gr"> <img src="/data/images/mail.png"></a>
  217. <table border=2 cellpadding=2 bgcolor=black>
  218. <td><font color=lime>Αριθμός Επισκεπτών</td>
  219. <td><a href="http://superhost.gr/?show=log&page=%s"><font color=yellow> %d </td>
  220. </table><br>
  221. ''' % (page, data[0])
  222.  
  223. template = htmldata + counter
  224. print( template )
  225. elif page.endswith('.py'):
  226. print( '''<meta http-equiv="REFRESH" content="0;/cgi-bin/%s">''' ) % page
  227. else:
  228. print( "Δεν μας θυμήθηκε κανείς αφεντικό !!! Της λησμονιάς το νερό ήπιαν φαίνεται !!!" )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement