pihole.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. trait PiHoleHomepageItem
  3. {
  4. public function piholeSettingsArray($infoOnly = false)
  5. {
  6. $homepageInformation = [
  7. 'name' => 'Pi-hole',
  8. 'enabled' => true,
  9. 'image' => 'plugins/images/tabs/pihole.png',
  10. 'category' => 'Monitor',
  11. 'settingsArray' => __FUNCTION__
  12. ];
  13. if ($infoOnly) {
  14. return $homepageInformation;
  15. }
  16. $homepageSettings = [
  17. 'debug' => true,
  18. 'settings' => [
  19. 'Enable' => [
  20. $this->settingsOption('enable', 'homepagePiholeEnabled'),
  21. $this->settingsOption('auth', 'homepagePiholeAuth'),
  22. ],
  23. 'Connection' => [
  24. $this->settingsOption('multiple-url', 'piholeURL', ['help' => 'Please make sure to use local IP address and port at the end of the URL. You can add multiple Pi-holes by comma separating the URLs.', 'placeholder' => 'http(s)://hostname:port/']),
  25. $this->settingsOption('multiple-token', 'piholeToken'),
  26. ],
  27. 'Misc' => [
  28. $this->settingsOption('toggle-title', 'piholeHeaderToggle'),
  29. $this->settingsOption('switch', 'homepagePiholeCombine', ['label' => 'Combine stat cards', 'help' => 'This controls whether to combine the stats for multiple pihole instances into 1 card.']),
  30. ],
  31. 'Test Connection' => [
  32. $this->settingsOption('blank', null, ['label' => 'Please Save before Testing']),
  33. $this->settingsOption('test', 'pihole'),
  34. ]
  35. ]
  36. ];
  37. return array_merge($homepageInformation, $homepageSettings);
  38. }
  39. public function testConnectionPihole()
  40. {
  41. if (empty($this->config['piholeURL'])) {
  42. $this->setAPIResponse('error', 'Pihole URL is not defined', 422);
  43. return false;
  44. }
  45. $failed = false;
  46. $errors = '';
  47. $list = $this->csvHomepageUrlToken($this->config['piholeURL'], $this->config['piholeToken']);
  48. foreach ($list as $key => $value) {
  49. $response = $this->getAuth($value['url'], $value['token']);
  50. $errors = $response["errors"];
  51. }
  52. if ($errors != '') {
  53. $this->setAPIResponse('error', $errors, 500);
  54. return false;
  55. } else {
  56. $this->setAPIResponse('success', null, 200);
  57. return true;
  58. }
  59. }
  60. public function piholeHomepagePermissions($key = null)
  61. {
  62. $permissions = [
  63. 'main' => [
  64. 'enabled' => [
  65. 'homepagePiholeEnabled'
  66. ],
  67. 'auth' => [
  68. 'homepagePiholeAuth'
  69. ],
  70. 'not_empty' => [
  71. 'piholeURL'
  72. ]
  73. ]
  74. ];
  75. return $this->homepageCheckKeyPermissions($key, $permissions);
  76. }
  77. public function homepageOrderPihole()
  78. {
  79. if ($this->homepageItemPermissions($this->piholeHomepagePermissions('main'))) {
  80. return '
  81. <div id="' . __FUNCTION__ . '">
  82. <div class="white-box homepage-loading-box"><h2 class="text-center" lang="en">Loading Pihole...</h2></div>
  83. <script>
  84. // Pi-hole Stats
  85. homepagePihole("' . $this->config['homepagePiholeRefresh'] . '");
  86. // End Pi-hole Stats
  87. </script>
  88. </div>
  89. ';
  90. }
  91. }
  92. public function getAuth($base_url, $token)
  93. {
  94. $sid = null;
  95. if ($token === '' || $token === null) {
  96. $errors .= $base_url . ': Missing API Token';
  97. $this->setAPIResponse('error', $errors, 500);
  98. return $errors;
  99. }
  100. try {
  101. $sid = $this->doRequest($base_url, "createAuth", [], ['password' => $token]);
  102. $this->cleanSessions($base_url, $sid);
  103. } catch (Requests_Exception $e) {
  104. $errors .= $ip . ': ' . $e->getMessage();
  105. $this->setLoggerChannel('PiHole')->error($e);
  106. };
  107. return ["errors" => $errors, "sid" => $sid];
  108. }
  109. public function cleanSessions($base_url, $sid)
  110. {
  111. $sessions = $this->doRequest($base_url, "getAuths", ["sid" => $sid]);
  112. foreach ($sessions as $session) {
  113. // Skip if not right user agent, skip if current session
  114. if ($session['user_agent'] != 'Organizr' || $session['current_session'] == '1') {
  115. continue;
  116. }
  117. $this->doRequest($base_url,"deleteAuth", ["sid" => $sid], $session['id']);
  118. }
  119. }
  120. public function endpoints($endpoint)
  121. {
  122. return [
  123. "createAuth" => [
  124. "type" => "post",
  125. "urlHandler" => function() {
  126. return "auth";
  127. },
  128. "responseHandler" => function($payload) {
  129. return $payload['session']['sid'];
  130. },
  131. "payloadHandler" => function($data) {
  132. return json_encode($data);
  133. }
  134. ],
  135. "getAuths" => [
  136. "type" => "get",
  137. "urlHandler" => function() {
  138. return "auth/sessions";
  139. },
  140. "responseHandler" => function($payload) {
  141. return $payload['sessions'];
  142. }
  143. ],
  144. "deleteAuth" => [
  145. "type" => "delete",
  146. "urlHandler" => function($id) {
  147. return "auth/session/$id";
  148. },
  149. ],
  150. "get24HourStatsSummary" => [
  151. "type" => "get",
  152. "urlHandler" => function() {
  153. $nowUnixTimestamp = time();
  154. $oneDayAgoUnixTimestamp = $nowUnixTimestamp - (24 * 60 * 60);
  155. return "stats/database/summary?from=$oneDayAgoUnixTimestamp&until=$nowUnixTimestamp";
  156. }
  157. ],
  158. "get24HourBlockedDomains" => [
  159. "type" => "get",
  160. "urlHandler" => function() {
  161. $nowUnixTimestamp = time();
  162. $oneDayAgoUnixTimestamp = $nowUnixTimestamp - (24 * 60 * 60);
  163. return "stats/database/top_domains?from=$oneDayAgoUnixTimestamp&until=$nowUnixTimestamp&blocked=true&count=1000";
  164. },
  165. "responseHandler" => function($payload) {
  166. return array_map(
  167. function($item) {
  168. return $item['domain'];
  169. }, $payload['domains']
  170. );
  171. }
  172. ],
  173. ][$endpoint];
  174. }
  175. public function doRequest($baseUrl, $endpoint, $headers = [], $data = null)
  176. {
  177. $endpointDictionary = $this->endpoints($endpoint);
  178. $urlHandler = $endpointDictionary['urlHandler'];
  179. $payloadHandler = $endpointDictionary['payloadHandler'] ?? function() {
  180. return null;
  181. };
  182. $requestType = $endpointDictionary['type'];
  183. $responseHandler = $endpointDictionary['responseHandler'] ?? function($payload) {
  184. return $payload;
  185. };
  186. $url = $this->qualifyURL("$baseUrl/api/{$urlHandler($data)}");
  187. $headers = $headers + ["User-Agent" => 'Organizr'];
  188. try {
  189. $response = Requests::$requestType($url, $headers, $payloadHandler($data));
  190. if ($response->success) {
  191. $processedResponse = $responseHandler($this->testAndFormatString($response->body)["data"]);
  192. }
  193. } catch (Requests_Exception $e) {
  194. $this->setResponse(500, $e->getMessage());
  195. $this->setLoggerChannel('PiHole')->error($e);
  196. throw $e;
  197. };
  198. return $processedResponse ?? [];
  199. }
  200. public function getPiholeHomepageStats()
  201. {
  202. if (!$this->homepageItemPermissions($this->piholeHomepagePermissions('main'), true)) {
  203. return false;
  204. }
  205. $api = [];
  206. $list = $this->csvHomepageUrlToken($this->config['piholeURL'], $this->config['piholeToken']);
  207. foreach ($list as $key => $value) {
  208. $base_url = $value['url'];
  209. $sid = $this->getAuth($base_url, $value['token'])["sid"];
  210. $stats = $this->doRequest($base_url, "get24HourStatsSummary", ["sid" => $sid]);
  211. $stats["domains_being_blocked"] = $this->doRequest($base_url, "get24HourBlockedDomains", ["sid" => $sid]);
  212. $api['data'][$base_url] = $stats;
  213. }
  214. $api['options']['combine'] = $this->config['homepagePiholeCombine'];
  215. $api['options']['title'] = $this->config['piholeHeaderToggle'];
  216. $api = $api ?? null;
  217. $this->setAPIResponse('success', null, 200, $api);
  218. return $api;
  219. }
  220. }