crawler.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. #!/usr/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. require __DIR__ . "/../../vendor/autoload.php";
  17. use LanguageDetection\Language;
  18. if (strtoupper(substr(PHP_OS,0,3))==='WIN')
  19. $iswin=true;
  20. else
  21. $iswin=false;
  22. $link=false;
  23. $logf=false;
  24. $jsonf=false;
  25. declare(ticks=1);
  26. if (function_exists('pcntl_signal')) {
  27. function signalHandler($signal) {
  28. global $link, $logf, $jsonf;
  29. lecho(N.'Sono stato interrotto.'.N);
  30. if ($link) {
  31. lecho('La connessione MySQL è aperta, la chiudo.'.N);
  32. mysqli_close($link);
  33. }
  34. if ($jsonf) {
  35. lecho('Il file di dump json è aperto, lo chiudo.'.N);
  36. // qui no, altrimenti "riprendi" fa poi casino
  37. // fwrite($jsonf,'"Fine?": true'.N.'}'.N);
  38. fclose($jsonf);
  39. }
  40. if ($logf) {
  41. lecho('Il file di log è aperto, lo chiudo.'.N);
  42. fclose($logf);
  43. }
  44. exit(2);
  45. }
  46. pcntl_signal(SIGTERM,'signalHandler');// Termination ('kill' was called)
  47. pcntl_signal(SIGHUP,'signalHandler');// Terminal log-out
  48. pcntl_signal(SIGINT,'signalHandler');// Interrupted (Ctrl-C is pressed)
  49. }
  50. $opts=array(
  51. 'timeout'=>3,
  52. 'log'=>false,
  53. 'jsonfp'=>__DIR__.'/instances.json',
  54. 'jsonwrite'=>false,
  55. 'peersfp'=>__DIR__.'/peers'
  56. );
  57. $help='crawler.php
  58. DESCRIZIONE
  59. Popola/aggiorna il database di mastostart con i dati che riesce
  60. a recuperare da una lista di istanze composta da quelle già presenti
  61. nel database più quelle di un file specificabile (tipicamente il file
  62. di output di peerscrawl.php).
  63. È possibile fermarne l’esecuzione per riprenderla in un secondo tempo:
  64. il programma genera, durante l’esecuzione, una lista delle istanze che
  65. deve controllare («instances.job») e un file in cui viene salvata l’ultima
  66. istanza controllata e altri dati; per riprendere l’esecuzione là dove
  67. era stata lasciata basta lanciare nuovamente il programma; per evitare
  68. che il programma riprenda da dove era arrivato durante l’esecuzione
  69. precedente basta cancellare i due file di cui sopra.
  70. SYNOPSIS
  71. peerscrawl.php [options]
  72. OPTIONS
  73. -p, --peersfp <file>
  74. Definisce il file da cui caricare la lista delle istanze di cui cercare
  75. di recuperare i dati. Nota: questa opzione è ininfluente se il programma
  76. viene lanciato per riprendere un’esecuzione precedente interrotta.
  77. DEFAULT: «'.$opts['peersfp'].'»
  78. -t, --timeout <secondi>
  79. Definisce il timeout in secondi di ogni tentativo di connessione.
  80. DEFAULT: «'.$opts['timeout'].'»
  81. -l, --log
  82. Attiva il logging dell’output nel file «crawler.php» nella stessa
  83. directory di crawler.php.
  84. -j, --jsonwrite
  85. Attiva la scrittura di un file «instances.json» nella stessa directory
  86. di crawler.php, contenente tutti i dati recuperati da tutte le istanze.
  87. This program comes with ABSOLUTELY NO WARRANTY; for details see the source.
  88. This is free software, and you are welcome to redistribute it under
  89. certain conditions; see <http://www.gnu.org/licenses/> for details.'.N;
  90. for ($i=1; $i<$argc; $i++) {
  91. if (substr($argv[$i],0,1)=='-') {
  92. switch($argv[$i]) {
  93. case '-p':
  94. case '--peersfp':
  95. if ($i+1>=$argc || !file_exists($argv[$i+1]) || !is_file($argv[$i+1]) || !is_readable($argv[$i+1]))
  96. mexit('L’opzione «'.$argv[$i].'» richiede come parametro un file esistente e leggibile (usa «-h» per vedere la guida).'.N,1);
  97. $i++;
  98. $opts['peersfp']=$argv[$i];
  99. break;
  100. case '-t':
  101. case '--timeout':
  102. if ($i+1>=$argc || preg_match('/[0-9]+/',$argv[$i+1])!==1)
  103. mexit('L’opzione «'.$argv[$i].'» richiede un parametro numerico (usa «-h» per vedere la guida).'.N,1);
  104. $i++;
  105. $opts['timeout']=$argv[$i]+0;
  106. break;
  107. case '-l':
  108. case '--log':
  109. $opts['log']=true;
  110. $i++;
  111. break;
  112. case '-j':
  113. case '--jsonwrite':
  114. $opts['jsonwrite']=true;
  115. break;
  116. case '-h':
  117. case '--help':
  118. mexit($help,0);
  119. break;
  120. default:
  121. mexit('L’opzione «'.$argv[$i].'» è sconosciuta (usa «-h» per vedere la guida).'.N,1);
  122. break;
  123. }
  124. }
  125. }
  126. use function mysqli_real_escape_string as myesc;
  127. function mexit($msg,$code) {
  128. global $link, $jsonf, $logf;
  129. lecho($msg);
  130. if ($link)
  131. mysqli_close($link);
  132. if ($jsonf)
  133. fclose($jsonf);
  134. if ($logf)
  135. fclose($logf);
  136. exit($code);
  137. }
  138. function lecho($msg,$logonly=false) {
  139. global $opts, $logf;
  140. if (!$logonly)
  141. echo($msg);
  142. if ($opts['log'] && $logf!==false)
  143. fwrite($logf,$msg);
  144. }
  145. $instsjfp=__DIR__.'/instances.job';
  146. $currinstjfp=__DIR__.'/currinst.job';
  147. if (file_exists($currinstjfp) && file_exists($instsjfp)) {
  148. $riprendi=true;
  149. } else {
  150. $riprendi=false;
  151. }
  152. $logfp=__DIR__.'/crawler.log';
  153. if ($opts['log']) {
  154. if ($riprendi)
  155. $mode=array('a','aggiunta');
  156. else
  157. $mode=array('w','scrittura');
  158. $logf=@fopen($logfp,$mode[0]);
  159. if ($logf===false) {
  160. echo('Non ho potuto aprire in modalità '.$mode[1].' il file di log «'.$logfp.'».'.N);
  161. exit(1);
  162. }
  163. }
  164. $inifp=__DIR__.'/../sec/mustard.ini';
  165. $iniarr=@parse_ini_file($inifp)
  166. or mexit('Impossibile aprire il file di configurazione «'.$inifp.'»'.N,1);
  167. $link=@mysqli_connect($iniarr['db_host'],$iniarr['db_admin_name'],$iniarr['db_admin_password'],$iniarr['db_name'],$iniarr['db_port'],$iniarr['db_socket'])
  168. or mexit('Impossibile connettersi al server MySQL: '.mysqli_connect_error().N,1);
  169. mysqli_set_charset($link,'utf8mb4')
  170. or mexit(__LINE__.': '.mysqli_error($link).N,1);
  171. require(__DIR__.'/../include/tables.php');
  172. $tables=tables($link);
  173. //print_r($tables);
  174. if ($riprendi) {
  175. lecho('Pare che ci sia un lavoro in sospeso, provo a riprenderlo...'.N);
  176. $buf=@file($instsjfp,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)
  177. or mexit('Non ho potuto aprire in lettura il file «'.$instsjfp.'».'.N,1);
  178. $insts=array();
  179. foreach ($buf as $line)
  180. $insts[]=$line;
  181. $buf=@file($currinstjfp,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)
  182. or mexit('Non ho potuto aprire in lettura il file «'.$currinstjfp.'».'.N,1);
  183. $buf=explode("\t",$buf[0]);
  184. $currinst=array('dom'=>$buf[0], 'i'=>$buf[1], 'qok'=>$buf[2], 'qgood'=>$buf[3]);
  185. $riprendi=true;
  186. }
  187. function truncs($str,$tab,$col,$ctx) {
  188. global $tables, $tronconi, $iswin;
  189. if ($iswin)
  190. $tab=strtolower($tab);
  191. $size=$tables[$tab][$col];
  192. $len=mb_strlen($str,'UTF-8');
  193. if ($len>$size) {
  194. notify($ctx.': ho dovuto troncare a '.$size.' caratteri il valore da inserire nella colonna «'.$col.'» della tabella «'.$tab.'» perché troppo lungo ('.$len.' caratteri).',2);
  195. $str=mb_substr($str,0,$size-1,'UTF-8').'…';
  196. }
  197. return($str);
  198. }
  199. function truncn($num,$tab,$col,$ctx) {
  200. global $tables, $iswin;
  201. if ($iswin)
  202. $tab=strtolower($tab);
  203. if (is_numeric($num)) {
  204. if ($num>$tables[$tab][$col]['max']) {
  205. notify($ctx.': ho dovuto troncare «'.$num.'» al valore massimo «'.$tables[$tab][$col]['max'].'» che può avere nella colonna «'.$col.'» della tabella «'.$tab.'»).',2);
  206. $num=$tables[$tab][$col]['max'];
  207. } elseif ($num<$tables[$tab][$col]['min']) {
  208. notify($ctx.': ho dovuto troncare «'.$num.'» al valore minimo «'.$tables[$tab][$col]['min'].'» che può avere nella colonna «'.$col.'» della tabella «'.$tab.'»).',2);
  209. $num=$tables[$tab][$col]['min'];
  210. }
  211. } else {
  212. notify($ctx.': truncn(): mi aspettavo un numero, invece non lo era; ritorno «0».',3);
  213. $num=0;
  214. }
  215. return($num);
  216. }
  217. $contextopts=array(
  218. 'http'=>array(
  219. 'timeout'=>$opts['timeout']
  220. ),
  221. 'socket'=>array(
  222. 'tcp_nodelay'=>true
  223. )
  224. );
  225. $context=stream_context_create($contextopts);
  226. $blacklist=array();
  227. lecho('Carico la blacklist dal database...'.N);
  228. $res=mysqli_query($link,'SELECT * FROM Blacklist')
  229. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  230. lecho(mysqli_num_rows($res).' istanze nella blacklist.'.N);
  231. while($row=mysqli_fetch_assoc($res)) {
  232. $blacklist[$row['Domain']]=$row;
  233. }
  234. function pgdatetomy($pgdate) {
  235. if (preg_match('/^(\d+)-(\d+)-(\d+)[ T]{1}(\d+):(\d+):(\d+)(\.\d+)?Z?$/',$pgdate,$buf)===1) {
  236. $mtime=mktime($buf[4],$buf[5],$buf[6],$buf[2],$buf[3],$buf[1]);
  237. if (array_key_exists(7,$buf))
  238. $mtime=$mtime+floatval('0'.$buf[7]);
  239. return($mtime);
  240. } else {
  241. notify('pgdatetomy: «'.$pgdate.'» non è un formato di data riconosciuto! Ritorno il magico momento attuale.',3);
  242. return(time());
  243. }
  244. }
  245. function blpgdumplinetomy($line) {
  246. $truefalse=array('f'=>0,'t'=>1);
  247. $row=explode("\t",$line);
  248. $row=array('Domain'=>$row[0],
  249. 'CreatedAt'=>pgdatetomy($row[1]),
  250. 'ModifiedAt'=>pgdatetomy($row[2]),
  251. 'Severity'=>$row[3],
  252. 'RejectMedia'=>$truefalse[$row[4]],
  253. 'RejectReports'=>$truefalse[$row[5]],
  254. 'PublicComment'=>$row[6]);
  255. return($row);
  256. }
  257. if (!$riprendi) {
  258. $blacklistnew=array();
  259. $insts=array();
  260. lecho('Carico le istanze di riferimento per le blacklist...'.N);
  261. $res=mysqli_query($link,'SELECT Domain FROM StartNodes')
  262. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  263. lecho(mysqli_num_rows($res).' istanze di riferimento.'.N);
  264. while($row=mysqli_fetch_assoc($res)) {
  265. $insts[]=$row['Domain'];
  266. /*lecho('Recupero la lista delle istanze note a «'.$row['Domain'].'» ... ');
  267. $buf=@file_get_contents('https://'.$row['Domain'].'/api/v1/instance/peers',false,$context);
  268. if ($buf!==false) {
  269. lecho('OK :-)'.N);
  270. $peers=json_decode($buf,true);
  271. foreach ($peers as $pdom) {
  272. if (willtrunc($pdom,'Instances','URI'))
  273. notify('L’istanza «'.$pdom.'» non sarà considerata perché il suo dominio è troppo lungo per il campo «URI» della tabella «Instances» nel DB',2);
  274. if (!in_array($pdom,$insts) && !willtrunc($pdom,'Instances','URI'))
  275. $insts[]=$pdom;
  276. }
  277. } else {
  278. lecho('ERRORE :-('.N);
  279. }*/
  280. lecho('Recupero la blacklist di «'.$row['Domain'].'» ... ');
  281. $buf=@file_get_contents('https://'.$row['Domain'].'/domain_blocks.txt',false,$context);
  282. if ($buf!==false) {
  283. lecho('OK :-)'.N);
  284. $buf=explode(N,$buf);
  285. foreach ($buf as $line) {
  286. if (preg_match('/(^#.*$)|(^\s*$)/',$line)===0) {
  287. $brow=blpgdumplinetomy($line);
  288. if (!array_key_exists($brow['Domain'],$blacklist)) {
  289. $blacklistnew[$brow['Domain']]=$brow;
  290. }
  291. $blacklist[$brow['Domain']]=$brow;
  292. }
  293. }
  294. } else {
  295. lecho('ERRORE :-('.N);
  296. }
  297. }
  298. foreach ($blacklistnew as $row) {
  299. if (!willtrunc($row['Domain'],'Blacklist','Domain')) {
  300. 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']).'\')')
  301. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  302. } else {
  303. lecho('Non ho potuto inserire «'.$row['Domain'].'» nella tabella delle istanze blacklistate perché il dominio è troppo lungo per il campo corrispondente nel DB.',2);
  304. }
  305. }
  306. lecho('Carico le istanze di partenza da «'.$opts['peersfp'].'»...'.N);
  307. $peers=@file($opts['peersfp'],FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
  308. if ($peers===false)
  309. mexit('Non ho potuto aprire in lettura «'.$opts['peersfp'].'».'.N,1);
  310. foreach ($peers as $pdom)
  311. if (!in_array($pdom,$insts))
  312. if (!willtrunc($pdom,'Instances','URI'))
  313. $insts[]=$pdom;
  314. else
  315. lecho('L’istanza «'.$pdom.'» non sarà considerata perché il suo dominio è troppo lungo per il campo «URI» della tabella «Instances» nel DB'.N);
  316. lecho('Carico le istanze note dal DB e aggiungo alla lista di quelle da controllare quelle che non ci sono già.'.N);
  317. $res=mysqli_query($link,'SELECT URI FROM Instances')
  318. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  319. while($row=mysqli_fetch_assoc($res)) {
  320. if (!in_array($row['URI'],$insts))
  321. $insts[]=$row['URI'];
  322. }
  323. sort($insts);
  324. // shuffle($insts);
  325. ksort($blacklist);
  326. ksort($blacklistnew);
  327. lecho('Istanze recuperate: '.count($insts).N);
  328. lecho('Istanze blacklistate: '.count($blacklist).', di cui '.count($blacklistnew).' nuove aggiunte al DB.'.N);
  329. $instsf=@fopen($instsjfp,'w')
  330. or mexit('Non ho potuto aprire in scrittura il file «'.$instsjfp.'».'.N,1);
  331. foreach ($insts as $dom)
  332. fwrite($instsf,$dom.N);
  333. fclose($instsf);
  334. }
  335. function willtrunc($str,$tab,$col) {
  336. global $tables, $iswin;
  337. if ($iswin)
  338. $tab=strtolower($tab);
  339. if (mb_strlen($str,'UTF-8')>$tables[$tab][$col])
  340. return(true);
  341. else
  342. return(false);
  343. }
  344. function b2i($bool,$pre) {
  345. if (is_bool($bool)) {
  346. if ($bool)
  347. return(1);
  348. else
  349. return(0);
  350. } else {
  351. notify($pre.'il valore «'.$bool.'» non è booleano, lo assumo come falso e ritorno «0».',3);
  352. return(0);
  353. }
  354. }
  355. //is array, array key exists and value is not null
  356. function akeavinn($key,&$arr) {
  357. if (is_array($arr) && array_key_exists($key,$arr) && !is_null($arr[$key]))
  358. return(true);
  359. else
  360. return(false);
  361. }
  362. function nempty($str) {
  363. if (preg_match('/^\s*$/',$str)===1)
  364. return(null);
  365. else
  366. return($str);
  367. }
  368. function subarimp($glue,$key,&$arr) {
  369. $str='';
  370. $i=1;
  371. $carr=count($arr);
  372. foreach ($arr as $inarr) {
  373. $str.=$inarr[$key];
  374. if ($i<$carr)
  375. $str.=$glue;
  376. $i++;
  377. }
  378. return($str);
  379. }
  380. function notify($msg,$sev) {
  381. global $link, $tables, $iswin;
  382. lecho('NOTIFICAZIÒ: '.strip_tags($msg).N);
  383. $tab='Notifications';
  384. if ($iswin)
  385. $tab='notifications';
  386. mysqli_query($link,'INSERT INTO Notifications (ID, Notification, Severity, Microtime, Seen) VALUES (NULL, \''.myesc($link,mb_substr($msg,0,$tables[$tab]['Notification'],'UTF-8')).'\', '.$sev.', \''.microtime(true).'\', 0)')
  387. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  388. }
  389. /** <LANGUAGE MANAGEMENT> */
  390. /**
  391. * Effettua una chiamata alla API di Mastodon.
  392. *
  393. * @param string $host L'host da chiamare (e.g.: "mastodon.bida.im")
  394. * @param string $path Il path della API (e.g.: "/api/v1/timelines/public?local=true")
  395. * @return mixed L'oggetto ritornato dalla chiamata, già parsato da json_decode, o NULL se la chiamata fallisce
  396. */
  397. function get_api($host, $path) {
  398. global $context;
  399. try {
  400. $buf = @file_get_contents('https://' . $host . $path, false, $context);
  401. } catch(Exception $e) {
  402. echo "error:";
  403. echo $e;
  404. return NULL;
  405. }
  406. if ($buf!==false) {
  407. $data = json_decode($buf, true);
  408. return $data;
  409. } else {
  410. return NULL;
  411. }
  412. }
  413. /**
  414. * Torna un elenco di linguaggi riconosciuti nel toot fornito con relativa probabilità.
  415. *
  416. * @param mixed $toot Il toot da analizzare, come ritornato dalle API
  417. * @return array Mappa tra codice lingua e probabilità che il toot sia in quella lingua.
  418. */
  419. function get_toot_languages($toot) {
  420. if (is_array($toot) && array_key_exists('language',$toot))
  421. $l = $toot['language'];
  422. else
  423. $l = NULL;
  424. if($l !== NULL) {
  425. // la lingua è specificata già nel toot: usa quella
  426. $langs[$l] = 1;
  427. } else {
  428. // la lingua non è specificata: deducila
  429. $text = strip_tags($toot['content']);
  430. $ld = new Language;
  431. $langs = $ld->detect($text)->bestResults()->close();
  432. }
  433. // raggruppa le lingue derivate, e.g.: "zh" e "zh-CN"
  434. $grouped_langs = array();
  435. foreach($langs as $key => $value) {
  436. $l = explode("-", $key)[0];
  437. if(array_key_exists($l, $grouped_langs)) {
  438. $grouped_langs[$l] = max($grouped_langs[$l], $value);
  439. } else {
  440. $grouped_langs[$l] = $value;
  441. }
  442. }
  443. return $grouped_langs;
  444. }
  445. /**
  446. * Date le probabilità di lingua per ogni toot, calcola la media.
  447. *
  448. * @param array $detected_langs Array di mappe tra lingua e probabilità
  449. * @return array Mappa tra lingua e probabilità
  450. */
  451. function summary($detected_langs) {
  452. $res = Array();
  453. foreach($detected_langs as $langs) {
  454. foreach($langs as $l => $weight) {
  455. if(!array_key_exists($l, $res)) {
  456. $res[$l] = 0;
  457. }
  458. $res[$l] += $weight;
  459. }
  460. }
  461. foreach($res as $l => $sumweight) {
  462. $res[$l] = $sumweight / count($detected_langs);
  463. }
  464. return $res;
  465. }
  466. /**
  467. * Helper function per usort: compara due array usando il primo elemento.
  468. *
  469. * @param array $entry1 Primo array da comparare
  470. * @param array $entry2 Secondo array da comparare
  471. * @return number -1, 0 o 1 a seconda che $entry1[0] sia minore, uguale o superiore a $entry2[0]
  472. */
  473. function sort_weights($entry1, $entry2) {
  474. $w1 = $entry1[0];
  475. $w2 = $entry2[0];
  476. if ($w1 < $w2)
  477. $ret=1;
  478. elseif ($w1 == $w2)
  479. $ret=0;
  480. else
  481. $ret=-1;
  482. return $ret;
  483. }
  484. /**
  485. * Data una mappa di lingue, ritorna una lista di linguaggi considerati probabili.
  486. *
  487. * @param array $summary Mappa tra lingue e probabilità
  488. * @return string[] Elenco di lingue considerate probabili
  489. */
  490. function get_languages($summary) {
  491. $lst = [];
  492. foreach($summary as $code => $weight) {
  493. $lst[] = [$weight, $code];
  494. }
  495. usort($lst, 'sort_weights');
  496. $languages = [];
  497. $lastweight = 0;
  498. foreach($lst as $entry) {
  499. $l = $entry[1];
  500. $weight = $entry[0];
  501. if($weight < $lastweight * 2 / 3) {
  502. break;
  503. }
  504. $languages[] = $l;
  505. $lastweight = $weight;
  506. }
  507. return $languages;
  508. }
  509. /**
  510. * Ritorna una lista di lingue probabili per la data istanza.
  511. *
  512. * @param string $host Hostname dell'istanza (e.g.: "mastodon.bida.im")
  513. * @return string[] Lista di lingue probabili
  514. */
  515. function get_instance_langs($host) {
  516. $data = get_api($host, '/api/v1/timelines/public?local=true');
  517. if($data == NULL) {
  518. return [];
  519. }
  520. $detected_langs = array_map('get_toot_languages', $data);
  521. $summary = summary($detected_langs);
  522. $languages = get_languages($summary);
  523. return $languages;
  524. }
  525. require(__DIR__.'/../include/mb_ucfirst.php');
  526. function langs($instid, $uri, $auto) {
  527. global $info, $instrow, $link;
  528. $retlangs=array();
  529. $languages=array();
  530. if ($auto) {
  531. $languages = get_instance_langs($uri);
  532. } elseif (akeavinn('languages',$info)) {
  533. $languages = $info['languages'];
  534. }
  535. if (count($languages)==0) {
  536. return($retlangs);
  537. } else {
  538. if ($auto)
  539. lecho('Lingue rilevate: '.implode(', ',$languages).N);
  540. else
  541. lecho('Lingue dichiarate: '.implode(', ',$languages).N);
  542. $pos=0;
  543. foreach($languages as $lang) {
  544. $res=mysqli_query($link,'SELECT * FROM Languages WHERE Code=\''.myesc($link,$lang).'\'')
  545. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  546. if (mysqli_num_rows($res)<1) {
  547. $code=myesc($link,truncs($lang,'Languages','Code','«'.$instrow['URI'].'»'));
  548. $NameOrig=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,$lang)),'Languages','NameOrig','«'.$instrow['URI'].'»'));
  549. $NameCa=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,'ca')),'Languages','NameCA','«'.$instrow['URI'].'»'));
  550. $NameEn=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,'en')),'Languages','NameEN','«'.$instrow['URI'].'»'));
  551. $NameEs=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,'es')),'Languages','NameES','«'.$instrow['URI'].'»'));
  552. $NameFr=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,'fr')),'Languages','NameFR','«'.$instrow['URI'].'»'));
  553. $NameIt=myesc($link,truncs(mb_ucfirst(locale_get_display_name($lang,'it')),'Languages','NameIT','«'.$instrow['URI'].'»'));
  554. $q = 'INSERT INTO Languages (ID, Code, NameOrig, NameCA, NameEN, NameES, NameFR, NameIT) VALUES (NULL, \''.$code.'\', \''.$NameOrig.'\', \''.$NameCa.'\', \''.$NameEn.'\', \''.$NameEs.'\', \''.$NameFr.'\', \''.$NameIt.'\')';
  555. mysqli_query($link, $q)
  556. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  557. $langid=mysqli_insert_id($link);
  558. } else {
  559. $row=mysqli_fetch_assoc($res);
  560. $langid=$row['ID'];
  561. }
  562. $pos++;
  563. $retlangs[]=array('InstID'=>$instid,'LangID'=>$langid,'Pos'=>$pos,'Code'=>$lang);
  564. }
  565. }
  566. return($retlangs);
  567. }
  568. function varbdump($var) {
  569. ob_start();
  570. var_dump($var);
  571. $content=ob_get_contents();
  572. ob_end_clean();
  573. return($content);
  574. }
  575. function mdasortbykey(&$arr,$key,$rev=false) {
  576. $karr=array();
  577. foreach ($arr as $akey=>$subarr)
  578. $karr[$subarr[$key]]=array($akey,$subarr);
  579. if (!$rev)
  580. ksort($karr);
  581. else
  582. krsort($karr);
  583. $arr=array();
  584. foreach ($karr as $akey=>$subarr)
  585. $arr[$subarr[0]]=$subarr[1];
  586. }
  587. /*
  588. * Nodeinfo ('https://'.$dom.'/nodeinfo/2.0') è stato aggiunto nella 3.0.0
  589. * Trends ('https://'.$dom.'/api/v1/trends') è stato aggiunto nella 3.0.0
  590. * Activity ('https://'.$dom.'/api/v1/instance/activity') è stato aggiunto nella 2.1.2
  591. */
  592. if ($opts['jsonwrite']) {
  593. if ($riprendi)
  594. $mode=array('a','aggiunta');
  595. else
  596. $mode=array('w','scrittura');
  597. $jsonf=@fopen($opts['jsonfp'],$mode[0])
  598. or mexit('Non ho potuto aprire in modalità '.$mode[1].' il file di dump delle info json «'.$opts['jsonfp'].'».',1);
  599. if ($mode[0]=='w')
  600. fwrite($jsonf,'{'.N);
  601. }
  602. $cinsts=count($insts);
  603. $i=0;
  604. $qok=0;
  605. $qgood=0;
  606. if ($riprendi) {
  607. $i=$currinst['i'];
  608. $qok=$currinst['qok'];
  609. $qgood=$currinst['qgood'];
  610. }
  611. while ($i<$cinsts) {
  612. $dom=$insts[$i];
  613. @file_put_contents($currinstjfp,$dom."\t".$i."\t".$qok."\t".$qgood.N)
  614. or mexit('Non ho potuto aprire in scrittura il file «'.$currinstjfp.'».',1);
  615. $i++;
  616. $ok=true;
  617. $info=null;
  618. lecho('~~~~~~~~~~~~~~~'.N);
  619. lecho('Provo a recuperare info su «'.$dom.'» ['.$i.'/'.$cinsts.' ('.$qok.' OK; '.$qgood.' BUONE) - '.round(100/$cinsts*$i).'%]'.N);
  620. lecho('Provo a recuperare le informazioni API sull’istanza ... ');
  621. $buf=@file_get_contents('https://'.$dom.'/api/v1/instance',false,$context);
  622. if ($buf!==false) {
  623. $info=json_decode($buf,true);
  624. if (is_array($info)) {
  625. lecho('OK :-)'.N);
  626. lecho('Provo a recuperare le informazioni Nodeinfo sull’istanza ... ');
  627. $buf=@file_get_contents('https://'.$dom.'/nodeinfo/2.0',false,$context);
  628. if ($buf!==false) {
  629. lecho('OK :-)'.N);
  630. $info['x-nodeinfo']=json_decode($buf,true);
  631. // per ora teniamo solo quelle che, se si identificano, si identificano come mastodon o corgidon (derivato di mastodon)
  632. // teniamo d'occhio le notifiche di cui sotto per includere eventualmente altri derivati di mastodon?
  633. // visti fin qui, verificare cosa sono: epicyon
  634. 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'])) {
  635. if (preg_match('/^mastodon|corgidon/',$info['x-nodeinfo']['software']['name'])===0)
  636. $ok=false;
  637. $res=mysqli_query($link,'SELECT Name FROM Platforms WHERE Name=\''.myesc($link,$info['x-nodeinfo']['software']['name']).'\'')
  638. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  639. if (mysqli_num_rows($res)<1) {
  640. $res=mysqli_query($link,'INSERT INTO Platforms (Name) VALUES (\''.myesc($link,truncs($info['x-nodeinfo']['software']['name'],'Platforms','Name','«'.$info['uri'].'»')).'\')')
  641. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  642. notify('«'.$info['uri'].'» utilizza come software «'.$info['x-nodeinfo']['software']['name'].'»; l’ho aggiunto 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);
  643. }
  644. }
  645. } else {
  646. lecho('ERRORE :-('.N);
  647. }
  648. if ($ok && array_key_exists('version',$info)) {
  649. if ($info['version']>='2.1.2') {
  650. lecho('Provo a recuperare le informazioni API sull’attività dell’istanza ... ');
  651. $buf=@file_get_contents('https://'.$dom.'/api/v1/instance/activity',false,$context);
  652. if ($buf!==false) {
  653. lecho('OK :-)'.N);
  654. $info['x-activity']=json_decode($buf,true);
  655. } else {
  656. lecho('ERRORE :-('.N);
  657. }
  658. }
  659. if ($info['version']>='3.0.0') {
  660. lecho('Provo a recuperare le informazioni API sui trends dell’istanza ... ');
  661. $buf=@file_get_contents('https://'.$dom.'/api/v1/trends',false,$context);
  662. if ($buf!==false) {
  663. lecho('OK :-)'.N);
  664. $info['x-trends']=json_decode($buf,true);
  665. } else {
  666. lecho('ERRORE :-('.N);
  667. }
  668. }
  669. }
  670. } else {
  671. $ok=false;
  672. lecho('ERRORE :-('.N);
  673. }
  674. } else {
  675. $ok=false;
  676. lecho('ERRORE :-('.N);
  677. // questo è anche il limbo delle istanze che non rispondono, perciò controlliamo se già esistono nel db e, nel caso, aggiorniamo InstChecks
  678. $res=mysqli_query($link,'SELECT * FROM Instances WHERE URI=\''.myesc($link,mb_substr($dom,0,$tables[$iswin ? 'instances' : 'Instances']['URI'],'UTF-8')).'\'')
  679. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  680. if (mysqli_num_rows($res)>0) {
  681. lecho('«'.$dom.'» non risponde, ma è presente nel database; aggiorno InstChecks.'.N);
  682. $row=mysqli_fetch_assoc($res);
  683. mysqli_query($link,'INSERT INTO InstChecks (InstID, Time, Status) VALUES ('.$row['ID'].', '.time().', 0)')
  684. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  685. }
  686. }
  687. if (is_array($info) && count($info)>0) {
  688. lecho('Dumpone json di tutte le info recuperate:'.N.json_encode($info,JSON_PRETTY_PRINT).N,true);
  689. if ($opts['jsonwrite'])
  690. fwrite($jsonf,'"'.$dom.'": '.json_encode($info,JSON_PRETTY_PRINT).','.N);
  691. }
  692. 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'])!==1) {
  693. $qok++;
  694. $instrow=array('ID'=>null, 'FirstSeen'=>null, 'New'=>0, 'Good'=>0, 'Chosen'=>0, 'Visible'=>0, 'Blacklisted'=>0, 'URI'=>null, 'Title'=>null, 'ShortDesc'=>null, 'LongDesc'=>null, 'OurDesc'=>null, 'OurDescEN'=> null, 'LocalityID'=>null, 'OurLangsLock'=>0, '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, 'GuestID'=>null, 'LastGuestEdit'=>null);
  695. if (array_key_exists($info['uri'],$blacklist))
  696. $instrow['Blacklisted']=1;
  697. $instrow['URI']=$info['uri'];
  698. if (akeavinn('title',$info))
  699. $instrow['Title']=nempty(truncs($info['title'],'Instances','Title','«'.$instrow['URI'].'»'));
  700. if (akeavinn('short_description',$info))
  701. $instrow['ShortDesc']=nempty(truncs($info['short_description'],'Instances','ShortDesc','«'.$instrow['URI'].'»'));
  702. if (akeavinn('description',$info))
  703. $instrow['LongDesc']=nempty(truncs($info['description'],'Instances','LongDesc','«'.$instrow['URI'].'»'));
  704. if (akeavinn('email',$info))
  705. $instrow['Email']=nempty(truncs($info['email'],'Instances','Email','«'.$instrow['URI'].'»'));
  706. if (akeavinn('version',$info))
  707. $instrow['Version']=nempty(truncs($info['version'],'Instances','Version','«'.$instrow['URI'].'»'));
  708. if (akeavinn('stats',$info)) {
  709. if (akeavinn('user_count',$info['stats']))
  710. $instrow['UserCount']=truncn($info['stats']['user_count'],'Instances','UserCount','«'.$instrow['URI'].'»');
  711. if (akeavinn('status_count',$info['stats']))
  712. $instrow['StatusCount']=truncn($info['stats']['status_count'],'Instances','StatusCount','«'.$instrow['URI'].'»');
  713. if (akeavinn('domain_count',$info['stats']))
  714. $instrow['DomainCount']=truncn($info['stats']['domain_count'],'Instances','DomainCount','«'.$instrow['URI'].'»');
  715. }
  716. if (akeavinn('thumbnail',$info))
  717. $instrow['Thumb']=nempty(truncs($info['thumbnail'],'Instances','Thumb','«'.$instrow['URI'].'»'));
  718. if (akeavinn('max_toot_chars',$info))
  719. $instrow['MaxTootChars']=truncn($info['max_toot_chars'],'Instances','MaxTootChars','«'.$instrow['URI'].'»');
  720. if (akeavinn('registrations',$info))
  721. $instrow['RegOpen']=b2i($info['registrations'],'Istanza «'.$instrow['URI'].'»: ');
  722. if (akeavinn('approval_required',$info))
  723. $instrow['RegReqApproval']=b2i($info['approval_required'],'Istanza «'.$instrow['URI'].'»: ');
  724. if (akeavinn('contact_account',$info)) {
  725. if (akeavinn('acct',$info['contact_account']))
  726. $instrow['AdmAccount']=nempty(truncs($info['contact_account']['acct'],'Instances','AdmAccount','«'.$instrow['URI'].'»'));
  727. if (akeavinn('display_name',$info['contact_account']))
  728. $instrow['AdmDisplayName']=nempty(truncs($info['contact_account']['display_name'],'Instances','AdmDisplayName','«'.$instrow['URI'].'»'));
  729. if (akeavinn('created_at',$info['contact_account']))
  730. $instrow['AdmCreatedAt']=pgdatetomy($info['contact_account']['created_at']);
  731. if (akeavinn('note',$info['contact_account']))
  732. $instrow['AdmNote']=nempty(truncs(strip_tags($info['contact_account']['note'],'<a>'),'Instances','AdmNote','«'.$instrow['URI'].'»'));
  733. if (akeavinn('url',$info['contact_account']))
  734. $instrow['AdmURL']=nempty(truncs($info['contact_account']['url'],'Instances','AdmURL','«'.$instrow['URI'].'»'));
  735. if (akeavinn('avatar',$info['contact_account']))
  736. $instrow['AdmAvatar']=nempty(truncs($info['contact_account']['avatar'],'Instances','AdmAvatar','«'.$instrow['URI'].'»'));
  737. if (akeavinn('header',$info['contact_account']))
  738. $instrow['AdmHeader']=nempty(truncs($info['contact_account']['header'],'Instances','AdmHeader','«'.$instrow['URI'].'»'));
  739. }
  740. if (akeavinn('x-nodeinfo',$info)) {
  741. if (akeavinn('software',$info['x-nodeinfo']) && akeavinn('name',$info['x-nodeinfo']['software']))
  742. $instrow['Software']=nempty(truncs($info['x-nodeinfo']['software']['name'],'Instances','Software','«'.$instrow['URI'].'»'));
  743. if (akeavinn('usage',$info['x-nodeinfo']) && akeavinn('users',$info['x-nodeinfo']['usage'])) {
  744. if (akeavinn('activeMonth',$info['x-nodeinfo']['usage']['users']))
  745. $instrow['ActiveUsersMonth']=truncn($info['x-nodeinfo']['usage']['users']['activeMonth'],'Instances','ActiveUsersMonth','«'.$instrow['URI'].'»');
  746. if (akeavinn('activeHalfyear',$info['x-nodeinfo']['usage']['users']))
  747. $instrow['ActiveUsersHalfYear']=truncn($info['x-nodeinfo']['usage']['users']['activeHalfyear'],'Instances','ActiveUsersHalfYear','«'.$instrow['URI'].'»');
  748. }
  749. }
  750. $whynot=array();
  751. if ($instrow['Blacklisted']==1)
  752. $whynot[]='è nella blacklist';
  753. if (is_null($instrow['RegOpen'])) {
  754. $whynot[]='non se ne conosce lo stato delle registrazioni (aperte/chiuse)';
  755. } elseif ($instrow['RegOpen']==0) {
  756. $whynot[]='ha le registrazioni chiuse';
  757. }
  758. if (is_null($instrow['UserCount'])) {
  759. $whynot[]='non se ne conosce il numero di utenti';
  760. } elseif ($instrow['UserCount']<10 || $instrow['UserCount']>30000) {
  761. $whynot[]='il numero di utenti non è compreso tra 10 e 30.000';
  762. }
  763. if (is_null($instrow['DomainCount'])) {
  764. $whynot[]='non se ne conosce il numero di istanze note';
  765. } elseif ($instrow['DomainCount']<500) {
  766. $whynot[]='il numero di istanze note è minore di 500';
  767. }
  768. if (!is_null($instrow['ActiveUsersMonth'])) {
  769. if ($instrow['ActiveUsersMonth']<10)
  770. $whynot[]='il numero di utenti attivi nell’ultimo mese è minore di 10';
  771. } elseif (!is_null($instrow['StatusCount']) && $instrow['StatusCount']/$instrow['UserCount']<10) {
  772. $whynot[]='il numero medio di toots per utente è minore di 10';
  773. }
  774. if (count($whynot)==0) {
  775. $instrow['Good']=1;
  776. lecho('Siamo in presenza di un’istanza BUONA! :-)'.N);
  777. $qgood++;
  778. } else {
  779. lecho('Siamo in presenza di un’istanza CATTIVA: '.implode('; ',$whynot).' :-('.N);
  780. }
  781. $res=mysqli_query($link,'SELECT * FROM Instances WHERE URI=\''.myesc($link,$instrow['URI']).'\'')
  782. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  783. if (mysqli_num_rows($res)>0) {
  784. lecho('«'.$instrow['URI'].'» è già presente nel DB, la aggiorno...'.N);
  785. $oldinstrow=mysqli_fetch_assoc($res);
  786. $instid=$oldinstrow['ID'];
  787. $instrow['ID']=$oldinstrow['ID'];
  788. $instrow['FirstSeen']=$oldinstrow['FirstSeen'];
  789. $instrow['New']=$oldinstrow['New'];
  790. if ($instrow['Good']==1 && $oldinstrow['Good']==0) {
  791. notify('L’istanza «<a href="viewinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» non era papabile, ma lo è diventata!',1);
  792. } elseif ($instrow['Good']==0 && $oldinstrow['Good']==1) {
  793. notify('L’istanza «<a href="viewinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» era papabile, ma non lo è più per i seguenti motivi: '.implode('; ',$whynot),3);
  794. }
  795. $instrow['Chosen']=$oldinstrow['Chosen'];
  796. $instrow['Visible']=$oldinstrow['Visible'];
  797. if ($instrow['ShortDesc']!=$oldinstrow['ShortDesc'])
  798. notify('La «Descrizione breve» dell’istanza «<a href="viewinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata.',2);
  799. if ($instrow['LongDesc']!=$oldinstrow['LongDesc'])
  800. notify('La «Descrizione lunga» dell’istanza «<a href="viewinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata.',2);
  801. $instrow['OurDesc']=$oldinstrow['OurDesc'];
  802. $instrow['OurDescEN']=$oldinstrow['OurDescEN'];
  803. $instrow['LocalityID']=$oldinstrow['LocalityID'];
  804. $instrow['OurLangsLock']=$oldinstrow['OurLangsLock'];
  805. $instrow['GuestID']=$oldinstrow['GuestID'];
  806. $instrow['LastGuestEdit']=$oldinstrow['LastGuestEdit'];
  807. $query='UPDATE Instances SET ';
  808. foreach ($instrow as $field=>$value) {
  809. if (!is_null($value))
  810. $query.=$field.'=\''.myesc($link,$value).'\', ';
  811. else
  812. $query.=$field.'=NULL, ';
  813. }
  814. $query=substr($query,0,-2).' WHERE Instances.ID='.$instrow['ID'];
  815. lecho('QUERONA DI UPDATE: «'.$query.'».'.N);
  816. mysqli_query($link,$query)
  817. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  818. $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')
  819. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  820. $oldinstlangs=array();
  821. while ($row=mysqli_fetch_assoc($res))
  822. $oldinstlangs[]=$row;
  823. $instlangs=langs($instrow['ID'], $instrow['URI'], false);
  824. if ($instlangs!=$oldinstlangs) {
  825. notify('La lista delle lingue utilizzate dichiarate dall’istanza «<a href="viewinst.php?id='.$instrow['ID'].'">'.$instrow['URI'].'</a>» è cambiata da «'.subarimp(', ','Code',$oldinstlangs).'» a «'.subarimp(', ','Code',$instlangs).'».',2);
  826. mysqli_query($link,'DELETE FROM InstLangs WHERE InstID='.$instrow['ID'])
  827. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  828. foreach ($instlangs as $row) {
  829. mysqli_query($link,'INSERT INTO InstLangs (InstID, LangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  830. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  831. }
  832. }
  833. if ($instrow['OurLangsLock']==0) {
  834. $instourlangs=langs($instrow['ID'], $instrow['URI'], true);
  835. if (count($instourlangs)>0) {
  836. mysqli_query($link,'DELETE FROM InstLangs WHERE InstID='.$instrow['ID'])
  837. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  838. foreach ($instourlangs as $row) {
  839. mysqli_query($link,'INSERT INTO InstOurLangs (InstID, OurLangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  840. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  841. }
  842. }
  843. }
  844. } else {
  845. lecho('«'.$info['uri'].'» non è già presente nel DB, la aggiungo...'.N);
  846. $instrow['FirstSeen']=time();
  847. $instrow['New']=1;
  848. $fields=array();
  849. $values='';
  850. foreach ($instrow as $field=>$value) {
  851. $fields[]=$field;
  852. if (!is_null($value))
  853. $values.='\''.myesc($link,$value).'\', ';
  854. else
  855. $values.='NULL, ';
  856. }
  857. $values=substr($values,0,-2);
  858. $query='INSERT INTO Instances ('.implode(', ',$fields).') VALUES ('.$values.')';
  859. lecho('QUERONA DI INSERT: «'.$query.'»'.N);
  860. mysqli_query($link,$query)
  861. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  862. $instid=mysqli_insert_id($link);
  863. notify('Ho trovato una nuova istanza: «<a href="viewinst.php?id='.$instid.'">'.$instrow['URI'].'</a>».',1);
  864. $instlangs=langs($instid, $instrow['URI'], false);
  865. foreach ($instlangs as $row) {
  866. mysqli_query($link,'INSERT INTO InstLangs (InstID, LangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  867. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  868. }
  869. $instourlangs=langs($instid, $instrow['URI'], true);
  870. foreach ($instourlangs as $row) {
  871. mysqli_query($link,'INSERT INTO InstOurLangs (InstID, OurLangID, Pos) VALUES ('.$row['InstID'].', '.$row['LangID'].', '.$row['Pos'].')')
  872. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  873. }
  874. if ($instrow['Good']==1)
  875. notify('La nuova istanza «<a href="viewinst.php?id='.$instid.'">'.$instrow['URI'].'</a>» è papabile!',1);
  876. }
  877. if (array_key_exists('x-activity',$info) && is_array($info['x-activity'])) {
  878. mysqli_query($link,'DELETE FROM InstActivity WHERE InstID='.$instid);
  879. $pos=0;
  880. foreach ($info['x-activity'] as $buf) {
  881. if (akeavinn('week',$buf) && akeavinn('statuses',$buf) && akeavinn('logins',$buf) && akeavinn('registrations',$buf)) {
  882. $pos++;
  883. $query='INSERT INTO InstActivity (InstID, Week, Statuses, Logins, Registrations, Pos) VALUES (\''.$instid.'\', \''.myesc($link,$buf['week']).'\', \''.myesc($link,$buf['statuses']).'\', \''.myesc($link,$buf['logins']).'\', \''.myesc($link,$buf['registrations']).'\', '.$pos.')';
  884. mysqli_query($link,$query)
  885. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  886. }
  887. }
  888. }
  889. if (array_key_exists('x-trends',$info) && is_array($info['x-trends'])) {
  890. $trends=array();
  891. foreach ($info['x-trends'] as $buf) {
  892. if (akeavinn('name',$buf) && akeavinn('url',$buf) && akeavinn('history',$buf) && is_array($buf['history'])) {
  893. $trend=0;
  894. foreach ($buf['history'] as $row) {
  895. if ($row['uses']>0)
  896. $trend+=($row['accounts']/$row['uses']);
  897. }
  898. $trends[]=array(
  899. 'InstID'=>$instid,
  900. 'LastDay'=>$buf['history'][0]['day'],
  901. 'Name'=>$buf['name'],
  902. 'URL'=>$buf['url'],
  903. 'Pos'=>null,
  904. 'trend'=>$trend
  905. );
  906. }
  907. }
  908. mdasortbykey($trends,'trend',true);
  909. // print_r($trends);
  910. mysqli_query($link,'DELETE FROM InstTrends WHERE InstID='.$instid);
  911. $pos=0;
  912. foreach ($trends as $trend) {
  913. $pos++;
  914. $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.')';
  915. mysqli_query($link,$query)
  916. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  917. }
  918. }
  919. mysqli_query($link,'INSERT INTO InstChecks (InstID, Time, Status) VALUES ('.$instid.', '.time().', 1)')
  920. or mexit(__LINE__.': '.mysqli_error($link).N,3);
  921. }
  922. }
  923. mysqli_close($link);
  924. if ($opts['jsonwrite']) {
  925. fwrite($jsonf,'"Fine?": true'.N.'}'.N);
  926. fclose($jsonf);
  927. }
  928. unlink($instsjfp);
  929. unlink($currinstjfp);
  930. exit(0);
  931. ?>