viewgit/index.php:465 Only variables should be passed by reference [2048]

viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4.  
  5. import random
  6. import urllib2
  7. import mutex
  8. import threading
  9. import re, time
  10. from optparse import OptionParser
  11.  
  12. default_page = "http://poisson.phc.unipi.it"
  13.  
  14. __author__ = "Leonardo Robol <leo@robol.it>"
  15.  
  16. mtx_url_dict = mutex.mutex()
  17.  
  18. size = 1000
  19. url_dict = {}
  20. url_counter = range(size)
  21.  
  22. max_steps = 5
  23.  
  24. debug = False
  25. outfile = "connections.txt"
  26.  
  27.  
  28. def get_links(page):
  29. """Restituisce una lista con i link
  30. presenti nella pagina data, in forma canonica"""
  31. content, real_url = get_content(page.url)
  32.  
  33. if(content == -1):
  34. return -1
  35.  
  36. links = re.findall(r"<a href=\"(\S*)\"[^>]*>",content)
  37. ret = []
  38. for link in links:
  39. # Espando il link in modo da (speriamo!)
  40. # garantire l'unicità
  41. ret.append(expand_url(real_url, link))
  42.  
  43. return ret
  44.  
  45.  
  46. def expand_url(parent, url):
  47. """Questa funzione prende l'url della pagina parent
  48. e l'url del link e dà all'url del link una forma unica
  49. e canonica, del tipo
  50.  
  51. http://www.example.com/pagina
  52. http://www.example.com/pagina.html
  53. """
  54.  
  55. ## Controllo che l'url non cominci con un punto
  56. ## nel qual caso cerchiamo di rimediare subito,
  57. ## ma non cadiamo nel tranello di ignorare i ..
  58. if url[0] == ".":
  59. if len(url) == 1:
  60. url = parent
  61.  
  62. else:
  63. if(url[1] != "."):
  64. url = url[1:]
  65.  
  66. ## Se all'inizio dell'url c'è uno slash non ci serve tutto
  67. ## il parent, ma solo la prima parte
  68. if url.startswith("/"):
  69. parent = re.search(".+//[^/]*", parent).group(0)
  70. else:
  71. # in caso contrario dobbiamo assicurarci di troncare
  72. # l'ultima parte dell'url dopo il /, a meno che non
  73. # finisca senza estensione (in quel caso aggiungiamo un /)
  74. if re.search("\.[^/]*$", parent):
  75. parent = re.sub("[^/]*$", "", parent)
  76. else:
  77. if not parent.endswith("/"):
  78. parent += "/"
  79.  
  80.  
  81.  
  82. ## Controlliamo prima di tutto se nell'url c'è un
  83. ## protocollo
  84. protocol = re.search(r"(\w+):", url)
  85. if protocol == None:
  86. url = parent + url
  87. return url
  88.  
  89. def get_content(url):
  90. """Cerca di scaricare l'url dato e restituisce
  91. -1 se non ce la fa, il contenuto altrimenti"""
  92. try:
  93. req = urllib2.urlopen(url)
  94. except:
  95. return (-1, None)
  96.  
  97. return (req.read(), req.geturl())
  98.  
  99. class Page():
  100. """Una pagina web. Questa classe, quando viene istanziata,
  101. controlla se una pagina con quel nome è già presente (una
  102. pagina è unica!) e se lo è restituisce lo stesso oggetto,
  103. altrimenti ne crea uno nuovo con un nuovo ID"""
  104.  
  105. def __repr__(self):
  106. return "<Page object: %s>" % self.url
  107.  
  108. def __init__(self, url=""):
  109.  
  110. if(url != ""):
  111. mtx_url_dict.lock(self.__new_page, url)
  112. mtx_url_dict.unlock()
  113. else:
  114. mtx_url_dict.lock(self.__get_page, 0)
  115. mtx_url_dict.unlock()
  116.  
  117. def __get_page(self, num):
  118.  
  119. if(len(url_counter) == 0):
  120. self.exhausted = True
  121. return
  122.  
  123. page_found = False
  124.  
  125. while(not page_found):
  126.  
  127. for url in url_dict:
  128. page = Page(url)
  129. if not page.analyzed:
  130. page_found = True
  131. self.url = url
  132. break
  133.  
  134. if not page_found:
  135. time.sleep(1)
  136.  
  137.  
  138.  
  139. self.ID = page.ID
  140. self.analyzed = page.analyzed
  141. self.exhausted = False
  142. url_dict[url].analyzed = True
  143.  
  144. def __new_page(self, url):
  145. # Questo ci serve per tenere il
  146. # conto di tutti gli url
  147. global url_dict
  148. global url_counter
  149.  
  150. self.exhausted = False
  151. self.analyzed = False
  152. self.url = url
  153.  
  154. if(url_dict.has_key(url)):
  155. # Preservo i parametri che esistono già!
  156. self.ID = url_dict[url].ID
  157. self.analyzed = url_dict[url].analyzed
  158.  
  159. else:
  160. try:
  161. self.ID = url_counter.pop()
  162. except IndexError:
  163. self.exhausted = True
  164.  
  165.  
  166. url_dict[url] = self
  167. url_dict[url].links = []
  168.  
  169. def add_link(self, page):
  170.  
  171. if(page.exhausted):
  172. return -1
  173. if debug:
  174. print " => Adding link to %s" % page.url
  175. mtx_url_dict.lock(self.__add_link, page.ID)
  176. mtx_url_dict.unlock()
  177. return 0
  178.  
  179. def __add_link(self, ID):
  180. url_dict[self.url].links.append(ID)
  181.  
  182. def links(self):
  183. return url_dict[self.url].links
  184.  
  185.  
  186.  
  187.  
  188. class Crawler(threading.Thread):
  189. """Partendo da startpage, segue tutti i link registrando
  190. i vari collegamenti fra le pagine. Una volta raggiunto il
  191. limite di pagine da controllare termina"""
  192.  
  193. def __init__(self, startpage=default_page):
  194. threading.Thread.__init__(self)
  195. self.start_page = startpage
  196.  
  197.  
  198. def run(self):
  199.  
  200. step_counter = 0
  201.  
  202. # Capiamo che pagina ci serve
  203. page = Page(self.start_page)
  204.  
  205. while(not page.exhausted):
  206.  
  207. if(step_counter > max_steps):
  208. page = Page(self.start_page)
  209. step_counter = 0
  210. else:
  211. page = Page()
  212. step_counter += 1
  213.  
  214. if page.exhausted:
  215. break
  216.  
  217. # Come prima cosa devo fare il parsing dei
  218. # link che ci sono nella pagina
  219. # Diamo una mixata per simulare meglio
  220. # il caso.. dato che tanto è probabile che
  221. # alcuni link rimarranno non visitati!
  222. links = get_links(page)
  223.  
  224. ## A questo punto io che mi occupo della pagina devo
  225. ## aggiungere tutti i link alla pagina
  226.  
  227. if not links == -1:
  228. random.shuffle(links)
  229. for l in links:
  230. lpage = Page(l)
  231.  
  232. if not lpage.exhausted:
  233. page.add_link(lpage)
  234. else:
  235. break
  236.  
  237.  
  238.  
  239.  
  240. if __name__ == "__main__":
  241.  
  242. parser = OptionParser()
  243. parser.add_option("-c", "--concurrency", dest="concurrency", action="store",
  244. help="Set level of concurrency (i.e. how many threads)", default=3)
  245. parser.add_option("-d", "--debug", dest="debug", action="store_true",
  246. help="Activate debug mode", default=False)
  247. parser.add_option("-o", "--output", dest="outfile", action="store",
  248. help="Name of the output file for the connection matrix", default="connections.txt")
  249. parser.add_option("-n", "--number", dest="size", action="store",
  250. help="Number of pages to analyze", default=1000)
  251. parser.add_option("-m", "--max-steps", dest="max_steps", action="store",
  252. help="Max steps to walk from the starting page", default=5)
  253. parser.add_option("-s", "--start-page", dest="start_page",
  254. default="http://poisson.phc.unipi.it",
  255. help="Starting page for all the crawlers",
  256. action="store")
  257.  
  258.  
  259. (option, args) = parser.parse_args()
  260.  
  261. concurrency = int(option.concurrency)
  262. debug = bool(option.debug)
  263. outfile = option.outfile
  264. size = int(option.size)
  265. url_counter = range(size)
  266. max_steps = int(option.max_steps)
  267. default_page = option.start_page
  268.  
  269.  
  270. l = time.localtime(time.time())
  271. print " => Starting with this configuration at %s:%s:%s\n\
  272. %d thread(s)\n\
  273. %d pages to analyze\n\
  274. %d max steps from the start page, %s\n\
  275. Writing on file %s\n\
  276. " % (l.tm_hour,l.tm_min,l.tm_sec, concurrency, size, max_steps, default_page, outfile)
  277.  
  278.  
  279. threads = []
  280. for i in range(0, concurrency):
  281. threads.append(Crawler(default_page))
  282. threads[i].start()
  283.  
  284.  
  285. ## Qui non c'è modo umano di terminare il
  286. ## suo lavoro, bisognerà studiarci sopra
  287. for i in range(0, concurrency):
  288. threads[i].join()
  289.  
  290.  
  291. ## A questo punto mi devo preoccupare di salvare
  292. ## la matrice in un formato soddisfacente
  293.  
  294. out = open(outfile, 'w')
  295. out.write(str(size) + "\n")
  296.  
  297.  
  298.  
  299. for page in url_dict:
  300. for link in url_dict[page].links:
  301. out.write(page + "\t" + str(url_dict[page].ID) + "\t" + str(link) + "\n")
  302.  
  303. l = time.localtime(time.time())
  304. print " => Work completed at %s:%s:%s " % (l.tm_hour,l.tm_min,l.tm_sec)
  305.  
  306.  
  307.  
  308.