StatsDAO.php 9.4 KB

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