crawler.php 36 KB

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