crawler.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. #!/bin/php
  2. <?php
  3. /*
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. define('N',"\n");
  16. $link=false;
  17. $logf=false;
  18. $jsonf=false;
  19. declare(ticks=1);
  20. pcntl_signal(SIGTERM,'signalHandler');// Termination ('kill' was called)
  21. pcntl_signal(SIGHUP,'signalHandler');// Terminal log-out
  22. pcntl_signal(SIGINT,'signalHandler');// Interrupted (Ctrl-C is pressed)
  23. function signalHandler($signal) {
  24. global $link, $logf, $jsonf;
  25. lecho(N.'Sono stato interrotto.'.N);
  26. if ($link) {
  27. lecho('La connessione MySQL è aperta, la chiudo.'.N);
  28. mysqli_close($link);
  29. }
  30. if ($jsonf) {
  31. lecho('Il file di dump json è aperto, lo chiudo.'.N);
  32. // qui no, altrimenti "riprendi" fa poi casino
  33. // fwrite($jsonf,'"Fine?": true'.N.'}'.N);
  34. fclose($jsonf);
  35. }
  36. if ($logf) {
  37. lecho('Il file di log è aperto, lo chiudo.'.N);
  38. fclose($logf);
  39. }
  40. exit(2);
  41. }
  42. $opts=array(
  43. 'timeout'=>3,
  44. 'log'=>true,
  45. 'jsonfp'=>__DIR__.'/instances.json',
  46. 'jsonwrite'=>true,
  47. 'jsonread'=>false
  48. );
  49. use function mysqli_real_escape_string as myesc;
  50. function tosec($str) {
  51. if (preg_match('/^([0-9]+)([smogSMA]?)/',$str,$buf)===1) {
  52. switch ($buf[2]) {
  53. case '':
  54. case 's':
  55. return($buf[1]);
  56. break;
  57. case 'm':
  58. return($buf[1]*60);
  59. break;
  60. case 'o':
  61. return($buf[1]*60*60);
  62. break;
  63. case 'g':
  64. return($buf[1]*60*60*24);
  65. break;
  66. case 'S':
  67. return($buf[1]*60*60*24*7);
  68. break;
  69. case 'M':
  70. return($buf[1]*60*60*24*30);
  71. break;
  72. case 'A':
  73. return($buf[1]*60*60*24*365);
  74. break;
  75. }
  76. } else {
  77. return(false);
  78. }
  79. }
  80. function mexit($msg,$code) {
  81. global $link, $jsonf, $logf;
  82. lecho($msg);
  83. if ($link)
  84. mysqli_close($link);
  85. if ($jsonf)
  86. fclose($jsonf);
  87. if ($logf)
  88. fclose($logf);
  89. exit($code);
  90. }
  91. function lecho($msg,$logonly=false) {
  92. global $opts, $logf;
  93. if (!$logonly)
  94. echo($msg);
  95. if ($opts['log'])
  96. fwrite($logf,$msg);
  97. }
  98. $instsjfp=__DIR__.'/instances.job';
  99. $currinstjfp=__DIR__.'/currinst.job';
  100. if (file_exists($currinstjfp) && file_exists($instsjfp)) {
  101. $riprendi=true;
  102. } else {
  103. $riprendi=false;
  104. }
  105. $logfp=__DIR__.'/crawler.log';
  106. if ($opts['log']) {
  107. if ($riprendi)
  108. $mode=array('a','aggiunta');
  109. else
  110. $mode=array('w','scrittura');
  111. $logf=@fopen($logfp,$mode[0]);
  112. if ($logf===false) {
  113. echo('Non ho potuto aprire in modalità '.$mode[1].' il file di log «'.$logfp.'».'.N);
  114. exit(1);
  115. }
  116. }
  117. $inifp=__DIR__.'/../sec/mastostartadmin.ini';
  118. $iniarr=@parse_ini_file($inifp)
  119. or mexit('Impossibile aprire il file di configurazione «'.$inifp.'»'.N,1);
  120. $link=@mysqli_connect($iniarr['db_host'],$iniarr['db_admin_name'],$iniarr['db_admin_password'],$iniarr['db_name'],$iniarr['db_port'],$iniarr['db_socket'])
  121. or mexit('Impossibile connettersi al server MySQL: '.mysqli_connect_error().N,1);
  122. mysqli_set_charset($link,'utf8mb4')
  123. or mexit(mysqli_error($link).N,1);
  124. $tables=array();
  125. $res=mysqli_query($link,'SHOW TABLES')
  126. or mexit(mysqli_error($link).N,1);
  127. while ($row=mysqli_fetch_row($res)) {
  128. $resb=mysqli_query($link,'SHOW COLUMNS FROM '.$row[0])
  129. or mexit(mysqli_error($link).N,1);
  130. $fields=array();
  131. // lo uso solo per alcuni tipi, quindi non sto a cercare completezza
  132. while ($rowb=mysqli_fetch_assoc($resb)) {
  133. if (preg_match('/(\w+)\((.*)\)( unsigned)?/',$rowb['Type'],$buf)===1) {
  134. switch ($buf[1]) {
  135. case 'char':
  136. case 'varchar':
  137. $fields[$rowb['Field']]=$buf[2];
  138. break;
  139. case 'tinyint':
  140. if (array_key_exists(3,$buf))
  141. $fields[$rowb['Field']]=array('min'=>0,'max'=>255);
  142. else
  143. $fields[$rowb['Field']]=array('min'=>-128,'max'=>127);
  144. break;
  145. case 'smallint':
  146. if (array_key_exists(3,$buf))
  147. $fields[$rowb['Field']]=array('min'=>0,'max'=>65535);
  148. else
  149. $fields[$rowb['Field']]=array('min'=>-32768,'max'=>32767);
  150. break;
  151. case 'mediumint':
  152. if (array_key_exists(3,$buf))
  153. $fields[$rowb['Field']]=array('min'=>0,'max'=>16777215);
  154. else
  155. $fields[$rowb['Field']]=array('min'=>-8388608,'max'=>8388607);
  156. break;
  157. case 'int':
  158. if (array_key_exists(3,$buf))
  159. $fields[$rowb['Field']]=array('min'=>0,'max'=>4294967295);
  160. else
  161. $fields[$rowb['Field']]=array('min'=>-2147483648,'max'=>2147483647);
  162. break;
  163. // bigint non ci sta in php a meno di usare bcmath o gmp che non è detto siano abilitate sul server, in ogni caso poco importa perché valori bigint vengono usati solo internamente al db, non "vengono da fuori"
  164. case 'bigint':
  165. if (array_key_exists(3,$buf))
  166. $fields[$rowb['Field']]=array('min'=>'0','max'=>'18446744073709551615');
  167. else
  168. $fields[$rowb['Field']]=array('min'=>'-9223372036854775808','max'=>'9223372036854775807');
  169. break;
  170. case 'decimal':
  171. // questo è da testare contro un decimale vero
  172. // fatto, il risultato è che in mysql devo usare decimal(14,4)
  173. if (preg_match('/,/',$buf[2])===1) {
  174. $lim=explode(',',$buf[2]);
  175. } else {
  176. $lim[0]=$buf[2];
  177. $lim[1]=0;
  178. }
  179. $int=$lim[0]-$lim[1];
  180. $sint='';
  181. for ($i=0; $i<$int; $i++)
  182. $sint.='9';
  183. $sdec='';
  184. for ($i=0; $i<$lim[1]; $i++)
  185. $sdec.='9';
  186. $max=$sint.'.'.$sdec;
  187. if (array_key_exists(3,$buf))
  188. $fields[$rowb['Field']]=array('min'=>0,'max'=>floatval($max));
  189. else
  190. $fields[$rowb['Field']]=array('min'=>floatval('-'.$max),'max'=>floatval($max));
  191. break;
  192. default:
  193. $fields[$rowb['Field']]=$rowb['Type'];
  194. break;
  195. }
  196. } elseif ($rowb['Type']=='text') {
  197. $fields[$rowb['Field']]=65535;
  198. } else {
  199. $fields[$rowb['Field']]=$rowb['Type'];
  200. }
  201. }
  202. $tables[$row[0]]=$fields;
  203. }
  204. if ($riprendi) {
  205. lecho('Pare che ci sia un lavoro in sospeso, provo a riprenderlo...'.N);
  206. $buf=@file($instsjfp,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)
  207. or mexit('Non ho potuto aprire in lettura il file «'.$instsjfp.'».'.N,1);
  208. $insts=array();
  209. foreach ($buf as $line)
  210. $insts[]=$line;
  211. $buf=@file($currinstjfp,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)
  212. or mexit('Non ho potuto aprire in lettura il file «'.$currinstjfp.'».'.N,1);
  213. $buf=explode("\t",$buf[0]);
  214. $currinst=array('dom'=>$buf[0], 'i'=>$buf[1], 'qok'=>$buf[2], 'qgood'=>$buf[3]);
  215. $riprendi=true;
  216. }
  217. $tronconi=array();
  218. function flushtronc($id) {
  219. global $tronconi;
  220. foreach ($tronconi as $row) {
  221. if (!is_null($id)) {
  222. if ($row['tab']=='Blacklist')
  223. $eurl='editblinst.php';
  224. elseif ($row['tab']=='Instances')
  225. $eurl='editinst.php';
  226. elseif ($row['tab']=='Languages')
  227. $eurl='editlang.php';
  228. // questo qui sotto non è errore: la tabella InstTrends non ha ID perciò non è editabile, il massimo che si può fare è andare a vedere la tabella Instances e i trends collegati (l'id che viene passato è infatti quello della tabella Instances)
  229. elseif ($row['tab']=='InstTrends')
  230. $eurl='editinst.php';
  231. }
  232. $msg=$row['ctx'].': ho dovuto troncare a '.$row['size'].' caratteri il valore da inserire nella colonna «'.$row['col'].'» della tabella «'.$row['tab'].'» perché troppo lungo ('.$row['len'].' caratteri).';
  233. if (!is_null($id))
  234. $msg.=' Puoi <a href="'.$eurl.'?id='.$id.'">editarlo qui</a>.';
  235. notify($msg,2);
  236. }
  237. $tronconi=array();
  238. }
  239. function truncs($str,$tab,$col,$ctx) {
  240. global $tables, $tronconi;
  241. $size=$tables[$tab][$col];
  242. $len=mb_strlen($str,'UTF-8');
  243. if ($len>$size) {
  244. $tronconi[]=array('id'=>null,'tab'=>$tab,'col'=>$col,'ctx'=>$ctx,'len'=>$len,'size'=>$size);
  245. $str=mb_substr($str,0,$size-1,'UTF-8').'…';
  246. }
  247. return($str);
  248. }
  249. function truncn($num,$tab,$col,$ctx) {
  250. global $tables;
  251. if (is_numeric($num)) {
  252. if ($num>$tables[$tab][$col]['max']) {
  253. notify($ctx.': ho dovuto troncare «'.$num.'» al valore massimo «'.$tables[$tab][$col]['max'].'» che può avere nella colonna «'.$col.'» della tabella «'.$tab.'»).',2);
  254. $num=$tables[$tab][$col]['max'];
  255. } elseif ($num<$tables[$tab][$col]['min']) {
  256. notify($ctx.': ho dovuto troncare «'.$num.'» al valore minimo «'.$tables[$tab][$col]['min'].'» che può avere nella colonna «'.$col.'» della tabella «'.$tab.'»).',2);
  257. $num=$tables[$tab][$col]['min'];
  258. }
  259. } else {
  260. notify($ctx.': truncn(): mi aspettavo un numero, invece non lo era; ritorno «0».',3);
  261. $num=0;
  262. }
  263. return($num);
  264. }
  265. $contextopts=array(
  266. 'http'=>array(
  267. 'timeout'=>$opts['timeout']
  268. ),
  269. 'socket'=>array(
  270. 'tcp_nodelay'=>true
  271. )
  272. );
  273. $context=stream_context_create($contextopts);
  274. $blacklist=array();
  275. lecho('Carico la blacklist dal database...'.N);
  276. $res=mysqli_query($link,'SELECT * FROM Blacklist')
  277. or mexit(mysqli_error($link).N,3);
  278. lecho(mysqli_num_rows($res).' istanze nella blacklist.'.N);
  279. while($row=mysqli_fetch_assoc($res)) {
  280. $blacklist[$row['Domain']]=$row;
  281. }
  282. function pgdatetomy($pgdate) {
  283. if (preg_match('/^(\d+)-(\d+)-(\d+)[ T]{1}(\d+):(\d+):(\d+)(\.\d+)?Z?$/',$pgdate,$buf)===1) {
  284. $mtime=mktime($buf[4],$buf[5],$buf[6],$buf[2],$buf[3],$buf[1]);
  285. if (array_key_exists(7,$buf))
  286. $mtime=$mtime+floatval('0'.$buf[7]);
  287. return($mtime);
  288. } else {
  289. notify('pgdatetomy: «'.$pgdate.'» non è un formato di data riconosciuto! Ritorno il magico momento attuale.',3);
  290. return(time());
  291. }
  292. }
  293. function blpgdumplinetomy($line) {
  294. $truefalse=array('f'=>0,'t'=>1);
  295. $row=explode("\t",$line);
  296. $row=array('Domain'=>$row[0],
  297. 'CreatedAt'=>pgdatetomy($row[1]),
  298. 'ModifiedAt'=>pgdatetomy($row[2]),
  299. 'Severity'=>$row[3],
  300. 'RejectMedia'=>$truefalse[$row[4]],
  301. 'RejectReports'=>$truefalse[$row[5]],
  302. 'PublicComment'=>$row[6]);
  303. return($row);
  304. }
  305. if (!$riprendi) {
  306. $blacklistnew=array();
  307. $insts=array();
  308. lecho('Carico le istanze di partenza...'.N);
  309. $res=mysqli_query($link,'SELECT Domain FROM StartNodes')
  310. or mexit(mysqli_error($link).N,3);
  311. lecho(mysqli_num_rows($res).' istanze di partenza.'.N);
  312. while($row=mysqli_fetch_assoc($res)) {
  313. $insts[]=$row['Domain'];
  314. lecho('Recupero la lista delle istanze note a «'.$row['Domain'].'» ... ');
  315. $buf=@file_get_contents('https://'.$row['Domain'].'/api/v1/instance/peers',false,$context);
  316. if ($buf!==false) {
  317. lecho('OK :-)'.N);
  318. $peers=json_decode($buf,true);
  319. foreach ($peers as $pdom) {
  320. if (willtrunc($pdom,'Instances','URI'))
  321. notify('L’istanza «'.$pdom.'» non sarà considerata perché il suo dominio è troppo lungo per il campo «URI» della tabella «Instances» nel DB',1);
  322. if (!in_array($pdom,$insts) && !willtrunc($pdom,'Instances','URI'))
  323. $insts[]=$pdom;
  324. }
  325. } else {
  326. lecho('ERRORE :-('.N);
  327. }
  328. lecho('Recupero la blacklist di «'.$row['Domain'].'» ... ');
  329. $buf=@file_get_contents('https://'.$row['Domain'].'/domain_blocks.txt',false,$context);
  330. if ($buf!==false) {
  331. lecho('OK :-)'.N);
  332. $buf=explode(N,$buf);
  333. foreach ($buf as $line) {
  334. if (preg_match('/(^#.*$)|(^\s*$)/',$line)===0) {
  335. $brow=blpgdumplinetomy($line);
  336. if (!array_key_exists($brow['Domain'],$blacklist)) {
  337. $blacklistnew[$brow['Domain']]=$brow;
  338. }
  339. $blacklist[$brow['Domain']]=$brow;
  340. }
  341. }
  342. } else {
  343. lecho('ERRORE :-('.N);
  344. }
  345. }
  346. foreach ($blacklistnew as $row) {
  347. if (!willtrunc($row['Domain'],'Blacklist','Domain')) {
  348. mysqli_query($link,'INSERT INTO Blacklist (ID, Domain, CreatedAt, ModifiedAt, Severity, RejectMedia, RejectReports, PrivateComment, PublicComment) VALUES (NULL, \''.myesc($link,$row['Domain']).'\', \''.myesc($link,$row['CreatedAt']).'\', \''.myesc($link,$row['ModifiedAt']).'\', \''.myesc($link,$row['Severity']).'\', \''.myesc($link,$row['RejectMedia']).'\', \''.myesc($link,$row['RejectReports']).'\', NULL, \''.myesc($link,$row['Domain']).'\')')
  349. or mexit(mysqli_error($link).N,3);
  350. flushtronc(mysqli_insert_id($link));
  351. } else {
  352. notify('Non ho potuto inserire «'.$row['Domain'].'» nella tabella delle istanze blacklistate perché il dominio è troppo lungo per il campo corrispondente nel DB.',2);
  353. }
  354. }
  355. //lecho('Carico le istanze note dal DB e aggiungo alla lista di quelle da controllare quelle che non ci sono già.'.N);
  356. $res=mysqli_query($link,'SELECT URI FROM Instances')
  357. or mexit(mysqli_error($link).N,3);
  358. while($row=mysqli_fetch_assoc($res)) {
  359. if (!in_array($row['URI'],$insts))
  360. $insts[]=$row['URI'];
  361. }
  362. sort($insts);
  363. ksort($blacklist);
  364. ksort($blacklistnew);
  365. lecho('Istanze recuperate: '.count($insts).N);
  366. lecho('Istanze blacklistate: '.count($blacklist).', di cui '.count($blacklistnew).' nuove aggiunte al DB.'.N);
  367. $instsf=@fopen($instsjfp,'w')
  368. or mexit('Non ho potuto aprire in scrittura il file «'.$instsjfp.'».'.N,1);
  369. foreach ($insts as $dom)
  370. fwrite($instsf,$dom.N);
  371. fclose($instsf);
  372. }
  373. function willtrunc($str,$tab,$col) {
  374. global $tables;
  375. if (mb_strlen($str,'UTF-8')>$tables[$tab][$col])
  376. return(true);
  377. else
  378. return(false);
  379. }
  380. function b2i($bool,$pre) {
  381. if (is_bool($bool)) {
  382. if ($bool)
  383. return(1);
  384. else
  385. return(0);
  386. } else {
  387. notify($pre.'il valore «'.$bool.'» non è booleano, lo assumo come falso e ritorno «0».',2);
  388. return(0);
  389. }
  390. }
  391. //is array, array key exists and value is not null
  392. function akeavinn($key,&$arr) {
  393. if (is_array($arr) && array_key_exists($key,$arr) && !is_null($arr[$key]))
  394. return(true);
  395. else
  396. return(false);
  397. }
  398. function nempty($str) {
  399. if (preg_match('/^\s*$/',$str)===1)
  400. return(null);
  401. else
  402. return($str);
  403. }
  404. function subarimp($glue,$key,&$arr) {
  405. $str='';
  406. $i=1;
  407. $carr=count($arr);
  408. foreach ($arr as $inarr) {
  409. $str.=$inarr[$key];
  410. if ($i<$carr)
  411. $str.=$glue;
  412. $i++;
  413. }
  414. return($str);
  415. }
  416. function notify($msg,$sev) {
  417. global $link, $tables;
  418. lecho('NOTIFICAZIÒ: '.strip_tags($msg).N);
  419. mysqli_query($link,'INSERT INTO Notifications (ID, Notification, Severity, Microtime, Seen) VALUES (NULL, \''.myesc($link,mb_substr($msg,0,$tables['Notifications']['Notification'],'UTF-8')).'\', '.$sev.', \''.microtime(true).'\', 0)')
  420. or mexit(mysqli_error($link).N,3);
  421. }
  422. function langs($instid) {
  423. global $info, $instrow, $link;
  424. $instlangs=array();
  425. if (akeavinn('languages',$info)) {
  426. $pos=0;
  427. foreach ($info['languages'] as $lang) {
  428. $res=mysqli_query($link,'SELECT * FROM Languages WHERE Code=\''.myesc($link,$lang).'\'')
  429. or mexit(mysqli_error($link).N,3);
  430. if (mysqli_num_rows($res)<1) {
  431. mysqli_query($link,'INSERT INTO Languages (ID, Code) VALUES (NULL, \''.myesc($link,truncs($lang,'Languages','Code','«'.$instrow['URI'].'»')).'\')')
  432. or mexit(mysqli_error($link).N,3);
  433. $langid=mysqli_insert_id($link);
  434. flushtronc($langid);
  435. } else {
  436. $row=mysqli_fetch_assoc($res);
  437. $langid=$row['ID'];
  438. }
  439. $pos++;
  440. $instlangs[]=array('InstID'=>$instid,'LangID'=>$langid,'Pos'=>$pos,'Code'=>$lang);
  441. }
  442. }
  443. return($instlangs);
  444. }
  445. function varbdump($var) {
  446. ob_start();
  447. var_dump($var);
  448. $content=ob_get_contents();
  449. ob_end_clean();
  450. return($content);
  451. }
  452. function mdasortbykey(&$arr,$key,$rev=false) {
  453. $karr=array();
  454. foreach ($arr as $akey=>$subarr)
  455. $karr[$subarr[$key]]=array($akey,$subarr);
  456. if (!$rev)
  457. ksort($karr);
  458. else
  459. krsort($karr);
  460. $arr=array();
  461. foreach ($karr as $akey=>$subarr)
  462. $arr[$subarr[0]]=$subarr[1];
  463. }
  464. /*
  465. * Nodeinfo ('https://'.$dom.'/nodeinfo/2.0') è stato aggiunto nella 3.0.0
  466. * Trends ('https://'.$dom.'/api/v1/trends') è stato aggiunto nella 3.0.0
  467. * Activity ('https://'.$dom.'/api/v1/instance/activity') è stato aggiunto nella 2.1.2
  468. */
  469. if ($opts['jsonwrite']) {
  470. if ($riprendi)
  471. $mode=array('a','aggiunta');
  472. else
  473. $mode=array('w','scrittura');
  474. $jsonf=@fopen($opts['jsonfp'],$mode[0])
  475. or mexit('Non ho potuto aprire in modalità '.$mode[1].' il file di dump delle info json «'.$opts['jsonfp'].'».',1);
  476. if ($mode[0]=='w')
  477. fwrite($jsonf,'{'.N);
  478. }
  479. $cinsts=count($insts);
  480. $i=0;
  481. $qok=0;
  482. $qgood=0;
  483. if ($riprendi) {
  484. $i=$currinst['i'];
  485. $qok=$currinst['qok'];
  486. $qgood=$currinst['qgood'];
  487. }
  488. while ($i<$cinsts) {
  489. $dom=$insts[$i];
  490. @file_put_contents($currinstjfp,$dom."\t".$i."\t".$qok."\t".$qgood.N)
  491. or mexit('Non ho potuto aprire in scrittura il file «'.$currinstjfp.'».',1);
  492. $i++;
  493. $ok=true;
  494. $info=null;
  495. lecho('~~~~~~~~~~~~~~~'.N);
  496. lecho('Provo a recuperare info su «'.$dom.'» ['.$i.'/'.$cinsts.' ('.$qok.' OK; '.$qgood.' BUONE) - '.round(100/$cinsts*$i).'%]'.N);
  497. lecho('Provo a recuperare le informazioni API sull’istanza ... ');
  498. $buf=@file_get_contents('https://'.$dom.'/api/v1/instance',false,$context);
  499. if ($buf!==false) {
  500. $info=json_decode($buf,true);
  501. if (is_array($info)) {
  502. lecho('OK :-)'.N);
  503. lecho('Provo a recuperare le informazioni Nodeinfo sull’istanza ... ');
  504. $buf=@file_get_contents('https://'.$dom.'/nodeinfo/2.0',false,$context);
  505. if ($buf!==false) {
  506. lecho('OK :-)'.N);
  507. $info['x-nodeinfo']=json_decode($buf,true);
  508. // per ora teniamo solo quelle che, se si identificano, si identificano come mastodon o corgidon (derivato di mastodon)
  509. // teniamo d'occhio le notifiche di cui sotto per includere eventualmente altri derivati di mastodon?
  510. // visti fin qui, verificare cosa sono: epicyon
  511. if (is_array($info['x-nodeinfo']) && array_key_exists('software',$info['x-nodeinfo']) && array_key_exists('name',$info['x-nodeinfo']['software']) &&!is_null($info['x-nodeinfo']['software']['name'])) {
  512. if (preg_match('/^mastodon|corgidon/',$info['x-nodeinfo']['software']['name'])===0)
  513. $ok=false;
  514. $res=mysqli_query($link,'SELECT Name FROM Platforms WHERE Name=\''.myesc($link,$info['x-nodeinfo']['software']['name']).'\'')
  515. or mexit(mysqli_error($link).N,3);
  516. if (mysqli_num_rows($res)<1) {
  517. $res=mysqli_query($link,'INSERT INTO Platforms (Name) VALUES (\''.myesc($link,truncs($info['x-nodeinfo']['software']['name'],'Platforms','Name','«'.$info['uri'].'»')).'\')')
  518. or mexit(mysqli_error($link).N,3);
  519. notify('«'.$info['uri'].'» utilizza come software «'.$info['x-nodeinfo']['software']['name'].'»; lo aggiungo alla tabella delle piattaforme incontrate. Se non si tratta di mastodon o corgidon, che già vengono accettati, sarebbe buona cosa verificare se è una variante di mastodon e quanto è compatibile, per valutare se accettare le istanze che lo utilizzano.',1);
  520. flushtronc(null);
  521. }
  522. }
  523. } else {
  524. lecho('ERRORE :-('.N);
  525. }
  526. if ($ok && array_key_exists('version',$info)) {
  527. if ($info['version']>='2.1.2') {
  528. lecho('Provo a recuperare le informazioni API sull’attività dell’istanza ... ');
  529. $buf=@file_get_contents('https://'.$dom.'/api/v1/instance/activity',false,$context);
  530. if ($buf!==false) {
  531. lecho('OK :-)'.N);
  532. $info['x-activity']=json_decode($buf,true);
  533. } else {
  534. lecho('ERRORE :-('.N);
  535. }
  536. }
  537. if ($info['version']>='3.0.0') {
  538. lecho('Provo a recuperare le informazioni API sui trends dell’istanza ... ');
  539. $buf=@file_get_contents('https://'.$dom.'/api/v1/trends',false,$context);
  540. if ($buf!==false) {
  541. lecho('OK :-)'.N);
  542. $info['x-trends']=json_decode($buf,true);
  543. } else {
  544. lecho('ERRORE :-('.N);
  545. }
  546. }
  547. }
  548. } else {
  549. $ok=false;
  550. lecho('ERRORE :-('.N);
  551. }
  552. } else {
  553. $ok=false;
  554. lecho('ERRORE :-('.N);
  555. // questo è anche il limbo delle istanze che non rispondono, perciò controlliamo se già esistono nel db e, nel caso, aggiorniamo InstChecks
  556. $res=mysqli_query($link,'SELECT * FROM Instances WHERE URI=\''.myesc($link,mb_substr($dom,0,$tables['Instances']['URI'],'UTF-8')).'\'')
  557. or mexit(mysqli_error($link).N,3);
  558. if (mysqli_num_rows($res)>0) {
  559. lecho('«'.$dom.'» non risponde, ma è presente nel database; aggiorno InstChecks.');
  560. $row=mysqli_fetch_assoc($res);
  561. mysqli_query($link,'INSERT INTO InstChecks (InstID, Time, Status) VALUES ('.$row['ID'].', '.time().', 0)')
  562. or mexit(mysqli_error($link).N,3);
  563. }
  564. }
  565. if (is_array($info) && count($info)>0) {
  566. lecho('Dumpone json di tutte le info recuperate:'.N.json_encode($info,JSON_PRETTY_PRINT).N,true);
  567. if ($opts['jsonwrite'])
  568. fwrite($jsonf,'"'.$dom.'": '.json_encode($info,JSON_PRETTY_PRINT).','.N);
  569. }
  570. if ($ok && !is_null($info) && akeavinn('uri',$info) && !is_null(nempty($info['uri'])) && !willtrunc($info['uri'],'Instances','URI') && akeavinn('version',$info) && preg_match('/pleroma|pixelfed/i',$info['version'])===0) {
  571. $qok++;
  572. $instrow=array('ID'=>null, 'New'=>0, 'Good'=>0, 'Chosen'=>0, 'Visible'=>0, 'Blacklisted'=>0, 'URI'=>null, 'Title'=>null, 'ShortDesc'=>null, 'LongDesc'=>null, 'OurDesc'=>null, 'PlaceID'=>null, 'Email'=>null, 'Software'=>null, 'Version'=>null, 'UserCount'=>null, 'StatusCount'=>null, 'DomainCount'=>null, 'ActiveUsersMonth'=>null, 'ActiveUsersHalfYear'=>null, 'Thumb'=>null, 'RegOpen'=>null, 'RegReqApproval'=>null, 'MaxTootChars'=>null, 'AdmAccount'=>null, 'AdmDisplayName'=>null, 'AdmCreatedAt'=>null, 'AdmNote'=>null, 'AdmURL'=>null, 'AdmAvatar'=>null, 'AdmHeader'=>null);
  573. if (array_key_exists($info['uri'],$blacklist))
  574. $instrow['Blacklisted']=1;
  575. $instrow['URI']=$info['uri'];
  576. if (akeavinn('title',$info))
  577. $instrow['Title']=nempty(truncs($info['title'],'Instances','Title','«'.$instrow['URI'].'»'));
  578. if (akeavinn('short_description',$info))
  579. $instrow['ShortDesc']=nempty(truncs($info['short_description'],'Instances','ShortDesc','«'.$instrow['URI'].'»'));
  580. if (akeavinn('description',$info))
  581. $instrow['LongDesc']=nempty(truncs($info['description'],'Instances','LongDesc','«'.$instrow['URI'].'»'));
  582. if (akeavinn('email',$info))
  583. $instrow['Email']=nempty(truncs($info['email'],'Instances','Email','«'.$instrow['URI'].'»'));
  584. if (akeavinn('version',$info))
  585. $instrow['Version']=nempty(truncs($info['version'],'Instances','Version','«'.$instrow['URI'].'»'));
  586. if (akeavinn('stats',$info)) {
  587. if (akeavinn('user_count',$info['stats']))
  588. $instrow['UserCount']=truncn($info['stats']['user_count'],'Instances','UserCount','«'.$instrow['URI'].'»');
  589. if (akeavinn('status_count',$info['stats']))
  590. $instrow['StatusCount']=truncn($info['stats']['status_count'],'Instances','StatusCount','«'.$instrow['URI'].'»');
  591. if (akeavinn('domain_count',$info['stats']))
  592. $instrow['DomainCount']=truncn($info['stats']['domain_count'],'Instances','DomainCount','«'.$instrow['URI'].'»');
  593. }
  594. if (akeavinn('thumbnail',$info))
  595. $instrow['Thumb']=nempty(truncs($info['thumbnail'],'Instances','Thumb','«'.$instrow['URI'].'»'));
  596. if (akeavinn('max_toot_chars',$info))
  597. $instrow['MaxTootChars']=truncn($info['max_toot_chars'],'Instances','MaxTootChars','«'.$instrow['URI'].'»');
  598. if (akeavinn('registrations',$info))
  599. $instrow['RegOpen']=b2i($info['registrations'],'Istanza «'.$instrow['URI'].'»: ');
  600. if (akeavinn('approval_required',$info))
  601. $instrow['RegReqApproval']=b2i($info['approval_required'],'Istanza «'.$instrow['URI'].'»: ');
  602. if (akeavinn('contact_account',$info)) {
  603. if (akeavinn('acct',$info['contact_account']))
  604. $instrow['AdmAccount']=nempty(truncs($info['contact_account']['acct'],'Instances','AdmAccount','«'.$instrow['URI'].'»'));
  605. if (akeavinn('display_name',$info['contact_account']))
  606. $instrow['AdmDisplayName']=nempty(truncs($info['contact_account']['display_name'],'Instances','AdmAccount','«'.$instrow['URI'].'»'));
  607. if (akeavinn('created_at',$info['contact_account']))
  608. $instrow['AdmCreatedAt']=pgdatetomy($info['contact_account']['created_at']);
  609. if (akeavinn('note',$info['contact_account']))
  610. $instrow['AdmNote']=nempty(truncs(strip_tags($info['contact_account']['note'],'<a>'),'Instances','AdmNote','«'.$instrow['URI'].'»'));
  611. if (akeavinn('url',$info['contact_account']))
  612. $instrow['AdmURL']=nempty(truncs($info['contact_account']['url'],'Instances','AdmURL','«'.$instrow['URI'].'»'));
  613. if (akeavinn('avatar',$info['contact_account']))
  614. $instrow['AdmAvatar']=nempty(truncs($info['contact_account']['avatar'],'Instances','AdmAvatar','«'.$instrow['URI'].'»'));
  615. if (akeavinn('header',$info['contact_account']))
  616. $instrow['AdmHeader']=nempty(truncs($info['contact_account']['header'],'Instances','AdmHeader','«'.$instrow['URI'].'»'));
  617. }
  618. if (akeavinn('x-nodeinfo',$info)) {
  619. if (akeavinn('software',$info['x-nodeinfo']) && akeavinn('name',$info['x-nodeinfo']['software']))
  620. $instrow['Software']=nempty(truncs($info['x-nodeinfo']['software']['name'],'Instances','Software','«'.$instrow['URI'].'»'));
  621. if (akeavinn('usage',$info['x-nodeinfo']) && akeavinn('users',$info['x-nodeinfo']['usage'])) {
  622. if (akeavinn('activeMonth',$info['x-nodeinfo']['usage']['users']))
  623. $instrow['ActiveUsersMonth']=truncn($info['x-nodeinfo']['usage']['users']['activeMonth'],'Instances','ActiveUsersMonth','«'.$instrow['URI'].'»');
  624. if (akeavinn('activeHalfyear',$info['x-nodeinfo']['usage']['users']))
  625. $instrow['ActiveUsersHalfYear']=truncn($info['x-nodeinfo']['usage']['users']['activeHalfyear'],'Instances','ActiveUsersHalfYear','«'.$instrow['URI'].'»');
  626. }
  627. }
  628. $whynot=array();
  629. if ($instrow['Blacklisted']==1)
  630. $whynot[]='è nella blacklist';
  631. if (is_null($instrow['RegOpen'])) {
  632. $whynot[]='non se ne conosce lo stato delle registrazioni (aperte/chiuse)';
  633. } elseif ($instrow['RegOpen']==0) {
  634. $whynot[]='ha le registrazioni chiuse';
  635. }
  636. if (is_null($instrow['UserCount'])) {
  637. $whynot[]='non se ne conosce il numero di utenti';
  638. } elseif ($instrow['UserCount']<10 || $instrow['UserCount']>30000) {
  639. $whynot[]='il numero di utenti non è compreso tra 10 e 30.000';
  640. }
  641. if (is_null($instrow['DomainCount'])) {
  642. $whynot[]='non se ne conosce il numero di istanze note';
  643. } elseif ($instrow['DomainCount']<500) {
  644. $whynot[]='il numero di istanze note è minore di 500';
  645. }
  646. if (!is_null($instrow['ActiveUsersMonth'])) {
  647. if ($instrow['ActiveUsersMonth']<10)
  648. $whynot[]='il numero di utenti attivi nell’ultimo mese è minore di 10';
  649. } elseif (!is_null($instrow['StatusCount']) && $instrow['StatusCount']/$instrow['UserCount']<10) {
  650. $whynot[]='il numero medio di toots per utente è minore di 10';
  651. }
  652. if (count($whynot)==0) {
  653. $instrow['Good']=1;
  654. lecho('Siamo in presenza di un’istanza BUONA! :-)'.N);
  655. $qgood++;
  656. } else {
  657. lecho('Siamo in presenza di un’istanza CATTIVA: '.implode('; ',$whynot).' :-('.N);
  658. }
  659. $res=mysqli_query($link,'SELECT * FROM Instances WHERE URI=\''.myesc($link,$instrow['URI']).'\'')
  660. or mexit(mysqli_error($link).N,3);
  661. if (mysqli_num_rows($res)>0) {
  662. lecho('«'.$instrow['URI'].'» è già presente nel DB, la aggiorno...'.N);
  663. $oldinstrow=mysqli_fetch_assoc($res);
  664. flushtronc($oldinstrow['ID']);
  665. $instid=$oldinstrow['ID'];
  666. $instrow['ID']=$oldinstrow['ID'];
  667. $instrow['New']=$oldinstrow['New'];
  668. if ($instrow['Good']==1 && $oldinstrow['Good']==0) {
  669. notify('L’istanza «<a href="editinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» non era papabile, ma lo è diventata!',1);
  670. } elseif ($instrow['Good']==0 && $oldinstrow['Good']==1) {
  671. notify('L’istanza «<a href="editinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» era papabile, ma non lo è più per i seguenti motivi: '.implode('; ',$whynot),3);
  672. }
  673. $instrow['Chosen']=$oldinstrow['Chosen'];
  674. $instrow['Visible']=$oldinstrow['Visible'];
  675. if ($instrow['ShortDesc']!=$oldinstrow['ShortDesc'])
  676. notify('<p>La «Descrizione breve» dell’istanza «<a href="editinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata. La vecchia era...</p><div class="valdesc">'.$oldinstrow['ShortDesc'].'</div><p>La nuova è...</p><div class="valdesc">'.$instrow['ShortDesc'].'</div>',1);
  677. if ($instrow['LongDesc']!=$oldinstrow['LongDesc'])
  678. notify('<p>La «Descrizione lunga» dell’istanza «<a href="editinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata. La vecchia era...</p><div class="valdesc">'.$oldinstrow['LongDesc'].'</div><p>La nuove è...</p><div class="valdesc">'.$instrow['LongDesc'].'</div>',1);
  679. $instrow['OurDesc']=$oldinstrow['OurDesc'];
  680. $instrow['PlaceID']=$oldinstrow['PlaceID'];
  681. $query='UPDATE Instances SET ';
  682. foreach ($instrow as $field=>$value) {
  683. if (!is_null($value))
  684. $query.=$field.'=\''.myesc($link,$value).'\', ';
  685. else
  686. $query.=$field.'=NULL, ';
  687. }
  688. $query=substr($query,0,-2).' WHERE Instances.ID='.$instrow['ID'];
  689. lecho('QUERONA DI UPDATE: «'.$query.'».'.N);
  690. mysqli_query($link,$query)
  691. or mexit(mysqli_error($link).N,3);
  692. $res=mysqli_query($link,'SELECT InstID, LangID, Pos, Code FROM InstLangs LEFT JOIN Languages ON Languages.ID=LangID WHERE InstID='.$instrow['ID'].' ORDER BY Pos ASC')
  693. or mexit(mysqli_error($link).N,3);
  694. $oldinstlangs=array();
  695. while ($row=mysqli_fetch_assoc($res))
  696. $oldinstlangs[]=$row;
  697. $instlangs=langs($instrow['ID']);
  698. if ($instlangs!=$oldinstlangs) {
  699. notify('La lista delle lingue utilizzate dichiarate dall’istanza «<a href="editinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata da «'.subarimp(', ','Code',$oldinstlangs).'» a «'.subarimp(', ','Code',$instlangs).'».',1);
  700. mysqli_query($link,'DELETE FROM InstLangs WHERE InstID='.$instrow['ID'])
  701. or mexit(mysqli_error($link).N,3);
  702. foreach ($instlangs as $row) {
  703. mysqli_query($link,'INSERT INTO InstLangs (InstID, LangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  704. or mexit(mysqli_error($link).N,3);
  705. }
  706. }
  707. } else {
  708. lecho('«'.$info['uri'].'» non è già presente nel DB, la aggiungo...'.N);
  709. $instrow['New']=1;
  710. $fields=array();
  711. $values='';
  712. foreach ($instrow as $field=>$value) {
  713. $fields[]=$field;
  714. if (!is_null($value))
  715. $values.='\''.myesc($link,$value).'\', ';
  716. else
  717. $values.='NULL, ';
  718. }
  719. $values=substr($values,0,-2);
  720. $query='INSERT INTO Instances ('.implode(', ',$fields).') VALUES ('.$values.')';
  721. lecho('QUERONA DI INSERT: «'.$query.'»'.N);
  722. mysqli_query($link,$query)
  723. or mexit(mysqli_error($link).N,3);
  724. $instid=mysqli_insert_id($link);
  725. flushtronc($instid);
  726. $instlangs=langs($instid);
  727. foreach ($instlangs as $row) {
  728. mysqli_query($link,'INSERT INTO InstLangs (InstID, LangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  729. or mexit(mysqli_error($link).N,3);
  730. }
  731. if ($instrow['Good']==1)
  732. notify('La nuova istanza «<a href="editinst.php?id='.$instid.'">'.$instrow['URI'].'</a>» è papabile!',1);
  733. }
  734. if (array_key_exists('x-activity',$info) && is_array($info['x-activity'])) {
  735. mysqli_query($link,'DELETE FROM InstActivity WHERE InstID='.$instid);
  736. foreach ($info['x-activity'] as $buf) {
  737. if (akeavinn('week',$buf) && akeavinn('statuses',$buf) && akeavinn('logins',$buf) && akeavinn('registrations',$buf)) {
  738. $query='INSERT INTO InstActivity (InstID, Week, Statuses, Logins, Registrations) VALUES (\''.$instid.'\', \''.myesc($link,$buf['week']).'\', \''.myesc($link,$buf['statuses']).'\', \''.myesc($link,$buf['logins']).'\', \''.myesc($link,$buf['registrations']).'\')';
  739. mysqli_query($link,$query)
  740. or mexit(mysqli_error($link).N,3);
  741. }
  742. }
  743. }
  744. if (array_key_exists('x-trends',$info) && is_array($info['x-trends'])) {
  745. $trends=array();
  746. foreach ($info['x-trends'] as $buf) {
  747. if (akeavinn('name',$buf) && akeavinn('url',$buf) && akeavinn('history',$buf) && is_array($buf['history'])) {
  748. $trend=0;
  749. foreach ($buf['history'] as $row) {
  750. if ($row['uses']>0)
  751. $trend+=($row['accounts']/$row['uses']);
  752. }
  753. $trends[]=array(
  754. 'InstID'=>$instid,
  755. 'LastDay'=>$buf['history'][0]['day'],
  756. 'Name'=>$buf['name'],
  757. 'URL'=>$buf['url'],
  758. 'Pos'=>null,
  759. 'trend'=>$trend
  760. );
  761. }
  762. }
  763. mdasortbykey($trends,'trend',true);
  764. // print_r($trends);
  765. mysqli_query($link,'DELETE FROM InstTrends WHERE InstID='.$instid);
  766. $pos=0;
  767. foreach ($trends as $trend) {
  768. $pos++;
  769. $query='INSERT INTO InstTrends (InstID, LastDay, Name, URL, Pos) VALUES ('.$trend['InstID'].', \''.$trend['LastDay'].'\', \''.myesc($link,truncs($trend['Name'],'InstTrends','Name','«'.$instrow['URI'].'»')).'\', \''.myesc($link,truncs($trend['URL'],'InstTrends','URL','«'.$instrow['URI'].'»')).'\', '.$pos.')';
  770. mysqli_query($link,$query)
  771. or mexit(mysqli_error($link).N,3);
  772. // questo qui sotto non è errore, vedi il commento relativo nella funzione
  773. flushtronc($instid);
  774. }
  775. }
  776. mysqli_query($link,'INSERT INTO InstChecks (InstID, Time, Status) VALUES ('.$instid.', '.time().', 1)')
  777. or mexit(mysqli_error($link).N,3);
  778. }
  779. }
  780. mysqli_close($link);
  781. if ($opts['jsonwrite']) {
  782. fwrite($jsonf,'"Fine?": true'.N.'}'.N);
  783. fclose($jsonf);
  784. }
  785. unlink($instsjfp);
  786. unlink($currinstjfp);
  787. exit(0);
  788. ?>