website.lib.php 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/core/lib/website.lib.php
  19. * \ingroup website
  20. * \brief Library for website module
  21. */
  22. /**
  23. * Remove PHP code part from a string.
  24. *
  25. * @param string $str String to clean
  26. * @param string $replacewith String to use as replacement
  27. * @return string Result string without php code
  28. * @see dolKeepOnlyPhpCode()
  29. */
  30. function dolStripPhpCode($str, $replacewith = '')
  31. {
  32. $str = str_replace('<?=', '<?php', $str);
  33. $newstr = '';
  34. // Split on each opening tag
  35. //$parts = explode('<?php', $str);
  36. $parts = preg_split('/'.preg_quote('<?php', '/').'/i', $str);
  37. if (!empty($parts)) {
  38. $i = 0;
  39. foreach ($parts as $part) {
  40. if ($i == 0) { // The first part is never php code
  41. $i++;
  42. $newstr .= $part;
  43. continue;
  44. }
  45. // The second part is the php code. We split on closing tag
  46. $partlings = explode('?>', $part);
  47. if (!empty($partlings)) {
  48. //$phppart = $partlings[0];
  49. //remove content before closing tag
  50. if (count($partlings) > 1) {
  51. $partlings[0] = ''; // Todo why a count > 1 and not >= 1 ?
  52. }
  53. //append to out string
  54. //$newstr .= '<span class="phptag" class="tooltip" title="'.dol_escape_htmltag(dolGetFirstLineOfText($phppart).'...').'">'.$replacewith.'<!-- '.$phppart.' --></span>'.implode('', $partlings);
  55. //$newstr .= '<span>'.$replacewith.'<!-- '.$phppart.' --></span>'.implode('', $partlings);
  56. $newstr .= '<span phptag>'.$replacewith.'</span>'.implode('', $partlings);
  57. //$newstr .= $replacewith.implode('', $partlings);
  58. }
  59. }
  60. }
  61. return $newstr;
  62. }
  63. /**
  64. * Keep only PHP code part from a HTML string page.
  65. *
  66. * @param string $str String to clean
  67. * @return string Result string with php code only
  68. * @see dolStripPhpCode(), checkPHPCode()
  69. */
  70. function dolKeepOnlyPhpCode($str)
  71. {
  72. $str = str_replace('<?=', '<?php', $str);
  73. $str = str_replace('<?php', '__LTINTPHP__', $str);
  74. $str = str_replace('<?', '<?php', $str); // replace the short_open_tag. It is recommended to set this is Off in php.ini
  75. $str = str_replace('__LTINTPHP__', '<?php', $str);
  76. $newstr = '';
  77. // Split on each opening tag
  78. //$parts = explode('<?php', $str);
  79. $parts = preg_split('/'.preg_quote('<?php', '/').'/i', $str);
  80. if (!empty($parts)) {
  81. $i = 0;
  82. foreach ($parts as $part) {
  83. if ($i == 0) { // The first part is never php code
  84. $i++;
  85. continue;
  86. }
  87. $newstr .= '<?php';
  88. //split on closing tag
  89. $partlings = explode('?>', $part, 2);
  90. if (!empty($partlings)) {
  91. $newstr .= $partlings[0].'?>';
  92. } else {
  93. $newstr .= $part.'?>';
  94. }
  95. }
  96. }
  97. return $newstr;
  98. }
  99. /**
  100. * Convert a page content to have correct links (based on DOL_URL_ROOT) into an html content. It replaces also dynamic content with '...php...'
  101. * Used to ouput the page on the Preview from backoffice.
  102. *
  103. * @param Website $website Web site object
  104. * @param string $content Content to replace
  105. * @param int $removephppart 0=Replace PHP sections with a PHP badge. 1=Remove completely PHP sections.
  106. * @param string $contenttype Content type
  107. * @param int $containerid Contenair id
  108. * @return boolean True if OK
  109. * @see dolWebsiteOutput() for function used to replace content in a web server context
  110. */
  111. function dolWebsiteReplacementOfLinks($website, $content, $removephppart = 0, $contenttype = 'html', $containerid = '')
  112. {
  113. $nbrep = 0;
  114. dol_syslog('dolWebsiteReplacementOfLinks start (contenttype='.$contenttype." containerid=".$containerid." USEDOLIBARREDITOR=".(defined('USEDOLIBARREDITOR') ? '1' : '')." USEDOLIBARRSERVER=".(defined('USEDOLIBARRSERVER') ? '1' : '').')', LOG_DEBUG);
  115. //if ($contenttype == 'html') { print $content;exit; }
  116. // Replace php code. Note $content may come from database and does not contain body tags.
  117. $replacewith = '...php...';
  118. if ($removephppart) {
  119. $replacewith = '';
  120. }
  121. $content = preg_replace('/value="<\?php((?!\?>).)*\?>\n*/ims', 'value="'.$replacewith.'"', $content);
  122. $replacewith = '"callto=#';
  123. if ($removephppart) {
  124. $replacewith = '';
  125. }
  126. $content = preg_replace('/"callto:<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
  127. $replacewith = '"mailto=#';
  128. if ($removephppart) {
  129. $replacewith = '';
  130. }
  131. $content = preg_replace('/"mailto:<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
  132. $replacewith = 'src="php';
  133. if ($removephppart) {
  134. $replacewith = '';
  135. }
  136. $content = preg_replace('/src="<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
  137. $replacewith = 'href="php';
  138. if ($removephppart) {
  139. $replacewith = '';
  140. }
  141. $content = preg_replace('/href="<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
  142. //$replacewith='<span class="phptag">...php...</span>';
  143. $replacewith = '...php...';
  144. if ($removephppart) {
  145. $replacewith = '';
  146. }
  147. //$content = preg_replace('/<\?php((?!\?toremove>).)*\?toremove>\n*/ims', $replacewith, $content);
  148. /*if ($content === null) {
  149. if (preg_last_error() == PREG_JIT_STACKLIMIT_ERROR) $content = 'preg_replace error (when removing php tags) PREG_JIT_STACKLIMIT_ERROR';
  150. }*/
  151. $content = dolStripPhpCode($content, $replacewith);
  152. // Protect the link styles.css.php to any replacement that we make after.
  153. $content = str_replace('href="styles.css.php', 'href="!~!~!~styles.css.php', $content);
  154. $content = str_replace('src="javascript.js.php', 'src="!~!~!~javascript.js.php', $content);
  155. $content = str_replace('href="http', 'href="!~!~!~http', $content);
  156. $content = str_replace('xlink:href="', 'xlink:href="!~!~!~', $content);
  157. $content = str_replace('href="//', 'href="!~!~!~//', $content);
  158. $content = str_replace('src="//', 'src="!~!~!~//', $content);
  159. $content = str_replace('src="viewimage.php', 'src="!~!~!~/viewimage.php', $content);
  160. $content = str_replace('src="/viewimage.php', 'src="!~!~!~/viewimage.php', $content);
  161. $content = str_replace('src="'.DOL_URL_ROOT.'/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
  162. $content = str_replace('href="document.php', 'href="!~!~!~/document.php', $content);
  163. $content = str_replace('href="/document.php', 'href="!~!~!~/document.php', $content);
  164. $content = str_replace('href="'.DOL_URL_ROOT.'/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
  165. // Replace relative link '/' with dolibarr URL
  166. $content = preg_replace('/(href=")\/(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'\2"', $content, -1, $nbrep);
  167. // Replace relative link /xxx.php#aaa or /xxx.php with dolibarr URL (we discard param ?...)
  168. $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2\3"', $content, -1, $nbrep);
  169. // Replace relative link /xxx.php?a=b&c=d#aaa or /xxx.php?a=b&c=d with dolibarr URL
  170. $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php\?([^#\"<>]*)(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2&\3\4"', $content, -1, $nbrep);
  171. // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
  172. $content = preg_replace('/url\((["\']?)\/?medias\//', 'url(\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  173. $content = preg_replace('/data-slide-bg=(["\']?)\/?medias\//', 'data-slide-bg=\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  174. // <img src="medias/...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  175. // <img src="...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  176. $content = preg_replace('/(<img[^>]*src=")\/?medias\//', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  177. // <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  178. $content = preg_replace('/(<img[^>]*src=")\/?([^:\"\!]+)\"/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=\2"', $content, -1, $nbrep);
  179. // <img src="viewimage.php/modulepart=medias&file=image.png" => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png"
  180. $content = preg_replace('/(<img[^>]*src=")(\/?viewimage\.php)/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content, -1, $nbrep);
  181. // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
  182. $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
  183. // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart="
  184. $content = preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  185. $content = preg_replace('/(src=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  186. // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart="
  187. $content = preg_replace('/(url\(")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  188. // Fix relative URL
  189. $content = str_replace('src="!~!~!~/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
  190. $content = str_replace('href="!~!~!~/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
  191. // Remove the protection tag !~!~!~
  192. $content = str_replace('!~!~!~', '', $content);
  193. dol_syslog('dolWebsiteReplacementOfLinks end', LOG_DEBUG);
  194. //if ($contenttype == 'html') { print $content;exit; }
  195. return $content;
  196. }
  197. /**
  198. * Converts smiley string into the utf8 sequence.
  199. * @param string $content Content to replace
  200. * @return string Replacement of all smiley strings with their utf8 code
  201. * @see dolWebsiteOutput()
  202. */
  203. function dolReplaceSmileyCodeWithUTF8($content)
  204. {
  205. $map = array(
  206. ":face_with_tears_of_joy:" => "\xF0\x9F\x98\x82",
  207. ":grinning_face_with_smiling_eyes:" => "\xF0\x9F\x98\x81",
  208. ":smiling_face_with_open_mouth:" => "\xF0\x9F\x98\x83",
  209. ":smiling_face_with_open_mouth_and_cold_sweat:" => "\xF0\x9F\x98\x85",
  210. ":smiling_face_with_open_mouth_and_tightly_closed_eyes:" => "\xF0\x9F\x98\x86",
  211. ":winking_face:" => "\xF0\x9F\x98\x89",
  212. ":smiling_face_with_smiling_eyes:" => "\xF0\x9F\x98\x8A",
  213. ":face_savouring_delicious_food:" => "\xF0\x9F\x98\x8B",
  214. ":relieved_face:" => "\xF0\x9F\x98\x8C",
  215. ":smiling_face_with_heart_shaped_eyes:" => "\xF0\x9F\x98\x8D",
  216. ":smiling_face_with_sunglasses:" => "\xF0\x9F\x98\x8E",
  217. ":smirking_face:" => "\xF0\x9F\x98\x8F",
  218. ":neutral_face:" => "\xF0\x9F\x98\x90",
  219. ":expressionless_face:" => "\xF0\x9F\x98\x91",
  220. ":unamused_face:" => "\xF0\x9F\x98\x92",
  221. ":face_with_cold_sweat:" => "\xF0\x9F\x98\x93",
  222. ":pensive_face:" => "\xF0\x9F\x98\x94",
  223. ":confused_face:" => "\xF0\x9F\x98\x95",
  224. ":confounded_face:" => "\xF0\x9F\x98\x96",
  225. ":kissing_face:" => "\xF0\x9F\x98\x97",
  226. ":face_throwing_a_kiss:" => "\xF0\x9F\x98\x98",
  227. ":kissing_face_with_smiling_eyes:" => "\xF0\x9F\x98\x99",
  228. ":kissing_face_with_closed_eyes:" => "\xF0\x9F\x98\x9A",
  229. ":face_with_stuck_out_tongue:" => "\xF0\x9F\x98\x9B",
  230. ":face_with_stuck_out_tongue_and_winking_eye:" => "\xF0\x9F\x98\x9C",
  231. ":face_with_stuck_out_tongue_and_tightly_closed_eyes:" => "\xF0\x9F\x98\x9D",
  232. ":disappointed_face:" => "\xF0\x9F\x98\x9E",
  233. ":worried_face:" => "\xF0\x9F\x98\x9F",
  234. ":angry_face:" => "\xF0\x9F\x98\xA0",
  235. ":face_with_symbols_on_mouth:" => "\xF0\x9F\x98\xA1",
  236. );
  237. foreach ($map as $key => $value) {
  238. $content = str_replace($key, $value, $content);
  239. }
  240. return $content;
  241. }
  242. /**
  243. * Render a string of an HTML content and output it.
  244. * Used to ouput the page when viewed from a server (Dolibarr or Apache).
  245. *
  246. * @param string $content Content string
  247. * @param string $contenttype Content type
  248. * @param int $containerid Contenair id
  249. * @return void
  250. * @see dolWebsiteReplacementOfLinks() for function used to replace content in the backoffice context.
  251. */
  252. function dolWebsiteOutput($content, $contenttype = 'html', $containerid = '')
  253. {
  254. global $db, $langs, $conf, $user;
  255. global $dolibarr_main_url_root, $dolibarr_main_data_root;
  256. global $website;
  257. global $includehtmlcontentopened;
  258. $nbrep = 0;
  259. dol_syslog("dolWebsiteOutput start - contenttype=".$contenttype." containerid=".$containerid." USEDOLIBARREDITOR=".(defined('USEDOLIBARREDITOR') ? '1' : '')." USEDOLIBARRSERVER=".(defined('USEDOLIBARRSERVER') ? '1' : '').' includehtmlcontentopened='.$includehtmlcontentopened);
  260. //print $containerid.' '.$content;
  261. // Define $urlwithroot
  262. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  263. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  264. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  265. if (defined('USEDOLIBARREDITOR')) { // REPLACEMENT OF LINKS When page called from Dolibarr editor
  266. // We remove the <head> part of content
  267. if ($contenttype == 'html') {
  268. $content = preg_replace('/<head>.*<\/head>/ims', '', $content);
  269. $content = preg_replace('/^.*<body(\s[^>]*)*>/ims', '', $content);
  270. $content = preg_replace('/<\/body(\s[^>]*)*>.*$/ims', '', $content);
  271. }
  272. } elseif (defined('USEDOLIBARRSERVER')) { // REPLACEMENT OF LINKS When page called from Dolibarr server
  273. $content = str_replace('<link rel="stylesheet" href="/styles.css', '<link rel="stylesheet" href="styles.css', $content);
  274. $content = str_replace(' async src="/javascript.js', ' async src="javascript.js', $content);
  275. // Protect the link styles.css.php to any replacement that we make after.
  276. $content = str_replace('href="styles.css.php', 'href="!~!~!~styles.css.php', $content);
  277. $content = str_replace('src="javascript.css.php', 'src="!~!~!~javascript.css.php', $content);
  278. $content = str_replace('href="http', 'href="!~!~!~http', $content);
  279. $content = str_replace('xlink:href="', 'xlink:href="!~!~!~', $content);
  280. $content = str_replace('href="//', 'href="!~!~!~//', $content);
  281. $content = str_replace('src="//', 'src="!~!~!~//', $content);
  282. $content = str_replace(array('src="viewimage.php', 'src="/viewimage.php'), 'src="!~!~!~/viewimage.php', $content);
  283. $content = str_replace('src="'.DOL_URL_ROOT.'/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
  284. $content = str_replace(array('href="document.php', 'href="/document.php'), 'href="!~!~!~/document.php', $content);
  285. $content = str_replace('href="'.DOL_URL_ROOT.'/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
  286. // Replace relative link / with dolibarr URL: ...href="/"...
  287. $content = preg_replace('/(href=")\/\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'"', $content, -1, $nbrep);
  288. // Replace relative link /xxx.php#aaa or /xxx.php with dolibarr URL: ...href="....php" (we discard param ?...)
  289. $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2\3"', $content, -1, $nbrep);
  290. // Replace relative link /xxx.php?a=b&c=d#aaa or /xxx.php?a=b&c=d with dolibarr URL
  291. // Warning: we may replace twice if href="..." was inside an include (dolWebsiteOutput called by include and the by final page), that's why
  292. // at end we replace the '!~!~!~' only if we are in final parent page.
  293. $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php\?([^#\"<>]*)(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2&\3\4"', $content, -1, $nbrep);
  294. // Replace relative link without .php like /xxx#aaa or /xxx with dolibarr URL: ...href="....php"
  295. $content = preg_replace('/(href=")\/?([a-zA-Z0-9\-_#]+)(\"|\?)/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2\3', $content, -1, $nbrep);
  296. // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: href="/document.php?modulepart=" => href="/dolibarr/document.php?modulepart="
  297. $content = preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  298. $content = preg_replace('/(src=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  299. // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: href="/viewimage.php?modulepart=" => href="/dolibarr/viewimage.php?modulepart="
  300. $content = preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  301. $content = preg_replace('/(src=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  302. $content = preg_replace('/(url\(")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
  303. // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
  304. $content = preg_replace('/url\((["\']?)\/?medias\//', 'url(\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  305. $content = preg_replace('/data-slide-bg=(["\']?)\/?medias\//', 'data-slide-bg=\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  306. // <img src="medias/...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  307. // <img src="...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  308. $content = preg_replace('/(<img[^>]*src=")\/?medias\//', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  309. // <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
  310. $content = preg_replace('/(<img[^>]*src=")\/?([^:\"\!]+)\"/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=\2"', $content, -1, $nbrep);
  311. // <img src="viewimage.php/modulepart=medias&file=image.png" => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png"
  312. $content = preg_replace('/(<img[^>]*src=")(\/?viewimage\.php)/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content, -1, $nbrep);
  313. // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
  314. $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
  315. // Fix relative URL
  316. $content = str_replace('src="!~!~!~/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
  317. $content = str_replace('href="!~!~!~/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
  318. // Remove the protection tag !~!~!~, but only if this is the parent page and not an include
  319. if (empty($includehtmlcontentopened)) {
  320. $content = str_replace('!~!~!~', '', $content);
  321. }
  322. } else { // REPLACEMENT OF LINKS When page called from virtual host web server
  323. $symlinktomediaexists = 1;
  324. if ($website->virtualhost) {
  325. $content = preg_replace('/^(<link[^>]*rel="canonical" href=")\//m', '\1'.$website->virtualhost.'/', $content, -1, $nbrep);
  326. }
  327. //print 'rrrrrrrrr'.$website->virtualhost.$content;
  328. // Make a change into HTML code to allow to include images from medias directory correct with direct link for virtual server
  329. // <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
  330. // become
  331. // <img alt="" src="'.$urlwithroot.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
  332. if (!$symlinktomediaexists) {
  333. // <img src="image.png... => <img src="medias/image.png...
  334. $content = preg_replace('/(<img[^>]*src=")\/?image\//', '\1/wrapper.php?modulepart=medias&file=medias/image/', $content, -1, $nbrep);
  335. $content = preg_replace('/(url\(["\']?)\/?image\//', '\1/wrapper.php?modulepart=medias&file=medias/image/', $content, -1, $nbrep);
  336. $content = preg_replace('/(<script[^>]*src=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
  337. $content = preg_replace('/(<a[^>]*href=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
  338. $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
  339. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
  340. $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
  341. $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
  342. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
  343. $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)hashp=([^\)]*)(["\']?\))/', '\1/wrapper.php\2hashp\3\4', $content, -1, $nbrep);
  344. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=mycompany([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=mycompany\3file=\4\5', $content, -1, $nbrep);
  345. // If some links to documents or viewimage remains, we replace with wrapper
  346. $content = preg_replace('/(<img[^>]*src=")\/?viewimage\.php/', '\1/wrapper.php', $content, -1, $nbrep);
  347. $content = preg_replace('/(<a[^>]*href=")\/?documents\.php/', '\1/wrapper.php', $content, -1, $nbrep);
  348. } else {
  349. // <img src="image.png... => <img src="medias/image.png...
  350. $content = preg_replace('/(<img[^>]*src=")\/?image\//', '\1/medias/image/', $content, -1, $nbrep);
  351. $content = preg_replace('/(url\(["\']?)\/?image\//', '\1/medias/image/', $content, -1, $nbrep);
  352. $content = preg_replace('/(<script[^>]*src=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
  353. $content = preg_replace('/(<a[^>]*href=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
  354. $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
  355. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
  356. $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1/medias/\4\5', $content, -1, $nbrep);
  357. $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
  358. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
  359. $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)hashp=([^\)]*)(["\']?\))/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
  360. $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=mycompany([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=mycompany\3file=\4\5', $content, -1, $nbrep);
  361. // If some links to documents or viewimage remains, we replace with wrapper
  362. $content = preg_replace('/(<img[^>]*src=")\/?viewimage\.php/', '\1/wrapper.php', $content, -1, $nbrep);
  363. $content = preg_replace('/(<a[^>]*href=")\/?document\.php/', '\1/wrapper.php', $content, -1, $nbrep);
  364. }
  365. }
  366. if (!defined('USEDOLIBARREDITOR')) {
  367. $content = str_replace(' contenteditable="true"', ' contenteditable="false"', $content);
  368. }
  369. if (getDolGlobalString('WEBSITE_ADD_CSS_TO_BODY')) {
  370. $content = str_replace('<body id="bodywebsite" class="bodywebsite', '<body id="bodywebsite" class="bodywebsite ' . getDolGlobalString('WEBSITE_ADD_CSS_TO_BODY'), $content);
  371. }
  372. $content = dolReplaceSmileyCodeWithUTF8($content);
  373. dol_syslog("dolWebsiteOutput end");
  374. print $content;
  375. }
  376. /**
  377. * Increase the website counter of page access.
  378. *
  379. * @param int $websiteid ID of website
  380. * @param string $websitepagetype Type of page ('blogpost', 'page', ...)
  381. * @param int $websitepageid ID of page
  382. * @return int Return integer <0 if KO, >0 if OK
  383. */
  384. function dolWebsiteIncrementCounter($websiteid, $websitepagetype, $websitepageid)
  385. {
  386. if (!getDolGlobalInt('WEBSITE_PERF_DISABLE_COUNTERS')) {
  387. //dol_syslog("dolWebsiteIncrementCounter websiteid=".$websiteid." websitepagetype=".$websitepagetype." websitepageid=".$websitepageid);
  388. if (in_array($websitepagetype, array('blogpost', 'page'))) {
  389. global $db;
  390. $tmpnow = dol_getdate(dol_now('gmt'), true, 'gmt');
  391. $sql = "UPDATE ".$db->prefix()."website SET ";
  392. $sql .= " pageviews_total = pageviews_total + 1,";
  393. $sql .= " pageviews_month = pageviews_month + 1,";
  394. // if last access was done during previous month, we save pageview_month into pageviews_previous_month
  395. $sql .= " pageviews_previous_month = ".$db->ifsql("lastaccess < '".$db->idate(dol_mktime(0, 0, 0, $tmpnow['mon'], 1, $tmpnow['year'], 'gmt', 0), 'gmt')."'", 'pageviews_month', 'pageviews_previous_month').",";
  396. $sql .= " lastaccess = '".$db->idate(dol_now('gmt'), 'gmt')."'";
  397. $sql .= " WHERE rowid = ".((int) $websiteid);
  398. $resql = $db->query($sql);
  399. if (! $resql) {
  400. return -1;
  401. }
  402. }
  403. }
  404. return 1;
  405. }
  406. /**
  407. * Format img tags to introduce viewimage on img src.
  408. *
  409. * @param string $content Content string
  410. * @return void
  411. * @see dolWebsiteOutput()
  412. */
  413. /*
  414. function dolWebsiteSaveContent($content)
  415. {
  416. global $db, $langs, $conf, $user;
  417. global $dolibarr_main_url_root, $dolibarr_main_data_root;
  418. //dol_syslog("dolWebsiteSaveContent start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
  419. // Define $urlwithroot
  420. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  421. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  422. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  423. //$content = preg_replace('/(<img.*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
  424. return $content;
  425. }
  426. */
  427. /**
  428. * Make a redirect to another container.
  429. *
  430. * @param string $containerref Ref of container to redirect to (Example: 'mypage' or 'mypage.php').
  431. * @param string $containeraliasalt Ref of alternative aliases to redirect to.
  432. * @param int $containerid Id of container.
  433. * @param int $permanent 0=Use temporary redirect 302, 1=Use permanent redirect 301
  434. * @return void
  435. */
  436. function redirectToContainer($containerref, $containeraliasalt = '', $containerid = 0, $permanent = 0)
  437. {
  438. global $db, $website;
  439. $newurl = '';
  440. $result = 0;
  441. // We make redirect using the alternative alias, we must find the real $containerref
  442. if ($containeraliasalt) {
  443. include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
  444. $tmpwebsitepage = new WebsitePage($db);
  445. $result = $tmpwebsitepage->fetch(0, $website->id, '', $containeraliasalt);
  446. if ($result > 0) {
  447. $containerref = $tmpwebsitepage->pageurl;
  448. } else {
  449. print "Error, page contains a redirect to the alternative alias '".$containeraliasalt."' that does not exists in web site (".$website->id." / ".$website->ref.")";
  450. exit;
  451. }
  452. }
  453. if (defined('USEDOLIBARREDITOR')) {
  454. /*print '<div class="margintoponly marginleftonly">';
  455. print "This page contains dynamic code that make a redirect to '".$containerref."' in your current context. Redirect has been canceled as it is not supported in edition mode.";
  456. print '</div>';*/
  457. $text = "This page contains dynamic code that make a redirect to '".$containerref."' in your current context. Redirect has been canceled as it is not supported in edition mode.";
  458. setEventMessages($text, null, 'warnings', 'WEBSITEREDIRECTDISABLED'.$containerref);
  459. return;
  460. }
  461. if (defined('USEDOLIBARRSERVER')) { // When page called from Dolibarr server
  462. // Check new container exists
  463. if (!$containeraliasalt) { // If containeraliasalt set, we already did the test
  464. include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
  465. $tmpwebsitepage = new WebsitePage($db);
  466. $result = $tmpwebsitepage->fetch(0, $website->id, $containerref);
  467. unset($tmpwebsitepage);
  468. }
  469. if ($result > 0) {
  470. $currenturi = $_SERVER["REQUEST_URI"]; // Example: /public/website/index.php?website=mywebsite.com&pageref=mywebsite-home&nocache=1708177483
  471. $regtmp = array();
  472. if (preg_match('/&pageref=([^&]+)/', $currenturi, $regtmp)) {
  473. if ($regtmp[0] == $containerref) {
  474. print "Error, page with uri '.$currenturi.' try a redirect to the same alias page '".$containerref."' in web site '".$website->ref."'";
  475. exit;
  476. } else {
  477. $newurl = preg_replace('/&pageref=([^&]+)/', '&pageref='.$containerref, $currenturi);
  478. }
  479. } else {
  480. $newurl = $currenturi.'&pageref='.urlencode($containerref);
  481. }
  482. }
  483. } else { // When page called from virtual host server
  484. $newurl = '/'.$containerref.'.php';
  485. $newurl = $newurl.(empty($_SERVER["QUERY_STRING"]) ? '' : '?'.$_SERVER["QUERY_STRING"]);
  486. }
  487. if ($newurl) {
  488. if ($permanent) {
  489. header("Status: 301 Moved Permanently", false, 301);
  490. }
  491. header("Location: ".$newurl);
  492. exit;
  493. } else {
  494. print "Error, page contains a redirect to the alias page '".$containerref."' that does not exists in web site (".$website->id." / ".$website->ref.")";
  495. exit;
  496. }
  497. }
  498. /**
  499. * Clean an HTML page to report only content, so we can include it into another page.
  500. * It outputs content of file sanitized from html and body part.
  501. *
  502. * @param string $containerref Path to file to include (must be a page from website root. Example: 'mypage.php' means 'mywebsite/mypage.php')
  503. * @return void
  504. */
  505. function includeContainer($containerref)
  506. {
  507. global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running included containers.
  508. global $includehtmlcontentopened;
  509. global $websitekey, $websitepagefile;
  510. $MAXLEVEL = 20;
  511. if (!preg_match('/\.php$/i', $containerref)) {
  512. $containerref .= '.php';
  513. }
  514. $fullpathfile = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$websitekey.'/'.$containerref;
  515. if (empty($includehtmlcontentopened)) {
  516. $includehtmlcontentopened = 0;
  517. }
  518. $includehtmlcontentopened++;
  519. if ($includehtmlcontentopened > $MAXLEVEL) {
  520. print 'ERROR: RECURSIVE CONTENT LEVEL. Depth of recursive call is more than the limit of '.((int) $MAXLEVEL).".\n";
  521. return;
  522. }
  523. //dol_syslog("Include container ".$containerref.' includehtmlcontentopened='.$includehtmlcontentopened);
  524. // file_get_contents is not possible. We must execute code with include
  525. //$content = file_get_contents($fullpathfile);
  526. //print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $content);*/
  527. ob_start();
  528. $res = include $fullpathfile; // Include because we want to execute code content
  529. $tmpoutput = ob_get_contents();
  530. ob_end_clean();
  531. print "\n".'<!-- include '.$websitekey.'/'.$containerref.(is_object($websitepage) ? ' parent id='.$websitepage->id : '').' level = '.$includehtmlcontentopened.' -->'."\n";
  532. print preg_replace(array('/^.*<body[^>]*>/ims', '/<\/body>.*$/ims'), array('', ''), $tmpoutput);
  533. if (!$res) {
  534. print 'ERROR: FAILED TO INCLUDE PAGE '.$containerref.".\n";
  535. }
  536. $includehtmlcontentopened--;
  537. }
  538. /**
  539. * Return HTML content to add structured data for an article, news or Blog Post. Use the json-ld format.
  540. * Example:
  541. * <?php getStructureData('blogpost'); ?>
  542. * <?php getStructureData('software', array('name'=>'Name', 'os'=>'Windows', 'price'=>10)); ?>
  543. *
  544. * @param string $type 'blogpost', 'product', 'software', 'organization', 'qa', ...
  545. * @param array $data Array of data parameters for structured data
  546. * @return string HTML content
  547. */
  548. function getStructuredData($type, $data = array())
  549. {
  550. global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs, $pagelangs; // Very important. Required to have var available when running inluded containers.
  551. $type = strtolower($type);
  552. if ($type == 'software') {
  553. $ret = '<!-- Add structured data for entry in a software annuary -->'."\n";
  554. $ret .= '<script nonce="'.getNonce().'" type="application/ld+json">'."\n";
  555. $ret .= '{
  556. "@context": "https://schema.org",
  557. "@type": "SoftwareApplication",
  558. "name": "'.dol_escape_json($data['name']).'",
  559. "operatingSystem": "'.dol_escape_json($data['os']).'",
  560. "applicationCategory": "https://schema.org/'.dol_escape_json($data['applicationCategory']).'",';
  561. if (!empty($data['ratingcount'])) {
  562. $ret .= '
  563. "aggregateRating": {
  564. "@type": "AggregateRating",
  565. "ratingValue": "'.dol_escape_json($data['ratingvalue']).'",
  566. "ratingCount": "'.dol_escape_json($data['ratingcount']).'"
  567. },';
  568. }
  569. $ret .= '
  570. "offers": {
  571. "@type": "Offer",
  572. "price": "'.dol_escape_json($data['price']).'",
  573. "priceCurrency": "'.dol_escape_json($data['currency'] ? $data['currency'] : $conf->currency).'"
  574. }
  575. }'."\n";
  576. $ret .= '</script>'."\n";
  577. } elseif ($type == 'organization') {
  578. $companyname = $mysoc->name;
  579. $url = $mysoc->url;
  580. $ret = '<!-- Add structured data for organization -->'."\n";
  581. $ret .= '<script nonce="'.getNonce().'" type="application/ld+json">'."\n";
  582. $ret .= '{
  583. "@context": "https://schema.org",
  584. "@type": "Organization",
  585. "name": "'.dol_escape_json(!empty($data['name']) ? $data['name'] : $companyname).'",
  586. "url": "'.dol_escape_json(!empty($data['url']) ? $data['url'] : $url).'",
  587. "logo": "'.($data['logo'] ? dol_escape_json($data['logo']) : '/wrapper.php?modulepart=mycompany&file=logos%2F'.urlencode($mysoc->logo)).'",
  588. "contactPoint": {
  589. "@type": "ContactPoint",
  590. "contactType": "Contact",
  591. "email": "'.dol_escape_json(!empty($data['email']) ? $data['email'] : $mysoc->email).'"
  592. }'."\n";
  593. if (is_array($mysoc->socialnetworks) && count($mysoc->socialnetworks) > 0) {
  594. $ret .= ",\n";
  595. $ret .= '"sameAs": [';
  596. $i = 0;
  597. foreach ($mysoc->socialnetworks as $key => $value) {
  598. if ($key == 'linkedin') {
  599. $ret .= '"https://www.'.$key.'.com/company/'.dol_escape_json($value).'"';
  600. } elseif ($key == 'youtube') {
  601. $ret .= '"https://www.'.$key.'.com/user/'.dol_escape_json($value).'"';
  602. } else {
  603. $ret .= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"';
  604. }
  605. $i++;
  606. if ($i < count($mysoc->socialnetworks)) {
  607. $ret .= ', ';
  608. }
  609. }
  610. $ret .= ']'."\n";
  611. }
  612. $ret .= '}'."\n";
  613. $ret .= '</script>'."\n";
  614. } elseif ($type == 'blogpost') {
  615. if (!empty($websitepage->author_alias)) {
  616. //include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  617. //$tmpuser = new User($db);
  618. //$restmpuser = $tmpuser->fetch($websitepage->fk_user_creat);
  619. $pageurl = $websitepage->pageurl;
  620. $title = $websitepage->title;
  621. $image = $websitepage->image;
  622. $companyname = $mysoc->name;
  623. $description = $websitepage->description;
  624. $pageurl = str_replace('__WEBSITE_KEY__', $website->ref, $pageurl);
  625. $title = str_replace('__WEBSITE_KEY__', $website->ref, $title);
  626. $image = '/medias'.(preg_match('/^\//', $image) ? '' : '/').str_replace('__WEBSITE_KEY__', $website->ref, $image);
  627. $companyname = str_replace('__WEBSITE_KEY__', $website->ref, $companyname);
  628. $description = str_replace('__WEBSITE_KEY__', $website->ref, $description);
  629. $ret = '<!-- Add structured data for blog post -->'."\n";
  630. $ret .= '<script nonce="'.getNonce().'" type="application/ld+json">'."\n";
  631. $ret .= '{
  632. "@context": "https://schema.org",
  633. "@type": "NewsArticle",
  634. "mainEntityOfPage": {
  635. "@type": "WebPage",
  636. "@id": "'.dol_escape_json($pageurl).'"
  637. },
  638. "headline": "'.dol_escape_json($title).'",
  639. "image": [
  640. "'.dol_escape_json($image).'"
  641. ],
  642. "dateCreated": "'.dol_print_date($websitepage->date_creation, 'dayhourrfc').'",
  643. "datePublished": "'.dol_print_date($websitepage->date_creation, 'dayhourrfc').'",
  644. "dateModified": "'.dol_print_date($websitepage->date_modification, 'dayhourrfc').'",
  645. "author": {
  646. "@type": "Person",
  647. "name": "'.dol_escape_json($websitepage->author_alias).'"
  648. },
  649. "publisher": {
  650. "@type": "Organization",
  651. "name": "'.dol_escape_json($companyname).'",
  652. "logo": {
  653. "@type": "ImageObject",
  654. "url": "/wrapper.php?modulepart=mycompany&file=logos%2F'.urlencode($mysoc->logo).'"
  655. }
  656. },'."\n";
  657. if ($websitepage->keywords) {
  658. $ret .= '"keywords": [';
  659. $i = 0;
  660. $arrayofkeywords = explode(',', $websitepage->keywords);
  661. foreach ($arrayofkeywords as $keyword) {
  662. $ret .= '"'.dol_escape_json($keyword).'"';
  663. $i++;
  664. if ($i < count($arrayofkeywords)) {
  665. $ret .= ', ';
  666. }
  667. }
  668. $ret .= '],'."\n";
  669. }
  670. $ret .= '"description": "'.dol_escape_json($description).'"';
  671. $ret .= "\n".'}'."\n";
  672. $ret .= '</script>'."\n";
  673. } else {
  674. $ret = '<!-- no structured data inserted inline inside blogpost because no author_alias defined -->'."\n";
  675. }
  676. } elseif ($type == 'product') {
  677. $ret = '<!-- Add structured data for product -->'."\n";
  678. $ret .= '<script nonce="'.getNonce().'" type="application/ld+json">'."\n";
  679. $ret .= '{
  680. "@context": "https://schema.org/",
  681. "@type": "Product",
  682. "name": "'.dol_escape_json($data['label']).'",
  683. "image": [
  684. "'.dol_escape_json($data['image']).'",
  685. ],
  686. "description": "'.dol_escape_json($data['description']).'",
  687. "sku": "'.dol_escape_json($data['ref']).'",
  688. "brand": {
  689. "@type": "Thing",
  690. "name": "'.dol_escape_json($data['brand']).'"
  691. },
  692. "author": {
  693. "@type": "Person",
  694. "name": "'.dol_escape_json($data['author']).'"
  695. }
  696. },
  697. "offers": {
  698. "@type": "Offer",
  699. "url": "https://example.com/anvil",
  700. "priceCurrency": "'.dol_escape_json($data['currency'] ? $data['currency'] : $conf->currency).'",
  701. "price": "'.dol_escape_json($data['price']).'",
  702. "itemCondition": "https://schema.org/UsedCondition",
  703. "availability": "https://schema.org/InStock",
  704. "seller": {
  705. "@type": "Organization",
  706. "name": "'.dol_escape_json($mysoc->name).'"
  707. }
  708. }
  709. }'."\n";
  710. $ret .= '</script>'."\n";
  711. } elseif ($type == 'qa') {
  712. $ret = '<!-- Add structured data for QA -->'."\n";
  713. $ret .= '<script nonce="'.getNonce().'" type="application/ld+json">'."\n";
  714. $ret .= '{
  715. "@context": "https://schema.org/",
  716. "@type": "QAPage",
  717. "mainEntity": {
  718. "@type": "Question",
  719. "name": "'.dol_escape_json($data['name']).'",
  720. "text": "'.dol_escape_json($data['name']).'",
  721. "answerCount": 1,
  722. "author": {
  723. "@type": "Person",
  724. "name": "'.dol_escape_json($data['author']).'"
  725. }
  726. "acceptedAnswer": {
  727. "@type": "Answer",
  728. "text": "'.dol_escape_json(dol_string_nohtmltag(dolStripPhpCode($data['description']))).'",
  729. "author": {
  730. "@type": "Person",
  731. "name": "'.dol_escape_json($data['author']).'"
  732. }
  733. }
  734. }
  735. }'."\n";
  736. $ret .= '</script>'."\n";
  737. }
  738. return $ret;
  739. }
  740. /**
  741. * Return HTML content to add as header card for an article, news or Blog Post or home page.
  742. *
  743. * @param array $params Array of parameters
  744. * @return string HTML content
  745. */
  746. function getSocialNetworkHeaderCards($params = null)
  747. {
  748. global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
  749. $out = '';
  750. if ($website->virtualhost) {
  751. $pageurl = $websitepage->pageurl;
  752. $title = $websitepage->title;
  753. $image = $websitepage->image;
  754. $companyname = $mysoc->name;
  755. $description = $websitepage->description;
  756. $pageurl = str_replace('__WEBSITE_KEY__', $website->ref, $pageurl);
  757. $title = str_replace('__WEBSITE_KEY__', $website->ref, $title);
  758. $image = '/medias'.(preg_match('/^\//', $image) ? '' : '/').str_replace('__WEBSITE_KEY__', $website->ref, $image);
  759. $companyname = str_replace('__WEBSITE_KEY__', $website->ref, $companyname);
  760. $description = str_replace('__WEBSITE_KEY__', $website->ref, $description);
  761. $shortlangcode = '';
  762. if ($websitepage->lang) {
  763. $shortlangcode = substr($websitepage->lang, 0, 2); // en_US or en-US -> en
  764. }
  765. if (empty($shortlangcode)) {
  766. $shortlangcode = substr($website->lang, 0, 2); // en_US or en-US -> en
  767. }
  768. $fullurl = $website->virtualhost.'/'.$websitepage->pageurl.'.php';
  769. $canonicalurl = $website->virtualhost.(($websitepage->id == $website->fk_default_home) ? '/' : (($shortlangcode != substr($website->lang, 0, 2) ? '/'.$shortlangcode : '').'/'.$websitepage->pageurl.'.php'));
  770. $hashtags = trim(join(' #', array_map('trim', explode(',', $websitepage->keywords))));
  771. // Open Graph
  772. $out .= '<meta name="og:type" content="website">'."\n"; // TODO If blogpost, use type article
  773. $out .= '<meta name="og:title" content="'.$websitepage->title.'">'."\n";
  774. if ($websitepage->image) {
  775. $out .= '<meta name="og:image" content="'.$website->virtualhost.$image.'">'."\n";
  776. }
  777. $out .= '<meta name="og:url" content="'.$canonicalurl.'">'."\n";
  778. // Twitter
  779. $out .= '<meta name="twitter:card" content="summary">'."\n";
  780. if (!empty($params) && !empty($params['twitter_account'])) {
  781. $out .= '<meta name="twitter:site" content="@'.$params['twitter_account'].'">'."\n";
  782. $out .= '<meta name="twitter:creator" content="@'.$params['twitter_account'].'">'."\n";
  783. }
  784. $out .= '<meta name="twitter:title" content="'.$websitepage->title.'">'."\n";
  785. if ($websitepage->description) {
  786. $out .= '<meta name="twitter:description" content="'.$websitepage->description.'">'."\n";
  787. }
  788. if ($websitepage->image) {
  789. $out .= '<meta name="twitter:image" content="'.$website->virtualhost.$image.'">'."\n";
  790. }
  791. //$out .= '<meta name="twitter:domain" content="'.getDomainFromURL($website->virtualhost, 1).'">';
  792. /*
  793. $out .= '<meta name="twitter:app:name:iphone" content="">';
  794. $out .= '<meta name="twitter:app:name:ipad" content="">';
  795. $out .= '<meta name="twitter:app:name:googleplay" content="">';
  796. $out .= '<meta name="twitter:app:url:iphone" content="">';
  797. $out .= '<meta name="twitter:app:url:ipad" content="">';
  798. $out .= '<meta name="twitter:app:url:googleplay" content="">';
  799. $out .= '<meta name="twitter:app:id:iphone" content="">';
  800. $out .= '<meta name="twitter:app:id:ipad" content="">';
  801. $out .= '<meta name="twitter:app:id:googleplay" content="">';
  802. */
  803. }
  804. return $out;
  805. }
  806. /**
  807. * Return HTML content to add structured data for an article, news or Blog Post.
  808. *
  809. * @return string HTML content
  810. */
  811. function getSocialNetworkSharingLinks()
  812. {
  813. global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
  814. $out = '<!-- section for social network sharing of page -->'."\n";
  815. if ($website->virtualhost) {
  816. $fullurl = $website->virtualhost.'/'.$websitepage->pageurl.'.php';
  817. $hashtags = trim(join(' #', array_map('trim', explode(',', $websitepage->keywords))));
  818. $out .= '<div class="dol-social-share">'."\n";
  819. // Twitter
  820. $out .= '<div class="dol-social-share-tw">'."\n";
  821. $out .= '<a href="https://twitter.com/share" class="twitter-share-button" data-url="'.$fullurl.'" data-text="'.dol_escape_htmltag($websitepage->description).'" data-lang="'.$websitepage->lang.'" data-size="small" data-related="" data-hashtags="'.preg_replace('/^#/', '', $hashtags).'" data-count="horizontal">Tweet</a>';
  822. $out .= '<script nonce="'.getNonce().'">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?\'http\':\'https\';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+\'://platform.twitter.com/widgets.js\';fjs.parentNode.insertBefore(js,fjs);}}(document, \'script\', \'twitter-wjs\');</script>';
  823. $out .= '</div>'."\n";
  824. // Reddit
  825. $out .= '<div class="dol-social-share-reddit">'."\n";
  826. $out .= '<a href="https://www.reddit.com/submit" target="_blank" rel="noopener noreferrer external" onclick="window.location = \'https://www.reddit.com/submit?url='.$fullurl.'\'; return false">';
  827. $out .= '<span class="dol-social-share-reddit-span">Reddit</span>';
  828. $out .= '</a>';
  829. $out .= '</div>'."\n";
  830. // Facebook
  831. $out .= '<div class="dol-social-share-fbl">'."\n";
  832. $out .= '<div id="fb-root"></div>'."\n";
  833. $out .= '<script nonce="'.getNonce().'">(function(d, s, id) {
  834. var js, fjs = d.getElementsByTagName(s)[0];
  835. if (d.getElementById(id)) return;
  836. js = d.createElement(s); js.id = id;
  837. js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0&amp;appId=dolibarr.org";
  838. fjs.parentNode.insertBefore(js, fjs);
  839. }(document, \'script\', \'facebook-jssdk\'));</script>
  840. <fb:like
  841. href="'.$fullurl.'"
  842. layout="button_count"
  843. show_faces="false"
  844. width="90"
  845. colorscheme="light"
  846. share="1"
  847. action="like" ></fb:like>'."\n";
  848. $out .= '</div>'."\n";
  849. $out .= "\n</div>\n";
  850. } else {
  851. $out .= '<!-- virtual host not defined in CMS. No way to add sharing buttons -->'."\n";
  852. }
  853. $out .= '<!-- section end for social network sharing of page -->'."\n";
  854. return $out;
  855. }
  856. /**
  857. * Return list of containers object that match a criteria.
  858. * WARNING: This function can be used by websites.
  859. *
  860. * @param string $type Type of container to search into (Example: '', 'page', 'blogpost', 'page,blogpost', ...)
  861. * @param string $algo Algorithm used for search (Example: 'meta' is searching into meta information like title and description, 'content', 'sitefiles', or any combination 'meta,content,...')
  862. * @param string $searchstring Search string
  863. * @param int $max Max number of answers
  864. * @param string $sortfield Sort Fields
  865. * @param string $sortorder Sort order ('DESC' or 'ASC')
  866. * @param string $langcode Language code ('' or 'en', 'fr', 'es', ...)
  867. * @param array $otherfilters Other filters
  868. * @param int $status 0 or 1, or -1 for both
  869. * @return array Array with results of search
  870. */
  871. function getPagesFromSearchCriterias($type, $algo, $searchstring, $max = 25, $sortfield = 'date_creation', $sortorder = 'DESC', $langcode = '', $otherfilters = 'null', $status = 1)
  872. {
  873. global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
  874. $error = 0;
  875. $arrayresult = array('code'=>'', 'list'=>array());
  876. if (!is_object($weblangs)) {
  877. $weblangs = $langs;
  878. }
  879. if (empty($searchstring) && empty($type) && empty($langcode) && empty($otherfilters)) {
  880. $error++;
  881. $arrayresult['code'] = 'KO';
  882. $arrayresult['message'] = $weblangs->trans("EmptySearchString");
  883. } elseif ($searchstring && dol_strlen($searchstring) < 2) {
  884. $weblangs->load("errors");
  885. $error++;
  886. $arrayresult['code'] = 'KO';
  887. $arrayresult['message'] = $weblangs->trans("ErrorSearchCriteriaTooSmall");
  888. } else {
  889. $tmparrayoftype = explode(',', $type);
  890. /*foreach ($tmparrayoftype as $tmptype) {
  891. if (!in_array($tmptype, array('', 'page', 'blogpost'))) {
  892. $error++;
  893. $arrayresult['code'] = 'KO';
  894. $arrayresult['message'] = 'Bad value for parameter type';
  895. break;
  896. }
  897. }*/
  898. }
  899. $searchdone = 0;
  900. $found = 0;
  901. if (!$error && (empty($max) || ($found < $max)) && (preg_match('/meta/', $algo) || preg_match('/content/', $algo))) {
  902. include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
  903. $sql = 'SELECT wp.rowid FROM '.MAIN_DB_PREFIX.'website_page as wp';
  904. if (is_array($otherfilters) && !empty($otherfilters['category'])) {
  905. $sql .= ', '.MAIN_DB_PREFIX.'categorie_website_page as cwp';
  906. }
  907. $sql .= " WHERE wp.fk_website = ".((int) $website->id);
  908. if ($status >= 0) {
  909. $sql .= " AND wp.status = ".((int) $status);
  910. }
  911. if ($langcode) {
  912. $sql .= " AND wp.lang = '".$db->escape($langcode)."'";
  913. }
  914. if ($type) {
  915. $tmparrayoftype = explode(',', $type);
  916. $typestring = '';
  917. foreach ($tmparrayoftype as $tmptype) {
  918. $typestring .= ($typestring ? ", " : "")."'".$db->escape(trim($tmptype))."'";
  919. }
  920. $sql .= " AND wp.type_container IN (".$db->sanitize($typestring, 1).")";
  921. }
  922. $sql .= " AND (";
  923. $searchalgo = '';
  924. if (preg_match('/meta/', $algo)) {
  925. $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.title LIKE '%".$db->escape($db->escapeforlike($searchstring))."%' OR wp.description LIKE '%".$db->escape($db->escapeforlike($searchstring))."%'";
  926. $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.keywords LIKE '".$db->escape($db->escapeforlike($searchstring)).",%' OR wp.keywords LIKE '% ".$db->escape($db->escapeforlike($searchstring))."%'"; // TODO Use a better way to scan keywords
  927. }
  928. if (preg_match('/content/', $algo)) {
  929. $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.content LIKE '%".$db->escape($db->escapeforlike($searchstring))."%'";
  930. }
  931. $sql .= $searchalgo;
  932. if (is_array($otherfilters) && !empty($otherfilters['category'])) {
  933. $sql .= ' AND cwp.fk_website_page = wp.rowid AND cwp.fk_categorie = '.((int) $otherfilters['category']);
  934. }
  935. $sql .= ")";
  936. $sql .= $db->order($sortfield, $sortorder);
  937. $sql .= $db->plimit($max);
  938. //print $sql;
  939. $resql = $db->query($sql);
  940. if ($resql) {
  941. $i = 0;
  942. while (($obj = $db->fetch_object($resql)) && ($i < $max || $max == 0)) {
  943. if ($obj->rowid > 0) {
  944. $tmpwebsitepage = new WebsitePage($db);
  945. $tmpwebsitepage->fetch($obj->rowid);
  946. if ($tmpwebsitepage->id > 0) {
  947. $arrayresult['list'][$obj->rowid] = $tmpwebsitepage;
  948. }
  949. $found++;
  950. }
  951. $i++;
  952. }
  953. } else {
  954. $error++;
  955. $arrayresult['code'] = $db->lasterrno();
  956. $arrayresult['message'] = $db->lasterror();
  957. }
  958. $searchdone = 1;
  959. }
  960. if (!$error && (empty($max) || ($found < $max)) && (preg_match('/sitefiles/', $algo))) {
  961. global $dolibarr_main_data_root;
  962. $pathofwebsite = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$website->ref;
  963. $filehtmlheader = $pathofwebsite.'/htmlheader.html';
  964. $filecss = $pathofwebsite.'/styles.css.php';
  965. $filejs = $pathofwebsite.'/javascript.js.php';
  966. $filerobot = $pathofwebsite.'/robots.txt';
  967. $filehtaccess = $pathofwebsite.'/.htaccess';
  968. $filemanifestjson = $pathofwebsite.'/manifest.json.php';
  969. $filereadme = $pathofwebsite.'/README.md';
  970. $filecontent = file_get_contents($filehtmlheader);
  971. if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
  972. $arrayresult['list'][] = array('type'=>'website_htmlheadercontent');
  973. }
  974. $filecontent = file_get_contents($filecss);
  975. if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
  976. $arrayresult['list'][] = array('type'=>'website_csscontent');
  977. }
  978. $filecontent = file_get_contents($filejs);
  979. if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
  980. $arrayresult['list'][] = array('type'=>'website_jscontent');
  981. }
  982. $filerobot = file_get_contents($filerobot);
  983. if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
  984. $arrayresult['list'][] = array('type'=>'website_robotcontent');
  985. }
  986. $searchdone = 1;
  987. }
  988. if (!$error) {
  989. if ($searchdone) {
  990. $arrayresult['code'] = 'OK';
  991. if (empty($arrayresult['list'])) {
  992. $arrayresult['code'] = 'KO';
  993. $arrayresult['message'] = $weblangs->trans("NoRecordFound");
  994. }
  995. } else {
  996. $error++;
  997. $arrayresult['code'] = 'KO';
  998. $arrayresult['message'] = 'No supported algorithm found';
  999. }
  1000. }
  1001. return $arrayresult;
  1002. }
  1003. /**
  1004. * Download all images found into page content $tmp.
  1005. * If $modifylinks is set, links to images will be replace with a link to viewimage wrapper.
  1006. *
  1007. * @param Website $object Object website
  1008. * @param WebsitePage $objectpage Object website page
  1009. * @param string $urltograb URL to grab (exemple: http://www.nltechno.com/ or http://www.nltechno.com/dir1/ or http://www.nltechno.com/dir1/mapage1)
  1010. * @param string $tmp Content to parse
  1011. * @param string $action Var $action
  1012. * @param string $modifylinks 0=Do not modify content, 1=Replace links with a link to viewimage
  1013. * @param int $grabimages 0=Do not grab images, 1=Grab images
  1014. * @param string $grabimagesinto 'root' or 'subpage'
  1015. * @return void
  1016. */
  1017. function getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks = 0, $grabimages = 1, $grabimagesinto = 'subpage')
  1018. {
  1019. global $conf;
  1020. $error = 0;
  1021. dol_syslog("Call getAllImages with grabimagesinto=".$grabimagesinto);
  1022. $alreadygrabbed = array();
  1023. if (preg_match('/\/$/', $urltograb)) {
  1024. $urltograb .= '.';
  1025. }
  1026. $urltograb = dirname($urltograb); // So urltograb is now http://www.nltechno.com or http://www.nltechno.com/dir1
  1027. // Search X in "img...src=X"
  1028. $regs = array();
  1029. preg_match_all('/<img([^\.\/]+)src="([^>"]+)"([^>]*)>/i', $tmp, $regs);
  1030. foreach ($regs[0] as $key => $val) {
  1031. if (preg_match('/^data:image/i', $regs[2][$key])) {
  1032. continue; // We do nothing for such images
  1033. }
  1034. if (preg_match('/^\//', $regs[2][$key])) {
  1035. $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
  1036. $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
  1037. } else {
  1038. $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file
  1039. }
  1040. $linkwithoutdomain = $regs[2][$key];
  1041. $dirforimages = '/'.$objectpage->pageurl;
  1042. if ($grabimagesinto == 'root') {
  1043. $dirforimages = '';
  1044. }
  1045. // Define $filetosave and $filename
  1046. $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $regs[2][$key]) ? '' : '/').$regs[2][$key];
  1047. if (preg_match('/^http/', $regs[2][$key])) {
  1048. $urltograbbis = $regs[2][$key];
  1049. $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
  1050. $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
  1051. }
  1052. $filename = 'image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
  1053. // Clean the aa/bb/../cc into aa/cc
  1054. $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
  1055. $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
  1056. //var_dump($filetosave);
  1057. //var_dump($filename);
  1058. //exit;
  1059. if (empty($alreadygrabbed[$urltograbbis])) {
  1060. if ($grabimages) {
  1061. $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
  1062. if ($tmpgeturl['curl_error_no']) {
  1063. $error++;
  1064. setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
  1065. $action = 'create';
  1066. } elseif ($tmpgeturl['http_code'] != '200') {
  1067. $error++;
  1068. setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
  1069. $action = 'create';
  1070. } else {
  1071. $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed.
  1072. dol_mkdir(dirname($filetosave));
  1073. $fp = fopen($filetosave, "w");
  1074. fputs($fp, $tmpgeturl['content']);
  1075. fclose($fp);
  1076. dolChmod($filetosave);
  1077. }
  1078. }
  1079. }
  1080. if ($modifylinks) {
  1081. $tmp = preg_replace('/'.preg_quote($regs[0][$key], '/').'/i', '<img'.$regs[1][$key].'src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'"'.$regs[3][$key].'>', $tmp);
  1082. }
  1083. }
  1084. // Search X in "background...url(X)"
  1085. preg_match_all('/background([^\.\/\(;]+)url\([\"\']?([^\)\"\']*)[\"\']?\)/i', $tmp, $regs);
  1086. foreach ($regs[0] as $key => $val) {
  1087. if (preg_match('/^data:image/i', $regs[2][$key])) {
  1088. continue; // We do nothing for such images
  1089. }
  1090. if (preg_match('/^\//', $regs[2][$key])) {
  1091. $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
  1092. $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
  1093. } else {
  1094. $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file
  1095. }
  1096. $linkwithoutdomain = $regs[2][$key];
  1097. $dirforimages = '/'.$objectpage->pageurl;
  1098. if ($grabimagesinto == 'root') {
  1099. $dirforimages = '';
  1100. }
  1101. $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $regs[2][$key]) ? '' : '/').$regs[2][$key];
  1102. if (preg_match('/^http/', $regs[2][$key])) {
  1103. $urltograbbis = $regs[2][$key];
  1104. $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
  1105. $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
  1106. }
  1107. $filename = 'image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
  1108. // Clean the aa/bb/../cc into aa/cc
  1109. $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
  1110. $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
  1111. //var_dump($filetosave);
  1112. //var_dump($filename);
  1113. //exit;
  1114. if (empty($alreadygrabbed[$urltograbbis])) {
  1115. if ($grabimages) {
  1116. $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
  1117. if ($tmpgeturl['curl_error_no']) {
  1118. $error++;
  1119. setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
  1120. $action = 'create';
  1121. } elseif ($tmpgeturl['http_code'] != '200') {
  1122. $error++;
  1123. setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
  1124. $action = 'create';
  1125. } else {
  1126. $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed.
  1127. dol_mkdir(dirname($filetosave));
  1128. $fp = fopen($filetosave, "w");
  1129. fputs($fp, $tmpgeturl['content']);
  1130. fclose($fp);
  1131. dolChmod($filetosave);
  1132. }
  1133. }
  1134. }
  1135. if ($modifylinks) {
  1136. $tmp = preg_replace('/'.preg_quote($regs[0][$key], '/').'/i', 'background'.$regs[1][$key].'url("'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'")', $tmp);
  1137. }
  1138. }
  1139. }