4
0

StatsDAO.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_StatsDAO extends Minz_ModelPdo {
  4. public const ENTRY_COUNT_PERIOD = 30;
  5. /** Get the number of seconds to add to UTC to get the user's local time */
  6. protected function getTimezoneOffset(): int {
  7. $timezone = new DateTimeZone(date_default_timezone_get());
  8. return $timezone->getOffset(new DateTime('now', new DateTimeZone('UTC')));
  9. }
  10. /**
  11. * @param string $field to use for the date
  12. * @param int $precision to apply to the timestamp (1 for seconds, 1000 for milliseconds, 1000000 for microseconds)
  13. * @param 'day'|'month'|'year' $granularity of the date intervals
  14. */
  15. protected function sqlDateToIsoGranularity(string $field, int $precision, string $granularity): string {
  16. if (!preg_match('/^[a-zA-Z0-9_.]+$/', $field)) {
  17. throw new InvalidArgumentException('Invalid date field!');
  18. }
  19. $offset = $this->getTimezoneOffset();
  20. return match ($granularity) {
  21. 'day' => "FROM_UNIXTIME(($field / $precision) + $offset, '%Y-%m-%d')",
  22. 'month' => "FROM_UNIXTIME(($field / $precision) + $offset, '%Y-%m')",
  23. 'year' => "FROM_UNIXTIME(($field / $precision) + $offset, '%Y')",
  24. default => throw new InvalidArgumentException('Invalid date granularity!'),
  25. };
  26. }
  27. protected function sqlFloor(string $s): string {
  28. return "FLOOR($s)";
  29. }
  30. /**
  31. * Calculates entry repartition for all feeds and for main stream.
  32. *
  33. * @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}
  34. */
  35. public function calculateEntryRepartition(): array {
  36. return [
  37. 'main_stream' => $this->calculateEntryRepartitionPerFeed(null, true),
  38. 'all_feeds' => $this->calculateEntryRepartitionPerFeed(null, false),
  39. ];
  40. }
  41. /**
  42. * Calculates entry repartition for the selection.
  43. * The repartition includes:
  44. * - total entries
  45. * - read entries
  46. * - unread entries
  47. * - favorite entries
  48. *
  49. * @return array{total:int,count_unreads:int,count_reads:int,count_favorites:int}|false
  50. */
  51. public function calculateEntryRepartitionPerFeed(?int $feed = null, bool $only_main = false): array|false {
  52. $filter = '';
  53. if ($only_main) {
  54. $filter .= 'AND f.priority = 10';
  55. }
  56. if ($feed !== null) {
  57. $filter .= "AND e.id_feed = {$feed}";
  58. }
  59. $sql = <<<SQL
  60. SELECT COUNT(1) AS total,
  61. COUNT(1) - SUM(e.is_read) AS count_unreads,
  62. SUM(e.is_read) AS count_reads,
  63. SUM(e.is_favorite) AS count_favorites
  64. FROM `_entry` AS e, `_feed` AS f
  65. WHERE e.id_feed = f.id
  66. {$filter}
  67. SQL;
  68. $res = $this->fetchAssoc($sql);
  69. if (is_array($res) && !empty($res[0]) && is_array($res[0])) {
  70. $dao = array_map('intval', $res[0]);
  71. /** @var array{total:int,count_unreads:int,count_reads:int,count_favorites:int} $dao */
  72. return $dao;
  73. }
  74. return false;
  75. }
  76. /**
  77. * Calculates entry count per day on a 30 days period.
  78. * @return array<int,int>
  79. */
  80. public function calculateEntryCount(): array {
  81. $count = $this->initEntryCountArray();
  82. $midnight = mktime(0, 0, 0) ?: 0;
  83. $oldest = $midnight - (self::ENTRY_COUNT_PERIOD * 86400);
  84. $endOfDay = $midnight + 86400;
  85. // Get stats per day for the last 30 days, including today.
  86. // The reference is the oldest timestamp so that the division is always positive (and thus floors correctly with integer division).
  87. $sqlDay = $this->sqlFloor("(date - $oldest) / 86400");
  88. $sql = <<<SQL
  89. SELECT {$sqlDay} AS day,
  90. COUNT(*) as count
  91. FROM `_entry`
  92. WHERE date >= {$oldest} AND date < {$endOfDay}
  93. GROUP BY day
  94. ORDER BY day ASC
  95. SQL;
  96. $res = $this->fetchAssoc($sql);
  97. if (!is_array($res)) {
  98. return [];
  99. }
  100. /** @var list<array{day:int,count:int}> $res */
  101. foreach ($res as $value) {
  102. $count[(int)($value['day'])] = (int)($value['count']);
  103. }
  104. // Return a list so that JSON encoding produces an array and not an object.
  105. return array_values($count);
  106. }
  107. /**
  108. * Initialize an array for the entry count.
  109. * @return array<int,int>
  110. */
  111. protected function initEntryCountArray(): array {
  112. return $this->initStatsArray(0, self::ENTRY_COUNT_PERIOD);
  113. }
  114. /**
  115. * Calculates the number of article per hour of the day per feed
  116. * @return array<int,int>
  117. */
  118. public function calculateEntryRepartitionPerFeedPerHour(?int $feed = null): array {
  119. return $this->calculateEntryRepartitionPerFeedPerPeriod('%H', $feed);
  120. }
  121. /**
  122. * Calculates the number of article per day of week per feed
  123. * @return array<int,int>
  124. */
  125. public function calculateEntryRepartitionPerFeedPerDayOfWeek(?int $feed = null): array {
  126. return $this->calculateEntryRepartitionPerFeedPerPeriod('%w', $feed);
  127. }
  128. /**
  129. * Calculates the number of article per month per feed
  130. * @return array<int,int>
  131. */
  132. public function calculateEntryRepartitionPerFeedPerMonth(?int $feed = null): array {
  133. $monthRepartition = $this->calculateEntryRepartitionPerFeedPerPeriod('%m', $feed);
  134. return $this->normalizeMonthRepartition($monthRepartition);
  135. }
  136. /**
  137. * Normalize a month repartition so that it always contains 12 entries indexed from 0 (January) to 11 (December).
  138. * @param array<int,int> $repartition
  139. * @return array<int,int>
  140. */
  141. protected function normalizeMonthRepartition(array $repartition): array {
  142. $months = array_fill(0, 12, 0);
  143. foreach ($repartition as $month => $count) {
  144. if ($month >= 1 && $month <= 12) {
  145. $months[$month - 1] = $count;
  146. }
  147. }
  148. return $months;
  149. }
  150. /**
  151. * Calculates the number of article per period per feed
  152. * @param string $period format string to use for grouping
  153. * @return array<int,int>
  154. */
  155. protected function calculateEntryRepartitionPerFeedPerPeriod(string $period, ?int $feed = null): array {
  156. $restrict = '';
  157. if ($feed) {
  158. $restrict = "WHERE e.id_feed = {$feed}";
  159. }
  160. $offset = $this->getTimezoneOffset();
  161. $sql = <<<SQL
  162. SELECT DATE_FORMAT(FROM_UNIXTIME(e.date + {$offset}), '{$period}') AS period, COUNT(1) AS count
  163. FROM `_entry` AS e
  164. {$restrict}
  165. GROUP BY period
  166. ORDER BY period ASC
  167. SQL;
  168. $res = $this->fetchAssoc($sql);
  169. if (empty($res)) {
  170. return [];
  171. }
  172. $periodMax = match ($period) {
  173. '%H' => 24,
  174. '%w' => 7,
  175. '%m' => 12,
  176. default => 30,
  177. };
  178. $repartition = array_fill(0, $periodMax, 0);
  179. foreach ($res as $value) {
  180. $repartition[(int)$value['period']] = (int)$value['count'];
  181. }
  182. return $repartition;
  183. }
  184. /**
  185. * Calculates the average number of article per hour per feed
  186. */
  187. public function calculateEntryAveragePerFeedPerHour(?int $feed = null): float {
  188. return $this->calculateEntryAveragePerFeedPerPeriod(1 / 24, $feed);
  189. }
  190. /**
  191. * Calculates the average number of article per day of week per feed
  192. */
  193. public function calculateEntryAveragePerFeedPerDayOfWeek(?int $feed = null): float {
  194. return $this->calculateEntryAveragePerFeedPerPeriod(7, $feed);
  195. }
  196. /**
  197. * Calculates the average number of article per month per feed
  198. */
  199. public function calculateEntryAveragePerFeedPerMonth(?int $feed = null): float {
  200. return $this->calculateEntryAveragePerFeedPerPeriod(30, $feed);
  201. }
  202. /**
  203. * Calculates the average number of articles from an entry repartition.
  204. * @param array<int,int> $repartition
  205. */
  206. public static function calculateEntryAverageFromRepartition(array $repartition): float {
  207. return empty($repartition) ? 0.0 : array_sum($repartition) / count($repartition);
  208. }
  209. /**
  210. * Calculates the average number of article per feed
  211. * @param float $period number used to divide the number of day in the period
  212. */
  213. protected function calculateEntryAveragePerFeedPerPeriod(float $period, ?int $feed = null): float {
  214. $restrict = '';
  215. if ($feed) {
  216. $restrict = "WHERE e.id_feed = {$feed}";
  217. }
  218. $sql = <<<SQL
  219. SELECT COUNT(1) AS count, MIN(date) AS date_min, MAX(date) AS date_max
  220. FROM `_entry` AS e
  221. {$restrict}
  222. SQL;
  223. $res = $this->fetchAssoc($sql);
  224. if ($res == null || empty($res[0])) {
  225. return -1.0;
  226. }
  227. $date_min = new \DateTime();
  228. $date_min->setTimestamp((int)($res[0]['date_min']));
  229. $date_max = new \DateTime();
  230. $date_max->setTimestamp((int)($res[0]['date_max']));
  231. $interval = $date_max->diff($date_min, true);
  232. $interval_in_days = (float)($interval->format('%a'));
  233. if ($interval_in_days <= 0) {
  234. // Surely only one article.
  235. // We will return count / (period/period) == count.
  236. $interval_in_days = $period;
  237. }
  238. return (int)$res[0]['count'] / ($interval_in_days / $period);
  239. }
  240. /**
  241. * Initialize an array for statistics depending on a range
  242. * @return array<int,int>
  243. */
  244. protected function initStatsArray(int $min, int $max): array {
  245. return array_map(fn() => 0, array_flip(range($min, $max)));
  246. }
  247. /**
  248. * Calculates feed count per category.
  249. * @return list<array{'label':string,'data':int}>
  250. */
  251. public function calculateFeedByCategory(): array {
  252. $sql = <<<'SQL'
  253. SELECT c.name AS label, COUNT(f.id) AS data
  254. FROM `_category` AS c, `_feed` AS f
  255. WHERE c.id = f.category
  256. GROUP BY label
  257. ORDER BY data DESC
  258. SQL;
  259. /** @var list<array{'label':string,'data':int}>|null $res */
  260. $res = $this->fetchAssoc($sql);
  261. return $res == null ? [] : $res;
  262. }
  263. /**
  264. * Calculates entry count per category.
  265. * @return list<array{'label':string,'data':int}>
  266. */
  267. public function calculateEntryByCategory(): array {
  268. $sql = <<<'SQL'
  269. SELECT c.name AS label, COUNT(e.id) AS data
  270. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  271. WHERE c.id = f.category
  272. AND f.id = e.id_feed
  273. GROUP BY label
  274. ORDER BY data DESC
  275. SQL;
  276. $res = $this->fetchAssoc($sql);
  277. /** @var list<array{'label':string,'data':int}>|null $res */
  278. return $res == null ? [] : $res;
  279. }
  280. /**
  281. * Calculates the 10 top feeds based on their number of entries
  282. * @return list<array{'id':int,'name':string,'category':string,'count':int}>
  283. */
  284. public function calculateTopFeed(): array {
  285. $sql = <<<'SQL'
  286. SELECT f.id AS id, MAX(f.name) AS name, MAX(c.name) AS category, COUNT(e.id) AS count
  287. FROM `_category` AS c, `_feed` AS f, `_entry` AS e
  288. WHERE c.id = f.category
  289. AND f.id = e.id_feed
  290. GROUP BY f.id
  291. ORDER BY count DESC
  292. LIMIT 10
  293. SQL;
  294. $res = $this->fetchAssoc($sql);
  295. /** @var list<array{'id':int,'name':string,'category':string,'count':int}>|null $res */
  296. if (is_array($res)) {
  297. return $res;
  298. }
  299. return [];
  300. }
  301. /**
  302. * Calculates the last publication date for each feed
  303. * @return list<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>
  304. */
  305. public function calculateFeedLastDate(): array {
  306. $sql = <<<'SQL'
  307. SELECT MAX(f.id) as id, MAX(f.name) AS name, MAX(date) AS last_date, COUNT(*) AS nb_articles
  308. FROM `_feed` AS f, `_entry` AS e
  309. WHERE f.id = e.id_feed
  310. GROUP BY f.id
  311. ORDER BY name
  312. SQL;
  313. $res = $this->fetchAssoc($sql);
  314. /** @var list<array{'id':int,'name':string,'last_date':int,'nb_articles':int}>|null $res */
  315. if (is_array($res)) {
  316. return $res;
  317. }
  318. return [];
  319. }
  320. /**
  321. * Gets days ready for graphs
  322. * @return list<string>
  323. */
  324. public function getDays(): array {
  325. return $this->convertToTranslatedJson([
  326. 'sun',
  327. 'mon',
  328. 'tue',
  329. 'wed',
  330. 'thu',
  331. 'fri',
  332. 'sat',
  333. ]);
  334. }
  335. /**
  336. * Gets months ready for graphs
  337. * @return list<string>
  338. */
  339. public function getMonths(): array {
  340. return $this->convertToTranslatedJson([
  341. 'jan',
  342. 'feb',
  343. 'mar',
  344. 'apr',
  345. 'may_',
  346. 'jun',
  347. 'jul',
  348. 'aug',
  349. 'sep',
  350. 'oct',
  351. 'nov',
  352. 'dec',
  353. ]);
  354. }
  355. /**
  356. * Translates array content
  357. * @param list<string> $data
  358. * @return list<string>
  359. */
  360. private function convertToTranslatedJson(array $data = []): array {
  361. $translated = array_map(static fn(string $a) => _t('gen.date.' . $a), $data);
  362. return $translated;
  363. }
  364. /**
  365. * Gets the date intervals with the largest number of unread articles.
  366. * @param 'id'|'date' $field to use for the date
  367. * @param 'day'|'month'|'year' $granularity of the date intervals
  368. * @return list<array{'granularity':string,'unread_count':int}>
  369. */
  370. public function getMaxUnreadDates(string $field, string $granularity, int $max = 100, int $minPriority = FreshRSS_Feed::PRIORITY_HIDDEN): array {
  371. $sql = <<<SQL
  372. SELECT
  373. {$this->sqlDateToIsoGranularity('e.' . $field, precision: $field === 'id' ? 1000000 : 1, granularity: $granularity)} AS granularity,
  374. COUNT(*) AS unread_count
  375. FROM `_entry` e
  376. INNER JOIN `_feed` f ON e.id_feed = f.id
  377. WHERE e.is_read = 0 AND f.priority >= :min_priority
  378. GROUP BY granularity
  379. ORDER BY unread_count DESC, granularity DESC
  380. LIMIT :max
  381. SQL;
  382. if (($stm = $this->pdo->prepare($sql)) !== false &&
  383. $stm->bindValue(':min_priority', $minPriority, PDO::PARAM_INT) &&
  384. $stm->bindValue(':max', $max, PDO::PARAM_INT) &&
  385. $stm->execute() && is_array($res = $stm->fetchAll(PDO::FETCH_ASSOC))) {
  386. /** @var list<array{granularity:string,unread_count:int}> $res */
  387. return $res;
  388. } else {
  389. $info = $stm === false ? $this->pdo->errorInfo() : $stm->errorInfo();
  390. Minz_Log::error('SQL error ' . __METHOD__ . json_encode($info));
  391. return [];
  392. }
  393. }
  394. }