CommonHelper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <?php
  2. // app/Libraries/CommonHelper.php
  3. namespace App\Libraries;
  4. use Dcat\Admin\Admin;
  5. class CommonHelper
  6. {
  7. /*
  8. * $images 格式:['image.jpg','image2.jpg']
  9. * $ossSource 1:本地 2:相册
  10. * 返回显示的HTML显示图片
  11. */
  12. public static function displayImage($images,$boxSize=60,$imgSize=1024,$ossSource=1,$hasLink=true)
  13. {
  14. if (empty($images) || empty($images[0])) {
  15. $html = "";
  16. } else {
  17. // 默认显示 100x100 的图片
  18. $thumbnailImages = array_map(function ($imageUrl) use ($boxSize,$ossSource) {
  19. if ($ossSource == 1) {
  20. $imageUrl= CommonHelper::ossUrl($imageUrl);
  21. } else {
  22. $imageUrl= CommonHelper::albumUrl($imageUrl);
  23. }
  24. $extension = pathinfo($imageUrl, PATHINFO_EXTENSION);
  25. if ($extension == 'svg') {
  26. return $imageUrl;
  27. } else {
  28. return $imageUrl . "?x-oss-process=image/resize,m_pad,h_{$boxSize},w_{$boxSize},color_ffffff";
  29. }
  30. }, $images);
  31. // 生成点击查看大图的链接
  32. $largeImages = array_map(function ($imageUrl) use ($imgSize,$ossSource) {
  33. if ($ossSource == 1) {
  34. $imageUrl= CommonHelper::ossUrl($imageUrl);
  35. } else {
  36. $imageUrl= CommonHelper::albumUrl($imageUrl);
  37. }
  38. $extension = pathinfo($imageUrl, PATHINFO_EXTENSION);
  39. if ($extension == 'svg') {
  40. return $imageUrl;
  41. } else {
  42. return $imageUrl . "?x-oss-process=image/resize,m_lfit,w_{$imgSize},h_{$imgSize}";
  43. }
  44. }, $images);
  45. // 显示缩略图,并添加点击查看大图的功能
  46. $html = '';
  47. foreach ($thumbnailImages as $index => $thumbnailUrl) {
  48. $largeUrl = $largeImages[$index];
  49. if ($hasLink) {
  50. $html .= "<a href='$largeUrl' target='_blank'><img src='$thumbnailUrl' style='height:{$boxSize}px; margin-right:5px; border: 1px solid #ececf1;'></a>";
  51. } else {
  52. $html .= "<img src='$thumbnailUrl' style='height:{$boxSize}px; margin-right:5px; '>";
  53. }
  54. }
  55. return $html;
  56. }
  57. return $html;
  58. }
  59. /*
  60. * 返回oss的url
  61. */
  62. public static function ossUrl($imageUrl)
  63. {
  64. if (strpos($imageUrl, 'http:') === 0 || strpos($imageUrl, 'https:') === 0) {
  65. return $imageUrl;
  66. }
  67. if (env('OSS_DOMAIN')) {
  68. return "http://".env('OSS_DOMAIN').'/'.$imageUrl;
  69. }
  70. return "http://".env('OSS_BUCKET').'.'.env('OSS_ENDPOINT').'/'.$imageUrl;
  71. }
  72. /*
  73. * 图库图片URL
  74. */
  75. public static function albumUrl($imageUrl)
  76. {
  77. if (strpos($imageUrl, 'http:') === 0 || strpos($imageUrl, 'https:') === 0) {
  78. return $imageUrl;
  79. }
  80. return env('ALBUM_OSS_URL').'/'.$imageUrl;
  81. }
  82. /*
  83. * 显示视频
  84. */
  85. public static function displayVideo($items,$videoCover,$videoSrc,$boxSize=150,$ossSource=1)
  86. {
  87. $html = '';
  88. if (is_array($items)) {
  89. foreach ($items as $item) {
  90. $item = (array) $item;
  91. $cover = $item[$videoCover];
  92. $src = $item[$videoSrc];
  93. if ($ossSource == 1) {
  94. $videoUrl = CommonHelper::ossUrl($src);
  95. } else {
  96. $videoUrl = CommonHelper::albumUrl($src);
  97. }
  98. if ($ossSource == 1) {
  99. $thumbnailUrl = CommonHelper::ossUrl($cover) . "?x-oss-process=image/resize,m_pad,h_{$boxSize},w_{$boxSize},color_ffffff";
  100. } else {
  101. $thumbnailUrl = CommonHelper::albumUrl($cover) . "?x-oss-process=image/resize,m_pad,h_{$boxSize},w_{$boxSize},color_ffffff";
  102. }
  103. $html .= '<div class="video-container"><img src="'.$thumbnailUrl.'" alt="Video Thumbnail" class="video-thumbnail"><a href="#" class="downloadVideo" videoUrl="'.$videoUrl.'")"><div class="video-download-button"></div></a> <a href="#" class="playVideo" videoUrl="'.$videoUrl.'")"><div class="play-button"></div></a></div>';
  104. }
  105. $html .= '<div class="video-popup" id="videoPopup"><span class="close-btn">&times;</span> <iframe src="" frameborder="0" allowfullscreen></iframe></div>';
  106. }
  107. //视频播放CSS
  108. Admin::style("
  109. .video-container {
  110. position: relative;
  111. display: inline-block;
  112. margin-bottom: 5px;
  113. }
  114. .video-container img {
  115. height: 200px;
  116. margin-right: 5px;
  117. border: 1px solid #ececf1;
  118. }
  119. .video-download-button {
  120. position: absolute;
  121. top: 50%;
  122. left: 35%;
  123. transform: translate(-50%, -50%);
  124. width: 35px;
  125. height: 35px;
  126. background-color: rgba(0, 0, 0, 0.5);
  127. border-radius: 50%;
  128. cursor: pointer;
  129. }
  130. .video-download-button::after {
  131. content: '↓';
  132. font-size: 15px;
  133. color: white;
  134. position: absolute;
  135. top: 50%;
  136. left: 50%;
  137. transform: translate(-50%, -50%);
  138. }
  139. .play-button {
  140. position: absolute;
  141. top: 50%;
  142. left: 58%;
  143. transform: translate(-50%, -50%);
  144. width: 35px;
  145. height: 35px;
  146. background-color: rgba(0, 0, 0, 0.5);
  147. border-radius: 50%;
  148. cursor: pointer;
  149. }
  150. .play-button::after {
  151. content: '▶';
  152. font-size: 15px;
  153. color: white;
  154. position: absolute;
  155. top: 50%;
  156. left: 50%;
  157. transform: translate(-50%, -50%);
  158. }
  159. .video-popup {
  160. display: none;
  161. position: fixed;
  162. top: 50%;
  163. left: 50%;
  164. transform: translate(-50%, -50%);
  165. background-color: white;
  166. padding: 25px;
  167. box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  168. z-index: 1000;
  169. }
  170. .video-popup iframe {
  171. width: 800px;
  172. height: 450px;
  173. }
  174. .close-btn {
  175. position: absolute;
  176. top: 0px;
  177. right: 5px;
  178. font-size: 24px;
  179. color: #000;
  180. cursor: pointer;
  181. }
  182. .close-btn:hover {
  183. color: #f00;
  184. }
  185. ");
  186. Admin::script("
  187. $('.playVideo').on('click', function(e) {
  188. e.preventDefault(); // 阻止默认跳转行为
  189. var videoUrl = $(this).attr('videoUrl'); // 获取 videoUrl 属性
  190. $('#videoPopup').css('display', 'block');
  191. $('#videoPopup iframe').attr('src', videoUrl); // 设置 iframe 的 src
  192. });
  193. $('.downloadVideo').on('click', function(e) {
  194. e.preventDefault();
  195. const button = $(this);
  196. const videoUrl = button.attr('videoUrl');
  197. const loading = Dcat.loading({
  198. shade: 'rgba(0,0,0,0.5)',
  199. zIndex: 999999
  200. });
  201. fetch(videoUrl, {
  202. headers: new Headers({
  203. 'Origin': location.origin,
  204. 'X-CSRF-TOKEN': Dcat.token
  205. }),
  206. mode: 'cors'
  207. }).then(response => {
  208. if (!response.ok) throw new Error(`HTTP \${response.status}`);
  209. const reader = response.body.getReader();
  210. const chunks = [];
  211. const processChunk = ({ done, value }) => {
  212. if (done) {
  213. const blob = new Blob(chunks);
  214. const filename = videoUrl.split('/').pop() || 'video.mp4';
  215. // 标准文件下载实现[7](@ref)
  216. const link = document.createElement('a');
  217. link.href = URL.createObjectURL(blob);
  218. link.download = filename;
  219. document.body.appendChild(link);
  220. link.click();
  221. document.body.removeChild(link);
  222. URL.revokeObjectURL(link.href);
  223. Dcat.loading(false);
  224. return;
  225. }
  226. chunks.push(value);
  227. return reader.read().then(processChunk);
  228. };
  229. return reader.read().then(processChunk);
  230. }).catch(error => {
  231. Dcat.loading(false);
  232. Dcat.error(`下载失败:\${error.message}`);
  233. console.error('Download Error:', error);
  234. });
  235. });
  236. // 点击关闭按钮关闭视频
  237. $('.close-btn').on('click', function() {
  238. $('#videoPopup').css('display', 'none');
  239. $('#videoPopup iframe').attr('src', ''); // 停止播放视频
  240. });
  241. ");
  242. return $html; // 当没有数组数据时
  243. }
  244. /*
  245. * 替换新增与编辑的url,在后边加上指定的参数 (适用于弹出框的新增与编辑)
  246. * $addButton = '.tree-quick-create';
  247. * $editButton = '.tree-quick-edit';
  248. * $paramsUrl = 'location=0';
  249. */
  250. public static function replaceAddEditerUrl($addButton,$editButton,$paramsUrl) {
  251. Admin::script(
  252. <<<JS
  253. var button = $('{$addButton}');
  254. var currentUrl = button.attr('data-url');
  255. if (currentUrl.indexOf('?') === -1) {
  256. button.attr('data-url', currentUrl + '?{$paramsUrl}');
  257. } else {
  258. button.attr('data-url', currentUrl + '&{$paramsUrl}');
  259. }
  260. $('{$editButton}').each(function() {
  261. var currentUrl = $(this).attr('data-url');
  262. if (currentUrl.indexOf('?') === -1) {
  263. $(this).attr('data-url', currentUrl + '?{$paramsUrl}');
  264. } else {
  265. // 如果已经有查询参数,添加 &id=123
  266. $(this).attr('data-url', currentUrl + '&{$paramsUrl}');
  267. }
  268. });
  269. JS
  270. );
  271. }
  272. public static function seoReplace($titleName = 'title',$modelName = 'pages')
  273. {
  274. if ($titleName) {
  275. Admin::script(
  276. <<<JS
  277. $('input[name="{$titleName}"]').on('input', function() {
  278. // 将 title 的值赋给 seo_title
  279. $('input[name="seo_title"]').val($(this).val());
  280. });
  281. JS
  282. );
  283. }
  284. //ajax 生成slug
  285. if ($modelName) {
  286. Admin::script(
  287. <<<JS
  288. $('input[name="{$titleName}"]').on('blur', function() {
  289. //通过ajax请求修改slug
  290. title = $(this).val();
  291. $.ajax({
  292. url: '/dist/api/generate-slug',
  293. type: 'GET',
  294. data: {
  295. model:'{$modelName}',
  296. title: title,
  297. },
  298. success: function(response) {
  299. $('input[name="slug"]').val(response.slug);
  300. }
  301. });
  302. });
  303. JS
  304. );
  305. }
  306. }
  307. public static function slug_fix($slug)
  308. {
  309. if ($slug == '') {
  310. return '';
  311. } else {
  312. $slug = preg_replace('/\s+/', '-', $slug);
  313. $slug = strtolower($slug);
  314. return $slug;
  315. }
  316. }
  317. /*
  318. * 用于详情页,图片下载与放大
  319. */
  320. public static function viewDownloadEnlarge() {
  321. //css
  322. Admin::style(
  323. <<<CSS
  324. .box {
  325. border-radius:0;
  326. }
  327. .box.box-solid.box-default {
  328. border:none;
  329. box-shadow:none;
  330. border-bottom: 1px solid #e1e8ea;
  331. }
  332. .download-wrapper::after {
  333. content: "";
  334. position: absolute;
  335. top: 0;
  336. left: 0;
  337. width: 100%;
  338. height: 100%;
  339. background: rgba(58, 54, 54, 0.34); /* 浅灰色半透明 */
  340. opacity: 0;
  341. transition: opacity 0.3s ease;
  342. pointer-events: none;
  343. border-radius: 8px;
  344. }
  345. .download-wrapper {
  346. position: relative;
  347. display: inline-block;
  348. margin: 15px;
  349. overflow: hidden;
  350. border-radius: 8px;
  351. transition: transform 0.3s ease;
  352. }
  353. .download-hover {
  354. position: absolute;
  355. top: 50%;
  356. left: 50%;
  357. transform: translate(-50%, -50%);
  358. opacity: 0;
  359. transition: opacity 0.3s ease;
  360. display: flex;
  361. gap: 12px;
  362. z-index: 1; /* 确保按钮在遮罩层上方 */
  363. }
  364. .download-btn {
  365. background: rgba(255, 255, 255, 0.95);
  366. border: none;
  367. width: 42px;
  368. height: 42px;
  369. border-radius: 50%;
  370. cursor: pointer;
  371. box-shadow: 0 3px 6px rgba(0,0,0,0.16);
  372. transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  373. }
  374. .download-btn.disabled {
  375. background: rgba(189, 189, 189, 0.95);
  376. cursor: not-allowed;
  377. }
  378. .download-btn i {
  379. font-size: 18px;
  380. color: #2196F3;
  381. }
  382. .download-wrapper:hover::after {
  383. opacity: 1;
  384. }
  385. .download-wrapper:hover .download-hover {
  386. opacity: 1;
  387. }
  388. .auto-download-image {
  389. display: block;
  390. transition: transform 0.3s ease;
  391. max-width: 100%;
  392. height: auto;
  393. border-radius: 8px;
  394. }
  395. /*.download-wrapper:hover img {*/
  396. /* transform: scale(1.04);*/
  397. /*}*/
  398. /* 新增全屏样式 */
  399. .fullscreen-overlay {
  400. position: fixed;
  401. top: 0;
  402. left: 0;
  403. width: 100%;
  404. height: 100%;
  405. background: rgba(0,0,0,0.95);
  406. display: none;
  407. z-index: 1000;
  408. cursor: zoom-out;
  409. }
  410. .fullscreen-image {
  411. position: absolute;
  412. max-width: 90%;
  413. max-height: 90%;
  414. top: 50%;
  415. left: 50%;
  416. transform: translate(-50%, -50%);
  417. border-radius: 8px;
  418. animation: zoomIn 0.3s ease;
  419. }
  420. @keyframes zoomIn {
  421. from { transform: translate(-50%, -50%) scale(0.8); }
  422. to { transform: translate(-50%, -50%) scale(1); }
  423. }
  424. .download-wrapper:hover .download-hover {
  425. opacity: 1;
  426. }
  427. CSS );
  428. //js
  429. Admin::script(
  430. <<<JS
  431. const fullscreenOverlay = $('.fullscreen-overlay');
  432. const fullscreenImage = $('.fullscreen-image');
  433. function initDownloadButtons() {
  434. $('.box-body').find("img").each(function() {
  435. // 新增判断:如果父元素是<a>或已有download-wrapper则跳过
  436. if ($(this).parent().hasClass('download-wrapper') || $(this).parent().is('a')) return;
  437. if ($(this).hasClass('fullscreen-image') || $(this).hasClass('video-thumbnail')) {
  438. return;
  439. }
  440. // const fileName = this.src.split('/').pop().split('?')[0];
  441. const getFileName = url => url.split('?')[0].split('/').pop();
  442. const fileName = getFileName(this.src);
  443. // alert(fileName);
  444. $(this).wrap('<div class="download-wrapper"></div>')
  445. .after(`<div class="download-hover">
  446. <button class="download-btn" title="下载">
  447. <i class="feather icon-download"></i>
  448. </button>
  449. <button class="download-btn zoom-btn" title="放大">
  450. <i class="feather icon-zoom-in"></i>
  451. </button>
  452. </div>`);
  453. const \$btn = $(this).parent().find('.download-btn').first();
  454. \$btn.click(function() {
  455. const btn = $(this);
  456. btn.addClass('disabled');
  457. downloadImage(
  458. btn.closest('.download-wrapper').find('img')[0].src,
  459. fileName
  460. ).finally(() => btn.removeClass('disabled'));
  461. });
  462. var checkImageLoaded = function(img, callback) {
  463. const timer = setInterval(() => {
  464. if (img.complete || img.naturalWidth > 0) {
  465. clearInterval(timer);
  466. callback();
  467. }
  468. }, 50);
  469. }
  470. // 全屏放大功能
  471. $(this).next().find('.zoom-btn').click(function() {
  472. Dcat.loading();
  473. let imgSrc = $(this).closest('.download-wrapper').find('img').attr('src');
  474. imgSrc = imgSrc.replace(/\?.*$/, '');
  475. fullscreenImage.attr('src', imgSrc);
  476. fullscreenOverlay.fadeIn(200);
  477. checkImageLoaded(fullscreenImage[0], () => {
  478. Dcat.loading(false);
  479. });
  480. });
  481. });
  482. }
  483. // 关闭全屏
  484. fullscreenOverlay.click(function(e) {
  485. if (e.target === this) {
  486. Dcat.loading(false);
  487. $(this).fadeOut(200);
  488. fullscreenImage.attr('src', '');
  489. }
  490. });
  491. function downloadImage(url, filename) {
  492. url = url.replace(/\?.*$/, '');
  493. return new Promise((resolve, reject) => {
  494. fetch(url)
  495. .then(response => {
  496. if (!response.ok) throw new Error('网络异常');
  497. return response.blob()
  498. })
  499. .then(blob => {
  500. const blobUrl = URL.createObjectURL(blob);
  501. const link = document.createElement('a');
  502. link.href = blobUrl;
  503. link.download = filename || 'image.jpg';
  504. document.body.appendChild(link);
  505. link.click();
  506. setTimeout(() => {
  507. document.body.removeChild(link);
  508. URL.revokeObjectURL(blobUrl);
  509. }, 100);
  510. resolve();
  511. })
  512. .catch(error => {
  513. console.error(error);
  514. alert('下载失败');
  515. reject(error);
  516. });
  517. });
  518. }
  519. initDownloadButtons();
  520. JS);
  521. }
  522. /*
  523. * 用于详情页,图片下载与放大 HTML
  524. */
  525. public static function viewDownloadEnlargeHtml() {
  526. return '<div class="fullscreen-overlay"><img src="" class="fullscreen-image"></div>';
  527. }
  528. }