StatsDAO.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 intval($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(function () {
  212. return 0;
  213. }, array_flip(range($min, $max)));
  214. }
  215. /**
  216. * Calculates feed count per category.
  217. * @return array<array{'label':string,'data':int}>
  218. */
  219. public function calculateFeedByCategory(): array {
  220. $sql = <<<SQL
  221. SELECT c.name AS label
  222. , COUNT(f.id) AS data
  223. FROM `_category` AS c, `_feed` AS f
  224. WHERE c.id = f.category
  225. GROUP BY label
  226. ORDER BY data DESC
  227. SQL;
  228. /** @var array<array{'label':string,'data':int}>|null @res */
  229. $res = $this->fetchAssoc($sql);
  230. return $res == null ? [] : $res;
  231. }
  232. /**
  233. * Calculates entry count per category.
  234. * @return array<array{'label':string,'data':int}>
  235. */
  236. public function calculateEntryByCategory(): array {
  237. $sql = <<<SQL
  238. SELECT c.name AS label
  239. , COUNT(e.id) AS data
  240. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  241. WHERE c.id = f.category
  242. AND f.id = e.id_feed
  243. GROUP BY label
  244. ORDER BY data DESC
  245. SQL;
  246. $res = $this->fetchAssoc($sql);
  247. /** @var array<array{'label':string,'data':int}>|null $res */
  248. return $res == null ? [] : $res;
  249. }
  250. /**
  251. * Calculates the 10 top feeds based on their number of entries
  252. * @return array<array{'id':int,'name':string,'category':string,'count':int}>
  253. */
  254. public function calculateTopFeed(): array {
  255. $sql = <<<SQL
  256. SELECT f.id AS id
  257. , MAX(f.name) AS name
  258. , MAX(c.name) AS category
  259. , COUNT(e.id) AS count
  260. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  261. WHERE c.id = f.category
  262. AND f.id = e.id_feed
  263. GROUP BY f.id
  264. ORDER BY count DESC
  265. LIMIT 10
  266. SQL;
  267. $res = $this->fetchAssoc($sql);
  268. /** @var array<array{'id':int,'name':string,'category':string,'count':int}>|null $res */
  269. if (is_array($res)) {
  270. foreach ($res as &$dao) {
  271. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'count']);
  272. }
  273. return $res;
  274. }
  275. return [];
  276. }
  277. /**
  278. * Calculates the last publication date for each feed
  279. * @return array<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>
  280. */
  281. public function calculateFeedLastDate(): array {
  282. $sql = <<<SQL
  283. SELECT MAX(f.id) as id
  284. , MAX(f.name) AS name
  285. , MAX(date) AS last_date
  286. , COUNT(*) AS nb_articles
  287. FROM `_feed` AS f, `_entry` AS e
  288. WHERE f.id = e.id_feed
  289. GROUP BY f.id
  290. ORDER BY name
  291. SQL;
  292. $res = $this->fetchAssoc($sql);
  293. /** @var array<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>|null $res */
  294. if (is_array($res)) {
  295. foreach ($res as &$dao) {
  296. FreshRSS_DatabaseDAO::pdoInt($dao, ['id', 'last_date', 'nb_articles']);
  297. }
  298. return $res;
  299. }
  300. return [];
  301. }
  302. /**
  303. * Gets days ready for graphs
  304. * @return array<string>
  305. */
  306. public function getDays(): array {
  307. return $this->convertToTranslatedJson([
  308. 'sun',
  309. 'mon',
  310. 'tue',
  311. 'wed',
  312. 'thu',
  313. 'fri',
  314. 'sat',
  315. ]);
  316. }
  317. /**
  318. * Gets months ready for graphs
  319. * @return array<string>
  320. */
  321. public function getMonths(): array {
  322. return $this->convertToTranslatedJson([
  323. 'jan',
  324. 'feb',
  325. 'mar',
  326. 'apr',
  327. 'may_',
  328. 'jun',
  329. 'jul',
  330. 'aug',
  331. 'sep',
  332. 'oct',
  333. 'nov',
  334. 'dec',
  335. ]);
  336. }
  337. /**
  338. * Translates array content
  339. * @param array<string> $data
  340. * @return array<string>
  341. */
  342. private function convertToTranslatedJson(array $data = []): array {
  343. $translated = array_map(static function (string $a) {
  344. return _t('gen.date.' . $a);
  345. }, $data);
  346. return $translated;
  347. }
  348. }