helpers.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. class Score
  3. {
  4. public static $tmpArray = array();
  5. public static function getScanDirectory($dir, $recurse = false)
  6. {
  7. if (substr($dir, -1) != "/") {
  8. $dir .= "/";
  9. }
  10. $entryList = scandir($dir);
  11. foreach ($entryList as $key => $entry) {
  12. if ($entry[0] == ".") { continue; }
  13. $path = $dir . $entry;
  14. if (is_dir($path)) {
  15. self::$tmpArray['folders'][] = [
  16. "name" => "$path/",
  17. "size" => 0,
  18. "lastmod" => filemtime($path),
  19. ];
  20. if ($recurse && is_readable($path)) {
  21. self::getScanDirectory("$path/", true);
  22. }
  23. } elseif (is_readable($path)) {
  24. self::$tmpArray['files'][] = [
  25. "name" => $path,
  26. "size" => filesize($path),
  27. "lastmod" => filemtime($path),
  28. ];
  29. }
  30. }
  31. return self::$tmpArray;
  32. }
  33. }
  34. function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") {
  35. $maxArray = [];
  36. foreach ($array as $key => $data) {
  37. if (count($data) > count($maxArray)) {
  38. $maxArray = $data;
  39. }
  40. }
  41. $array = array_merge([array_keys($maxArray)], $array);
  42. header('Content-Type: application/csv');
  43. header('Content-Disposition: attachment; filename="' . $filename . '";');
  44. $f = fopen('php://output', 'w');
  45. foreach ($array as $line) {
  46. fputcsv($f, $line, $delimiter);
  47. }
  48. fclose($f);
  49. }
  50. function SendRequest($url, $method = 'GET', $params = array(), $header = array(), $proxy = '') : array
  51. {
  52. $defaultHeaders = array(
  53. //"User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
  54. //"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
  55. //"Accept-Encoding: gzip, deflate",
  56. "Accept-Language: en-US,en;q=0.5",
  57. "Connection: keep-alive",
  58. // //"Authorization: Bearer 6|E2QX1fToDWlptzD8CtsvEFu5OkTDqe5C2766NAvT",
  59. "Accept: application/json",
  60. // "Referer: https://content-customsearch.googleapis.com/static/proxy.html",
  61. // "X-Goog-Encode-Response-If-Executable: base64",
  62. // "X-Javascript-User-Agent: apix/3.0.0 google-api-javascript-client/1.1.0",
  63. // "X-Origin: https://explorer.apis.google.com",
  64. // "X-Referer: https://explorer.apis.google.com",
  65. "X-Requested-With: XMLHttpRequest"
  66. );
  67. $userHeaders = (!empty($header) && is_array($header)) ? $header : array();
  68. $headers = array_merge($defaultHeaders, $userHeaders);
  69. $curl = curl_init();
  70. switch ($method) {
  71. case 'GET':
  72. if ($params) {
  73. $query = http_build_query($params);
  74. $url = "{$url}?{$query}";
  75. }
  76. break;
  77. case 'POST':
  78. curl_setopt($curl, CURLOPT_POST, true);
  79. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  80. break;
  81. default:
  82. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
  83. curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
  84. break;
  85. }
  86. curl_setopt($curl, CURLOPT_URL, $url);
  87. //curl_setopt($curl, CURLOPT_HEADER, true);
  88. curl_setopt($curl, CURLOPT_PROXY, $proxy);
  89. //curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyauth);
  90. //curl_setopt($curl, CURLOPT_USERPWD, "adminka:s2zgqfhauJ");
  91. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  92. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
  93. curl_setopt($curl, CURLOPT_TIMEOUT, 10); //timeout in seconds
  94. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  95. curl_setopt($curl, CURLOPT_REFERER, "https://google.com");
  96. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
  97. //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  98. //curl_setopt($curl, CURLOPT_SSLVERSION, 1);
  99. //curl_setopt($curl,CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
  100. //curl_setopt($curl,CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
  101. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  102. $resp = curl_exec($curl);
  103. if ($resp === false) {
  104. $errno = curl_errno($curl);
  105. $error_message = curl_error($curl);
  106. curl_close($curl);
  107. throw new Exception($error_message, (int)$errno);
  108. }
  109. $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  110. return ['code' => $code, 'content' => $resp];
  111. }
  112. function getSlug($text)
  113. {
  114. // replace non letter or digits by -
  115. $text = preg_replace('~[^\pL\d]+~u', '-', $text);
  116. // transliterate
  117. $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  118. // remove unwanted characters
  119. $text = preg_replace('~[^-\w]+~', '', $text);
  120. // trim
  121. $text = trim($text, '-');
  122. // remove duplicate -
  123. $text = preg_replace('~-+~', '-', $text);
  124. // lowercase
  125. $text = strtolower($text);
  126. if (empty($text)) {
  127. return 'n-a';
  128. }
  129. return $text;
  130. }
  131. function db()
  132. {
  133. return \App\Database::getInstance();
  134. }
  135. function settings($grupa)
  136. {
  137. return new \App\Settings($grupa);
  138. }
  139. function ViewRender(String $view, Array $data = [])
  140. {
  141. extract($data);
  142. ob_start();
  143. if (file_exists(Config::PATH['view']."/{$view}")) {
  144. include(Config::PATH['view']."/{$view}");
  145. } else {
  146. echo "View {$view} not found!";
  147. }
  148. $content = ob_get_contents();
  149. ob_end_clean();
  150. return $content;
  151. }
  152. /**
  153. * Универсальная функция для загрузки изображений
  154. * @param array $files - $_FILES элемент или массив файлов
  155. * @param string $fieldName - имя поля файла (для вложенных массивов)
  156. * @return string|false - относительный путь к файлу или false при ошибке
  157. */
  158. function uploadImage($files, $fieldName = null): bool|string {
  159. // Разрешенные MIME типы для изображений
  160. $allowedMimeTypes = [
  161. 'image/jpeg',
  162. 'image/jpg',
  163. 'image/png',
  164. 'image/gif',
  165. 'image/webp',
  166. 'image/svg+xml',
  167. 'image/x-icon',
  168. 'image/vnd.microsoft.icon'
  169. ];
  170. // Если передано имя поля, извлекаем данные из вложенного массива
  171. if ($fieldName && isset($files['name'][$fieldName])) {
  172. $file = [
  173. 'name' => $files['name'][$fieldName],
  174. 'tmp_name' => $files['tmp_name'][$fieldName],
  175. 'error' => $files['error'][$fieldName],
  176. 'type' => $files['type'][$fieldName]
  177. ];
  178. } else {
  179. $file = $files;
  180. }
  181. if (empty($file['name']) || $file['error'] !== UPLOAD_ERR_OK) {
  182. return false;
  183. }
  184. // Проверка MIME типа
  185. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  186. $mimeType = finfo_file($finfo, $file['tmp_name']);
  187. finfo_close($finfo);
  188. if (!in_array($mimeType, $allowedMimeTypes)) {
  189. return false;
  190. }
  191. // Дополнительная проверка по расширению файла
  192. $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
  193. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico'];
  194. if (!in_array($fileExtension, $allowedExtensions)) {
  195. return false;
  196. }
  197. $uploadDir = Config::PATH['storage'] . '/';
  198. // Создаем директорию если она не существует
  199. if (!file_exists($uploadDir)) {
  200. mkdir($uploadDir, 0755, true);
  201. }
  202. // Используем оригинальное имя файла
  203. $fileName = basename($file['name']);
  204. $targetPath = $uploadDir . $fileName;
  205. if (move_uploaded_file($file['tmp_name'], $targetPath)) {
  206. // Возвращаем относительный путь для веб-доступа
  207. return 'uploads/' . $fileName;
  208. }
  209. return false;
  210. }
  211. /**
  212. * Получение реального IP адреса пользователя
  213. * @return string IP адрес пользователя
  214. */
  215. function getUserIp(): string {
  216. if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
  217. return $_SERVER['HTTP_CF_CONNECTING_IP'];
  218. } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  219. // Берём первый IP из списка (если их несколько через запятую)
  220. return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
  221. } else {
  222. return $_SERVER['REMOTE_ADDR'];
  223. }
  224. }
  225. function calculateRating($index) {
  226. if ($index < 3) {
  227. return '10';
  228. } elseif ($index < 6) {
  229. return '9.5';
  230. } elseif ($index < 9) {
  231. return '9';
  232. } else {
  233. return '8.5';
  234. }
  235. }
  236. function getCurrentUrl() {
  237. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  238. $domain = $_SERVER['HTTP_HOST'];
  239. $requestUri = $_SERVER['REQUEST_URI'];
  240. return $protocol . $domain . $requestUri;
  241. }
  242. function getCurrentDomain() {
  243. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  244. $domain = $_SERVER['HTTP_HOST'];
  245. return $protocol . $domain;
  246. }