crawler.php 38 KB

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