StatsDAO.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_StatsDAO extends Minz_ModelPdo {
  4. public const ENTRY_COUNT_PERIOD = 30;
  5. protected function sqlFloor(string $s): string {
  6. return "FLOOR($s)";
  7. }
  8. /**
  9. * Calculates entry repartition for all feeds and for main stream.
  10. *
  11. * @return array{'main_stream':array{'total':int,'count_unreads':int,'count_reads':int,'count_favorites':int}|false,'all_feeds':array{'total':int,'count_unreads':int,'count_reads':int,'count_favorites':int}|false}
  12. */
  13. public function calculateEntryRepartition(): array {
  14. return [
  15. 'main_stream' => $this->calculateEntryRepartitionPerFeed(null, true),
  16. 'all_feeds' => $this->calculateEntryRepartitionPerFeed(null, false),
  17. ];
  18. }
  19. /**
  20. * Calculates entry repartition for the selection.
  21. * The repartition includes:
  22. * - total entries
  23. * - read entries
  24. * - unread entries
  25. * - favorite entries
  26. *
  27. * @return array{total:int,count_unreads:int,count_reads:int,count_favorites:int}|false
  28. */
  29. public function calculateEntryRepartitionPerFeed(?int $feed = null, bool $only_main = false): array|false {
  30. $filter = '';
  31. if ($only_main) {
  32. $filter .= 'AND f.priority = 10';
  33. }
  34. if ($feed !== null) {
  35. $filter .= "AND e.id_feed = {$feed}";
  36. }
  37. $sql = <<<SQL
  38. SELECT COUNT(1) AS total,
  39. COUNT(1) - SUM(e.is_read) AS count_unreads,
  40. SUM(e.is_read) AS count_reads,
  41. SUM(e.is_favorite) AS count_favorites
  42. FROM `_entry` AS e, `_feed` AS f
  43. WHERE e.id_feed = f.id
  44. {$filter}
  45. SQL;
  46. $res = $this->fetchAssoc($sql);
  47. if (is_array($res) && !empty($res[0]) && is_array($res[0])) {
  48. $dao = array_map('intval', $res[0]);
  49. /** @var array{total:int,count_unreads:int,count_reads:int,count_favorites:int} $dao */
  50. return $dao;
  51. }
  52. return false;
  53. }
  54. /**
  55. * Calculates entry count per day on a 30 days period.
  56. * @return array<int,int>
  57. */
  58. public function calculateEntryCount(): array {
  59. $count = $this->initEntryCountArray();
  60. $midnight = mktime(0, 0, 0) ?: 0;
  61. $oldest = $midnight - (self::ENTRY_COUNT_PERIOD * 86400);
  62. // Get stats per day for the last 30 days
  63. $sqlDay = $this->sqlFloor("(date - $midnight) / 86400");
  64. $sql = <<<SQL
  65. SELECT {$sqlDay} AS day,
  66. COUNT(*) as count
  67. FROM `_entry`
  68. WHERE date >= {$oldest} AND date < {$midnight}
  69. GROUP BY day
  70. ORDER BY day ASC
  71. SQL;
  72. $res = $this->fetchAssoc($sql);
  73. if (!is_array($res)) {
  74. return [];
  75. }
  76. /** @var list<array{day:int,count:int}> $res */
  77. foreach ($res as $value) {
  78. $count[(int)($value['day'])] = (int)($value['count']);
  79. }
  80. return $count;
  81. }
  82. /**
  83. * Initialize an array for the entry count.
  84. * @return array<int,int>
  85. */
  86. protected function initEntryCountArray(): array {
  87. return $this->initStatsArray(-self::ENTRY_COUNT_PERIOD, -1);
  88. }
  89. /**
  90. * Calculates the number of article per hour of the day per feed
  91. * @return array<int,int>
  92. */
  93. public function calculateEntryRepartitionPerFeedPerHour(?int $feed = null): array {
  94. return $this->calculateEntryRepartitionPerFeedPerPeriod('%H', $feed);
  95. }
  96. /**
  97. * Calculates the number of article per day of week per feed
  98. * @return array<int,int>
  99. */
  100. public function calculateEntryRepartitionPerFeedPerDayOfWeek(?int $feed = null): array {
  101. return $this->calculateEntryRepartitionPerFeedPerPeriod('%w', $feed);
  102. }
  103. /**
  104. * Calculates the number of article per month per feed
  105. * @return array<int,int>
  106. */
  107. public function calculateEntryRepartitionPerFeedPerMonth(?int $feed = null): array {
  108. $monthRepartition = $this->calculateEntryRepartitionPerFeedPerPeriod('%m', $feed);
  109. // cut out the 0th month (Jan=1, Dec=12)
  110. \array_splice($monthRepartition, 0, 1);
  111. return $monthRepartition;
  112. }
  113. /**
  114. * Calculates the number of article per period per feed
  115. * @param string $period format string to use for grouping
  116. * @return array<int,int>
  117. */
  118. protected function calculateEntryRepartitionPerFeedPerPeriod(string $period, ?int $feed = null): array {
  119. $restrict = '';
  120. if ($feed) {
  121. $restrict = "WHERE e.id_feed = {$feed}";
  122. }
  123. $sql = <<<SQL
  124. SELECT DATE_FORMAT(FROM_UNIXTIME(e.date), '{$period}') AS period
  125. , COUNT(1) AS count
  126. FROM `_entry` AS e
  127. {$restrict}
  128. GROUP BY period
  129. ORDER BY period ASC
  130. SQL;
  131. $res = $this->fetchAssoc($sql);
  132. if ($res == false) {
  133. return [];
  134. }
  135. $periodMax = match ($period) {
  136. '%H' => 24,
  137. '%w' => 7,
  138. '%m' => 12,
  139. default => 30,
  140. };
  141. $repartition = array_fill(0, $periodMax, 0);
  142. foreach ($res as $value) {
  143. $repartition[(int)$value['period']] = (int)$value['count'];
  144. }
  145. return $repartition;
  146. }
  147. /**
  148. * Calculates the average number of article per hour per feed
  149. */
  150. public function calculateEntryAveragePerFeedPerHour(?int $feed = null): float {
  151. return $this->calculateEntryAveragePerFeedPerPeriod(1 / 24, $feed);
  152. }
  153. /**
  154. * Calculates the average number of article per day of week per feed
  155. */
  156. public function calculateEntryAveragePerFeedPerDayOfWeek(?int $feed = null): float {
  157. return $this->calculateEntryAveragePerFeedPerPeriod(7, $feed);
  158. }
  159. /**
  160. * Calculates the average number of article per month per feed
  161. */
  162. public function calculateEntryAveragePerFeedPerMonth(?int $feed = null): float {
  163. return $this->calculateEntryAveragePerFeedPerPeriod(30, $feed);
  164. }
  165. /**
  166. * Calculates the average number of article per feed
  167. * @param float $period number used to divide the number of day in the period
  168. */
  169. protected function calculateEntryAveragePerFeedPerPeriod(float $period, ?int $feed = null): float {
  170. $restrict = '';
  171. if ($feed) {
  172. $restrict = "WHERE e.id_feed = {$feed}";
  173. }
  174. $sql = <<<SQL
  175. SELECT COUNT(1) AS count
  176. , MIN(date) AS date_min
  177. , MAX(date) AS date_max
  178. FROM `_entry` AS e
  179. {$restrict}
  180. SQL;
  181. $res = $this->fetchAssoc($sql);
  182. if ($res == null || empty($res[0])) {
  183. return -1.0;
  184. }
  185. $date_min = new \DateTime();
  186. $date_min->setTimestamp((int)($res[0]['date_min']));
  187. $date_max = new \DateTime();
  188. $date_max->setTimestamp((int)($res[0]['date_max']));
  189. $interval = $date_max->diff($date_min, true);
  190. $interval_in_days = (float)($interval->format('%a'));
  191. if ($interval_in_days <= 0) {
  192. // Surely only one article.
  193. // We will return count / (period/period) == count.
  194. $interval_in_days = $period;
  195. }
  196. return (int)$res[0]['count'] / ($interval_in_days / $period);
  197. }
  198. /**
  199. * Initialize an array for statistics depending on a range
  200. * @return array<int,int>
  201. */
  202. protected function initStatsArray(int $min, int $max): array {
  203. return array_map(fn() => 0, array_flip(range($min, $max)));
  204. }
  205. /**
  206. * Calculates feed count per category.
  207. * @return list<array{'label':string,'data':int}>
  208. */
  209. public function calculateFeedByCategory(): array {
  210. $sql = <<<SQL
  211. SELECT c.name AS label
  212. , COUNT(f.id) AS data
  213. FROM `_category` AS c, `_feed` AS f
  214. WHERE c.id = f.category
  215. GROUP BY label
  216. ORDER BY data DESC
  217. SQL;
  218. /** @var list<array{'label':string,'data':int}>|null @res */
  219. $res = $this->fetchAssoc($sql);
  220. return $res == null ? [] : $res;
  221. }
  222. /**
  223. * Calculates entry count per category.
  224. * @return list<array{'label':string,'data':int}>
  225. */
  226. public function calculateEntryByCategory(): array {
  227. $sql = <<<SQL
  228. SELECT c.name AS label
  229. , COUNT(e.id) AS data
  230. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  231. WHERE c.id = f.category
  232. AND f.id = e.id_feed
  233. GROUP BY label
  234. ORDER BY data DESC
  235. SQL;
  236. $res = $this->fetchAssoc($sql);
  237. /** @var list<array{'label':string,'data':int}>|null $res */
  238. return $res == null ? [] : $res;
  239. }
  240. /**
  241. * Calculates the 10 top feeds based on their number of entries
  242. * @return list<array{'id':int,'name':string,'category':string,'count':int}>
  243. */
  244. public function calculateTopFeed(): array {
  245. $sql = <<<SQL
  246. SELECT f.id AS id
  247. , MAX(f.name) AS name
  248. , MAX(c.name) AS category
  249. , COUNT(e.id) AS count
  250. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  251. WHERE c.id = f.category
  252. AND f.id = e.id_feed
  253. GROUP BY f.id
  254. ORDER BY count DESC
  255. LIMIT 10
  256. SQL;
  257. $res = $this->fetchAssoc($sql);
  258. /** @var list<array{'id':int,'name':string,'category':string,'count':int}>|null $res */
  259. if (is_array($res)) {
  260. return $res;
  261. }
  262. return [];
  263. }
  264. /**
  265. * Calculates the last publication date for each feed
  266. * @return list<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>
  267. */
  268. public function calculateFeedLastDate(): array {
  269. $sql = <<<SQL
  270. SELECT MAX(f.id) as id
  271. , MAX(f.name) AS name
  272. , MAX(date) AS last_date
  273. , COUNT(*) AS nb_articles
  274. FROM `_feed` AS f, `_entry` AS e
  275. WHERE f.id = e.id_feed
  276. GROUP BY f.id
  277. ORDER BY name
  278. SQL;
  279. $res = $this->fetchAssoc($sql);
  280. /** @var list<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>|null $res */
  281. if (is_array($res)) {
  282. return $res;
  283. }
  284. return [];
  285. }
  286. /**
  287. * Gets days ready for graphs
  288. * @return list<string>
  289. */
  290. public function getDays(): array {
  291. return $this->convertToTranslatedJson([
  292. 'sun',
  293. 'mon',
  294. 'tue',
  295. 'wed',
  296. 'thu',
  297. 'fri',
  298. 'sat',
  299. ]);
  300. }
  301. /**
  302. * Gets months ready for graphs
  303. * @return list<string>
  304. */
  305. public function getMonths(): array {
  306. return $this->convertToTranslatedJson([
  307. 'jan',
  308. 'feb',
  309. 'mar',
  310. 'apr',
  311. 'may_',
  312. 'jun',
  313. 'jul',
  314. 'aug',
  315. 'sep',
  316. 'oct',
  317. 'nov',
  318. 'dec',
  319. ]);
  320. }
  321. /**
  322. * Translates array content
  323. * @param list<string> $data
  324. * @return list<string>
  325. */
  326. private function convertToTranslatedJson(array $data = []): array {
  327. $translated = array_map(static fn(string $a) => _t('gen.date.' . $a), $data);
  328. return $translated;
  329. }
  330. }