StatsDAO.php 9.2 KB

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