StatsDAO.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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) {
  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. switch ($period) {
  137. case '%H':
  138. $periodMax = 24;
  139. break;
  140. case '%w':
  141. $periodMax = 7;
  142. break;
  143. case '%m':
  144. $periodMax = 12;
  145. break;
  146. default:
  147. $periodMax = 30;
  148. }
  149. $repartition = array_fill(0, $periodMax, 0);
  150. foreach ($res as $value) {
  151. $repartition[(int)$value['period']] = (int)$value['count'];
  152. }
  153. return $repartition;
  154. }
  155. /**
  156. * Calculates the average number of article per hour per feed
  157. */
  158. public function calculateEntryAveragePerFeedPerHour(?int $feed = null): float {
  159. return $this->calculateEntryAveragePerFeedPerPeriod(1 / 24, $feed);
  160. }
  161. /**
  162. * Calculates the average number of article per day of week per feed
  163. */
  164. public function calculateEntryAveragePerFeedPerDayOfWeek(?int $feed = null): float {
  165. return $this->calculateEntryAveragePerFeedPerPeriod(7, $feed);
  166. }
  167. /**
  168. * Calculates the average number of article per month per feed
  169. */
  170. public function calculateEntryAveragePerFeedPerMonth(?int $feed = null): float {
  171. return $this->calculateEntryAveragePerFeedPerPeriod(30, $feed);
  172. }
  173. /**
  174. * Calculates the average number of article per feed
  175. * @param float $period number used to divide the number of day in the period
  176. */
  177. protected function calculateEntryAveragePerFeedPerPeriod(float $period, ?int $feed = null): float {
  178. $restrict = '';
  179. if ($feed) {
  180. $restrict = "WHERE e.id_feed = {$feed}";
  181. }
  182. $sql = <<<SQL
  183. SELECT COUNT(1) AS count
  184. , MIN(date) AS date_min
  185. , MAX(date) AS date_max
  186. FROM `_entry` AS e
  187. {$restrict}
  188. SQL;
  189. $res = $this->fetchAssoc($sql);
  190. if ($res == null || empty($res[0])) {
  191. return -1.0;
  192. }
  193. $date_min = new \DateTime();
  194. $date_min->setTimestamp((int)($res[0]['date_min']));
  195. $date_max = new \DateTime();
  196. $date_max->setTimestamp((int)($res[0]['date_max']));
  197. $interval = $date_max->diff($date_min, true);
  198. $interval_in_days = (float)($interval->format('%a'));
  199. if ($interval_in_days <= 0) {
  200. // Surely only one article.
  201. // We will return count / (period/period) == count.
  202. $interval_in_days = $period;
  203. }
  204. return (int)$res[0]['count'] / ($interval_in_days / $period);
  205. }
  206. /**
  207. * Initialize an array for statistics depending on a range
  208. * @return array<int,int>
  209. */
  210. protected function initStatsArray(int $min, int $max): array {
  211. return array_map(fn() => 0, array_flip(range($min, $max)));
  212. }
  213. /**
  214. * Calculates feed count per category.
  215. * @return array<array{'label':string,'data':int}>
  216. */
  217. public function calculateFeedByCategory(): array {
  218. $sql = <<<SQL
  219. SELECT c.name AS label
  220. , COUNT(f.id) AS data
  221. FROM `_category` AS c, `_feed` AS f
  222. WHERE c.id = f.category
  223. GROUP BY label
  224. ORDER BY data DESC
  225. SQL;
  226. /** @var array<array{'label':string,'data':int}>|null @res */
  227. $res = $this->fetchAssoc($sql);
  228. return $res == null ? [] : $res;
  229. }
  230. /**
  231. * Calculates entry count per category.
  232. * @return array<array{'label':string,'data':int}>
  233. */
  234. public function calculateEntryByCategory(): array {
  235. $sql = <<<SQL
  236. SELECT c.name AS label
  237. , COUNT(e.id) AS data
  238. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  239. WHERE c.id = f.category
  240. AND f.id = e.id_feed
  241. GROUP BY label
  242. ORDER BY data DESC
  243. SQL;
  244. $res = $this->fetchAssoc($sql);
  245. /** @var array<array{'label':string,'data':int}>|null $res */
  246. return $res == null ? [] : $res;
  247. }
  248. /**
  249. * Calculates the 10 top feeds based on their number of entries
  250. * @return array<array{'id':int,'name':string,'category':string,'count':int}>
  251. */
  252. public function calculateTopFeed(): array {
  253. $sql = <<<SQL
  254. SELECT f.id AS id
  255. , MAX(f.name) AS name
  256. , MAX(c.name) AS category
  257. , COUNT(e.id) AS count
  258. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  259. WHERE c.id = f.category
  260. AND f.id = e.id_feed
  261. GROUP BY f.id
  262. ORDER BY count DESC
  263. LIMIT 10
  264. SQL;
  265. $res = $this->fetchAssoc($sql);
  266. /** @var array<array{'id':int,'name':string,'category':string,'count':int}>|null $res */
  267. if (is_array($res)) {
  268. foreach ($res as &$dao) {
  269. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'count']);
  270. }
  271. return $res;
  272. }
  273. return [];
  274. }
  275. /**
  276. * Calculates the last publication date for each feed
  277. * @return array<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>
  278. */
  279. public function calculateFeedLastDate(): array {
  280. $sql = <<<SQL
  281. SELECT MAX(f.id) as id
  282. , MAX(f.name) AS name
  283. , MAX(date) AS last_date
  284. , COUNT(*) AS nb_articles
  285. FROM `_feed` AS f, `_entry` AS e
  286. WHERE f.id = e.id_feed
  287. GROUP BY f.id
  288. ORDER BY name
  289. SQL;
  290. $res = $this->fetchAssoc($sql);
  291. /** @var array<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>|null $res */
  292. if (is_array($res)) {
  293. foreach ($res as &$dao) {
  294. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'last_date', 'nb_articles']);
  295. }
  296. return $res;
  297. }
  298. return [];
  299. }
  300. /**
  301. * Gets days ready for graphs
  302. * @return array<string>
  303. */
  304. public function getDays(): array {
  305. return $this->convertToTranslatedJson([
  306. 'sun',
  307. 'mon',
  308. 'tue',
  309. 'wed',
  310. 'thu',
  311. 'fri',
  312. 'sat',
  313. ]);
  314. }
  315. /**
  316. * Gets months ready for graphs
  317. * @return array<string>
  318. */
  319. public function getMonths(): array {
  320. return $this->convertToTranslatedJson([
  321. 'jan',
  322. 'feb',
  323. 'mar',
  324. 'apr',
  325. 'may_',
  326. 'jun',
  327. 'jul',
  328. 'aug',
  329. 'sep',
  330. 'oct',
  331. 'nov',
  332. 'dec',
  333. ]);
  334. }
  335. /**
  336. * Translates array content
  337. * @param array<string> $data
  338. * @return array<string>
  339. */
  340. private function convertToTranslatedJson(array $data = []): array {
  341. $translated = array_map(static fn(string $a) => _t('gen.date.' . $a), $data);
  342. return $translated;
  343. }
  344. }