dolibarr  16.0.5
website.lib.php
Go to the documentation of this file.
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 
32 function dolStripPhpCode($str, $replacewith = '')
33 {
34  $str = str_replace('<?=', '<?php', $str);
35 
36  $newstr = '';
37 
38  // Split on each opening tag
39  //$parts = explode('<?php', $str);
40  $parts = preg_split('/'.preg_quote('<?php', '/').'/i', $str);
41 
42  if (!empty($parts)) {
43  $i = 0;
44  foreach ($parts as $part) {
45  if ($i == 0) { // The first part is never php code
46  $i++;
47  $newstr .= $part;
48  continue;
49  }
50  // The second part is the php code. We split on closing tag
51  $partlings = explode('?>', $part);
52  if (!empty($partlings)) {
53  //$phppart = $partlings[0];
54  //remove content before closing tag
55  if (count($partlings) > 1) {
56  $partlings[0] = ''; // Todo why a count > 1 and not >= 1 ?
57  }
58  //append to out string
59  //$newstr .= '<span class="phptag" class="tooltip" title="'.dol_escape_htmltag(dolGetFirstLineOfText($phppart).'...').'">'.$replacewith.'<!-- '.$phppart.' --></span>'.implode('', $partlings);
60  //$newstr .= '<span>'.$replacewith.'<!-- '.$phppart.' --></span>'.implode('', $partlings);
61  $newstr .= '<span phptag>'.$replacewith.'</span>'.implode('', $partlings);
62  //$newstr .= $replacewith.implode('', $partlings);
63  }
64  }
65  }
66  return $newstr;
67 }
68 
76 function dolKeepOnlyPhpCode($str)
77 {
78  $str = str_replace('<?=', '<?php', $str);
79 
80  $newstr = '';
81 
82  // Split on each opening tag
83  //$parts = explode('<?php', $str);
84  $parts = preg_split('/'.preg_quote('<?php', '/').'/i', $str);
85 
86  if (!empty($parts)) {
87  $i = 0;
88  foreach ($parts as $part) {
89  if ($i == 0) { // The first part is never php code
90  $i++;
91  continue;
92  }
93  $newstr .= '<?php';
94  //split on closing tag
95  $partlings = explode('?>', $part, 2);
96  if (!empty($partlings)) {
97  $newstr .= $partlings[0].'?>';
98  } else {
99  $newstr .= $part.'?>';
100  }
101  }
102  }
103  return $newstr;
104 }
105 
118 function dolWebsiteReplacementOfLinks($website, $content, $removephppart = 0, $contenttype = 'html', $containerid = '')
119 {
120  $nbrep = 0;
121 
122  dol_syslog('dolWebsiteReplacementOfLinks start (contenttype='.$contenttype." containerid=".$containerid." USEDOLIBARREDITOR=".(defined('USEDOLIBARREDITOR') ? '1' : '')." USEDOLIBARRSERVER=".(defined('USEDOLIBARRSERVER') ? '1' : '').')', LOG_DEBUG);
123  //if ($contenttype == 'html') { print $content;exit; }
124 
125  // Replace php code. Note $content may come from database and does not contains body tags.
126  $replacewith = '...php...';
127  if ($removephppart) {
128  $replacewith = '';
129  }
130  $content = preg_replace('/value="<\?php((?!\?>).)*\?>\n*/ims', 'value="'.$replacewith.'"', $content);
131 
132  $replacewith = '"callto=#';
133  if ($removephppart) {
134  $replacewith = '';
135  }
136  $content = preg_replace('/"callto:<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
137 
138  $replacewith = '"mailto=#';
139  if ($removephppart) {
140  $replacewith = '';
141  }
142  $content = preg_replace('/"mailto:<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
143 
144  $replacewith = 'src="php';
145  if ($removephppart) {
146  $replacewith = '';
147  }
148  $content = preg_replace('/src="<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
149 
150  $replacewith = 'href="php';
151  if ($removephppart) {
152  $replacewith = '';
153  }
154  $content = preg_replace('/href="<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
155 
156  //$replacewith='<span class="phptag">...php...</span>';
157  $replacewith = '...php...';
158  if ($removephppart) {
159  $replacewith = '';
160  }
161  //$content = preg_replace('/<\?php((?!\?toremove>).)*\?toremove>\n*/ims', $replacewith, $content);
162  /*if ($content === null) {
163  if (preg_last_error() == PREG_JIT_STACKLIMIT_ERROR) $content = 'preg_replace error (when removing php tags) PREG_JIT_STACKLIMIT_ERROR';
164  }*/
165  $content = dolStripPhpCode($content, $replacewith);
166  //var_dump($content);
167 
168  // Protect the link styles.css.php to any replacement that we make after.
169  $content = str_replace('href="styles.css.php', 'href="!~!~!~styles.css.php', $content);
170  $content = str_replace('href="http', 'href="!~!~!~http', $content);
171  $content = str_replace('href="//', 'href="!~!~!~//', $content);
172  $content = str_replace('src="viewimage.php', 'src="!~!~!~/viewimage.php', $content);
173  $content = str_replace('src="/viewimage.php', 'src="!~!~!~/viewimage.php', $content);
174  $content = str_replace('src="'.DOL_URL_ROOT.'/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
175  $content = str_replace('href="document.php', 'href="!~!~!~/document.php', $content);
176  $content = str_replace('href="/document.php', 'href="!~!~!~/document.php', $content);
177  $content = str_replace('href="'.DOL_URL_ROOT.'/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
178 
179  // Replace relative link '/' with dolibarr URL
180  $content = preg_replace('/(href=")\/(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'\2"', $content, -1, $nbrep);
181  // Replace relative link /xxx.php#aaa or /xxx.php with dolibarr URL (we discard param ?...)
182  $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2\3"', $content, -1, $nbrep);
183  // Replace relative link /xxx.php?a=b&c=d#aaa or /xxx.php?a=b&c=d with dolibarr URL
184  $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php\?([^#\"<>]*)(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2&\3\4"', $content, -1, $nbrep);
185 
186  // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
187  $content = preg_replace('/url\((["\']?)\/?medias\//', 'url(\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
188  $content = preg_replace('/data-slide-bg=(["\']?)\/?medias\//', 'data-slide-bg=\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
189 
190  // <img src="medias/...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
191  // <img src="...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
192  $content = preg_replace('/(<img[^>]*src=")\/?medias\//', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
193  // <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
194  $content = preg_replace('/(<img[^>]*src=")\/?([^:\"\!]+)\"/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=\2"', $content, -1, $nbrep);
195  // <img src="viewimage.php/modulepart=medias&file=image.png" => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png"
196  $content = preg_replace('/(<img[^>]*src=")(\/?viewimage\.php)/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content, -1, $nbrep);
197 
198  // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
199  $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1!~!~!~'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
200 
201  // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: ...href="/document.php?modulepart="
202  $content = preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
203  $content = preg_replace('/(src=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
204 
205  // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: ...href="/viewimage.php?modulepart="
206  $content = preg_replace('/(url\(")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
207 
208  // Fix relative URL
209  $content = str_replace('src="!~!~!~/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
210  $content = str_replace('href="!~!~!~/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
211  // Remove the protection tag !~!~!~
212  $content = str_replace('!~!~!~', '', $content);
213 
214  dol_syslog('dolWebsiteReplacementOfLinks end', LOG_DEBUG);
215  //if ($contenttype == 'html') { print $content;exit; }
216 
217  return $content;
218 }
219 
230 function dolWebsiteOutput($content, $contenttype = 'html', $containerid = '')
231 {
232  global $db, $langs, $conf, $user;
233  global $dolibarr_main_url_root, $dolibarr_main_data_root;
234  global $website;
235  global $includehtmlcontentopened;
236 
237  $nbrep = 0;
238 
239  dol_syslog("dolWebsiteOutput start - contenttype=".$contenttype." containerid=".$containerid." USEDOLIBARREDITOR=".(defined('USEDOLIBARREDITOR') ? '1' : '')." USEDOLIBARRSERVER=".(defined('USEDOLIBARRSERVER') ? '1' : '').' includehtmlcontentopened='.$includehtmlcontentopened);
240 
241  //print $containerid.' '.$content;
242 
243  // Define $urlwithroot
244  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
245  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
246  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
247 
248  if (defined('USEDOLIBARREDITOR')) { // REPLACEMENT OF LINKS When page called from Dolibarr editor
249  // We remove the <head> part of content
250  if ($contenttype == 'html') {
251  $content = preg_replace('/<head>.*<\/head>/ims', '', $content);
252  $content = preg_replace('/^.*<body(\s[^>]*)*>/ims', '', $content);
253  $content = preg_replace('/<\/body(\s[^>]*)*>.*$/ims', '', $content);
254  }
255  } elseif (defined('USEDOLIBARRSERVER')) { // REPLACEMENT OF LINKS When page called from Dolibarr server
256  $content = str_replace('<link rel="stylesheet" href="/styles.css', '<link rel="stylesheet" href="styles.css', $content);
257 
258  // Protect the link styles.css.php to any replacement that we make after.
259  $content = str_replace('href="styles.css.php', 'href="!~!~!~styles.css.php', $content);
260  $content = str_replace('href="http', 'href="!~!~!~http', $content);
261  $content = str_replace('href="//', 'href="!~!~!~//', $content);
262  $content = str_replace(array('src="viewimage.php', 'src="/viewimage.php'), 'src="!~!~!~/viewimage.php', $content);
263  $content = str_replace('src="'.DOL_URL_ROOT.'/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
264  $content = str_replace(array('href="document.php', 'href="/document.php'), 'href="!~!~!~/document.php', $content);
265  $content = str_replace('href="'.DOL_URL_ROOT.'/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
266 
267  // Replace relative link / with dolibarr URL: ...href="/"...
268  $content = preg_replace('/(href=")\/\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'"', $content, -1, $nbrep);
269  // Replace relative link /xxx.php#aaa or /xxx.php with dolibarr URL: ...href="....php" (we discard param ?...)
270  $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2\3"', $content, -1, $nbrep);
271  // Replace relative link /xxx.php?a=b&c=d#aaa or /xxx.php?a=b&c=d with dolibarr URL
272  // Warning: we may replace twice if href="..." was inside an include (dolWebsiteOutput called by include and the by final page), that's why
273  // at end we replace the '!~!~!~' only if we are in final parent page.
274  $content = preg_replace('/(href=")\/?([^:\"\!]*)\.php\?([^#\"<>]*)(#[^\"<>]*)?\"/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2&\3\4"', $content, -1, $nbrep);
275  // Replace relative link without .php like /xxx#aaa or /xxx with dolibarr URL: ...href="....php"
276  $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);
277 
278  // Fix relative link /document.php with correct URL after the DOL_URL_ROOT: href="/document.php?modulepart=" => href="/dolibarr/document.php?modulepart="
279  $content = preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
280  $content = preg_replace('/(src=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
281 
282  // Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT: href="/viewimage.php?modulepart=" => href="/dolibarr/viewimage.php?modulepart="
283  $content = preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
284  $content = preg_replace('/(src=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
285  $content = preg_replace('/(url\(")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1!~!~!~'.DOL_URL_ROOT.'\2\3', $content, -1, $nbrep);
286 
287  // Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
288  $content = preg_replace('/url\((["\']?)\/?medias\//', 'url(\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
289  $content = preg_replace('/data-slide-bg=(["\']?)\/?medias\//', 'data-slide-bg=\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
290 
291  // <img src="medias/...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
292  // <img src="...image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
293  $content = preg_replace('/(<img[^>]*src=")\/?medias\//', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
294  // <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
295  $content = preg_replace('/(<img[^>]*src=")\/?([^:\"\!]+)\"/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=\2"', $content, -1, $nbrep);
296  // <img src="viewimage.php/modulepart=medias&file=image.png" => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png"
297  $content = preg_replace('/(<img[^>]*src=")(\/?viewimage\.php)/', '\1!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content, -1, $nbrep);
298 
299  // action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
300  $content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1!~!~!~'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
301 
302  // Fix relative URL
303  $content = str_replace('src="!~!~!~/viewimage.php', 'src="!~!~!~'.DOL_URL_ROOT.'/viewimage.php', $content);
304  $content = str_replace('href="!~!~!~/document.php', 'href="!~!~!~'.DOL_URL_ROOT.'/document.php', $content);
305 
306  // Remove the protection tag !~!~!~, but only if this is the parent page and not an include
307  if (empty($includehtmlcontentopened)) {
308  $content = str_replace('!~!~!~', '', $content);
309  }
310  } else // REPLACEMENT OF LINKS When page called from virtual host web server
311  {
312  $symlinktomediaexists = 1;
313  if ($website->virtualhost) {
314  $content = preg_replace('/^(<link[^>]*rel="canonical" href=")\//m', '\1'.$website->virtualhost.'/', $content, -1, $nbrep);
315  }
316  //print 'rrrrrrrrr'.$website->virtualhost.$content;
317 
318 
319  // Make a change into HTML code to allow to include images from medias directory correct with direct link for virtual server
320  // <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
321  // become
322  // <img alt="" src="'.$urlwithroot.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
323  if (!$symlinktomediaexists) {
324  // <img src="image.png... => <img src="medias/image.png...
325  $content = preg_replace('/(<img[^>]*src=")\/?image\//', '\1/wrapper.php?modulepart=medias&file=medias/image/', $content, -1, $nbrep);
326  $content = preg_replace('/(url\(["\']?)\/?image\//', '\1/wrapper.php?modulepart=medias&file=medias/image/', $content, -1, $nbrep);
327 
328  $content = preg_replace('/(<script[^>]*src=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
329  $content = preg_replace('/(<a[^>]*href=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
330 
331  $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
332  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
333  $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1/wrapper.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
334 
335  $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
336  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
337  $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)hashp=([^\)]*)(["\']?\))/', '\1/wrapper.php\2hashp\3\4', $content, -1, $nbrep);
338 
339  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=mycompany([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=mycompany\3file=\4\5', $content, -1, $nbrep);
340 
341  // If some links to documents or viewimage remains, we replace with wrapper
342  $content = preg_replace('/(<img[^>]*src=")\/?viewimage\.php/', '\1/wrapper.php', $content, -1, $nbrep);
343  $content = preg_replace('/(<a[^>]*href=")\/?documents\.php/', '\1/wrapper.php', $content, -1, $nbrep);
344  } else {
345  // <img src="image.png... => <img src="medias/image.png...
346  $content = preg_replace('/(<img[^>]*src=")\/?image\//', '\1/medias/image/', $content, -1, $nbrep);
347  $content = preg_replace('/(url\(["\']?)\/?image\//', '\1/medias/image/', $content, -1, $nbrep);
348 
349  $content = preg_replace('/(<script[^>]*src=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
350  $content = preg_replace('/(<a[^>]*href=")[^\"]*document\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
351 
352  $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
353  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/medias/\4\5', $content, -1, $nbrep);
354  $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1/medias/\4\5', $content, -1, $nbrep);
355 
356  $content = preg_replace('/(<a[^>]*href=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
357  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)hashp=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
358  $content = preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)hashp=([^\)]*)(["\']?\))/', '\1/wrapper.php\2hashp=\3\4', $content, -1, $nbrep);
359 
360  $content = preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=mycompany([^\"]*)file=([^\"]*)("[^>]*>)/', '\1/wrapper.php\2modulepart=mycompany\3file=\4\5', $content, -1, $nbrep);
361 
362  // If some links to documents or viewimage remains, we replace with wrapper
363  $content = preg_replace('/(<img[^>]*src=")\/?viewimage\.php/', '\1/wrapper.php', $content, -1, $nbrep);
364  $content = preg_replace('/(<a[^>]*href=")\/?document\.php/', '\1/wrapper.php', $content, -1, $nbrep);
365  }
366  }
367 
368  if (!defined('USEDOLIBARREDITOR')) {
369  $content = str_replace(' contenteditable="true"', ' contenteditable="false"', $content);
370  }
371 
372  if (!empty($conf->global->WEBSITE_ADD_CSS_TO_BODY)) {
373  $content = str_replace('<body id="bodywebsite" class="bodywebsite', '<body id="bodywebsite" class="bodywebsite '.$conf->global->WEBSITE_ADD_CSS_TO_BODY, $content);
374  }
375 
376  dol_syslog("dolWebsiteOutput end");
377 
378  print $content;
379 }
380 
381 
389 /*
390 function dolWebsiteSaveContent($content)
391 {
392  global $db, $langs, $conf, $user;
393  global $dolibarr_main_url_root, $dolibarr_main_data_root;
394 
395  //dol_syslog("dolWebsiteSaveContent start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
396 
397  // Define $urlwithroot
398  $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
399  $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
400  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
401 
402  //$content = preg_replace('/(<img.*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
403 
404  return $content;
405 }
406 */
407 
408 
418 function redirectToContainer($containerref, $containeraliasalt = '', $containerid = 0, $permanent = 0)
419 {
420  global $db, $website;
421 
422  $newurl = '';
423  $result = 0;
424 
425  // We make redirect using the alternative alias, we must find the real $containerref
426  if ($containeraliasalt) {
427  include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
428  $tmpwebsitepage = new WebsitePage($db);
429  $result = $tmpwebsitepage->fetch(0, $website->id, '', $containeraliasalt);
430  if ($result > 0) {
431  $containerref = $tmpwebsitepage->pageurl;
432  } else {
433  print "Error, page contains a redirect to the alternative alias '".$containeraliasalt."' that does not exists in web site (".$website->id." / ".$website->ref.")";
434  exit;
435  }
436  }
437 
438  if (defined('USEDOLIBARREDITOR')) {
439  /*print '<div class="margintoponly marginleftonly">';
440  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.";
441  print '</div>';*/
442  $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.";
443  setEventMessages($text, null, 'warnings', 'WEBSITEREDIRECTDISABLED'.$containerref);
444  return;
445  }
446 
447  if (defined('USEDOLIBARRSERVER')) { // When page called from Dolibarr server
448  // Check new container exists
449  if (!$containeraliasalt) { // If containeraliasalt set, we already did the test
450  include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
451  $tmpwebsitepage = new WebsitePage($db);
452  $result = $tmpwebsitepage->fetch(0, $website->id, $containerref);
453  unset($tmpwebsitepage);
454  }
455  if ($result > 0) {
456  $currenturi = $_SERVER["REQUEST_URI"];
457  $regtmp = array();
458  if (preg_match('/&pageref=([^&]+)/', $currenturi, $regtmp)) {
459  if ($regtmp[0] == $containerref) {
460  print "Error, page with uri '.$currenturi.' try a redirect to the same alias page '".$containerref."' in web site '".$website->ref."'";
461  exit;
462  } else {
463  $newurl = preg_replace('/&pageref=([^&]+)/', '&pageref='.$containerref, $currenturi);
464  }
465  } else {
466  $newurl = $currenturi.'&pageref='.urlencode($containerref);
467  }
468  }
469  } else // When page called from virtual host server
470  {
471  $newurl = '/'.$containerref.'.php';
472  }
473 
474  if ($newurl) {
475  if ($permanent) {
476  header("Status: 301 Moved Permanently", false, 301);
477  }
478  header("Location: ".$newurl.(empty($_SERVER["QUERY_STRING"]) ? '' : '?'.$_SERVER["QUERY_STRING"]));
479  exit;
480  } else {
481  print "Error, page contains a redirect to the alias page '".$containerref."' that does not exists in web site (".$website->id." / ".$website->ref.")";
482  exit;
483  }
484 }
485 
486 
494 function includeContainer($containerref)
495 {
496  global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running included containers.
497  global $includehtmlcontentopened;
498  global $websitekey, $websitepagefile;
499 
500  $MAXLEVEL = 20;
501 
502  if (!preg_match('/\.php$/i', $containerref)) {
503  $containerref .= '.php';
504  }
505 
506  $fullpathfile = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$websitekey.'/'.$containerref;
507 
508  if (empty($includehtmlcontentopened)) {
509  $includehtmlcontentopened = 0;
510  }
511  $includehtmlcontentopened++;
512  if ($includehtmlcontentopened > $MAXLEVEL) {
513  print 'ERROR: RECURSIVE CONTENT LEVEL. Depth of recursive call is more than the limit of '.((int) $MAXLEVEL).".\n";
514  return;
515  }
516 
517  //dol_syslog("Include container ".$containerref.' includehtmlcontentopened='.$includehtmlcontentopened);
518 
519  // file_get_contents is not possible. We must execute code with include
520  //$content = file_get_contents($fullpathfile);
521  //print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $content);*/
522 
523  ob_start();
524  $res = include $fullpathfile; // Include because we want to execute code content
525  $tmpoutput = ob_get_contents();
526  ob_end_clean();
527 
528  print "\n".'<!-- include '.$websitekey.'/'.$containerref.(is_object($websitepage) ? ' parent id='.$websitepage->id : '').' level = '.$includehtmlcontentopened.' -->'."\n";
529  print preg_replace(array('/^.*<body[^>]*>/ims', '/<\/body>.*$/ims'), array('', ''), $tmpoutput);
530 
531  if (!$res) {
532  print 'ERROR: FAILED TO INCLUDE PAGE '.$containerref.".\n";
533  }
534 
535  $includehtmlcontentopened--;
536 }
537 
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 
552  $type = strtolower($type);
553 
554  if ($type == 'software') {
555  $ret = '<!-- Add structured data for entry in a software annuary -->'."\n";
556  $ret .= '<script type="application/ld+json">'."\n";
557  $ret .= '{
558  "@context": "https://schema.org",
559  "@type": "SoftwareApplication",
560  "name": "'.dol_escape_json($data['name']).'",
561  "operatingSystem": "'.dol_escape_json($data['os']).'",
562  "applicationCategory": "https://schema.org/'.dol_escape_json($data['applicationCategory']).'",';
563  if (!empty($data['ratingcount'])) {
564  $ret .= '
565  "aggregateRating": {
566  "@type": "AggregateRating",
567  "ratingValue": "'.dol_escape_json($data['ratingvalue']).'",
568  "ratingCount": "'.dol_escape_json($data['ratingcount']).'"
569  },';
570  }
571  $ret .= '
572  "offers": {
573  "@type": "Offer",
574  "price": "'.dol_escape_json($data['price']).'",
575  "priceCurrency": "'.dol_escape_json($data['currency'] ? $data['currency'] : $conf->currency).'"
576  }
577  }'."\n";
578  $ret .= '</script>'."\n";
579  } elseif ($type == 'organization') {
580  $companyname = $mysoc->name;
581  $url = $mysoc->url;
582 
583  $ret = '<!-- Add structured data for organization -->'."\n";
584  $ret .= '<script type="application/ld+json">'."\n";
585  $ret .= '{
586  "@context": "https://schema.org",
587  "@type": "Organization",
588  "name": "'.dol_escape_json($data['name'] ? $data['name'] : $companyname).'",
589  "url": "'.dol_escape_json($data['url'] ? $data['url'] : $url).'",
590  "logo": "'.($data['logo'] ? dol_escape_json($data['logo']) : '/wrapper.php?modulepart=mycompany&file=logos%2F'.urlencode($mysoc->logo)).'",
591  "contactPoint": {
592  "@type": "ContactPoint",
593  "contactType": "Contact",
594  "email": "'.dol_escape_json($data['email'] ? $data['email'] : $mysoc->email).'"
595  }'."\n";
596  if (is_array($mysoc->socialnetworks) && count($mysoc->socialnetworks) > 0) {
597  $ret .= ",\n";
598  $ret .= '"sameAs": [';
599  $i = 0;
600  foreach ($mysoc->socialnetworks as $key => $value) {
601  if ($key == 'linkedin') {
602  $ret .= '"https://www.'.$key.'.com/company/'.dol_escape_json($value).'"';
603  } elseif ($key == 'youtube') {
604  $ret .= '"https://www.'.$key.'.com/user/'.dol_escape_json($value).'"';
605  } else {
606  $ret .= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"';
607  }
608  $i++;
609  if ($i < count($mysoc->socialnetworks)) {
610  $ret .= ', ';
611  }
612  }
613  $ret .= ']'."\n";
614  }
615  $ret .= '}'."\n";
616  $ret .= '</script>'."\n";
617  } elseif ($type == 'blogpost') {
618  if (!empty($websitepage->author_alias)) {
619  //include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
620  //$tmpuser = new User($db);
621  //$restmpuser = $tmpuser->fetch($websitepage->fk_user_creat);
622 
623  $pageurl = $websitepage->pageurl;
624  $title = $websitepage->title;
625  $image = $websitepage->image;
626  $companyname = $mysoc->name;
627  $description = $websitepage->description;
628 
629  $pageurl = str_replace('__WEBSITE_KEY__', $website->ref, $pageurl);
630  $title = str_replace('__WEBSITE_KEY__', $website->ref, $title);
631  $image = '/medias'.(preg_match('/^\//', $image) ? '' : '/').str_replace('__WEBSITE_KEY__', $website->ref, $image);
632  $companyname = str_replace('__WEBSITE_KEY__', $website->ref, $companyname);
633  $description = str_replace('__WEBSITE_KEY__', $website->ref, $description);
634 
635  $ret = '<!-- Add structured data for blog post -->'."\n";
636  $ret .= '<script type="application/ld+json">'."\n";
637  $ret .= '{
638  "@context": "https://schema.org",
639  "@type": "NewsArticle",
640  "mainEntityOfPage": {
641  "@type": "WebPage",
642  "@id": "'.dol_escape_json($pageurl).'"
643  },
644  "headline": "'.dol_escape_json($title).'",
645  "image": [
646  "'.dol_escape_json($image).'"
647  ],
648  "dateCreated": "'.dol_print_date($websitepage->date_creation, 'dayhourrfc').'",
649  "datePublished": "'.dol_print_date($websitepage->date_creation, 'dayhourrfc').'",
650  "dateModified": "'.dol_print_date($websitepage->date_modification, 'dayhourrfc').'",
651  "author": {
652  "@type": "Person",
653  "name": "'.dol_escape_json($websitepage->author_alias).'"
654  },
655  "publisher": {
656  "@type": "Organization",
657  "name": "'.dol_escape_json($companyname).'",
658  "logo": {
659  "@type": "ImageObject",
660  "url": "/wrapper.php?modulepart=mycompany&file=logos%2F'.urlencode($mysoc->logo).'"
661  }
662  },'."\n";
663  if ($websitepage->keywords) {
664  $ret .= '"keywords": [';
665  $i = 0;
666  $arrayofkeywords = explode(',', $websitepage->keywords);
667  foreach ($arrayofkeywords as $keyword) {
668  $ret .= '"'.dol_escape_json($keyword).'"';
669  $i++;
670  if ($i < count($arrayofkeywords)) {
671  $ret .= ', ';
672  }
673  }
674  $ret .= '],'."\n";
675  }
676  $ret .= '"description": "'.dol_escape_json($description).'"';
677  $ret .= "\n".'}'."\n";
678  $ret .= '</script>'."\n";
679  } else {
680  $ret .= '<!-- no structured data inserted inline inside blogpost because no author_alias defined -->'."\n";
681  }
682  } elseif ($type == 'product') {
683  $ret = '<!-- Add structured data for product -->'."\n";
684  $ret .= '<script type="application/ld+json">'."\n";
685  $ret .= '{
686  "@context": "https://schema.org/",
687  "@type": "Product",
688  "name": "'.dol_escape_json($data['label']).'",
689  "image": [
690  "'.dol_escape_json($data['image']).'",
691  ],
692  "description": "'.dol_escape_json($data['description']).'",
693  "sku": "'.dol_escape_json($data['ref']).'",
694  "brand": {
695  "@type": "Thing",
696  "name": "'.dol_escape_json($data['brand']).'"
697  },
698  "author": {
699  "@type": "Person",
700  "name": "'.dol_escape_json($data['author']).'"
701  }
702  },
703  "offers": {
704  "@type": "Offer",
705  "url": "https://example.com/anvil",
706  "priceCurrency": "'.dol_escape_json($data['currency'] ? $data['currency'] : $conf->currency).'",
707  "price": "'.dol_escape_json($data['price']).'",
708  "itemCondition": "https://schema.org/UsedCondition",
709  "availability": "https://schema.org/InStock",
710  "seller": {
711  "@type": "Organization",
712  "name": "'.dol_escape_json($mysoc->name).'"
713  }
714  }
715  }'."\n";
716  $ret .= '</script>'."\n";
717  } elseif ($type == 'qa') {
718  $ret = '<!-- Add structured data for QA -->'."\n";
719  $ret .= '<script type="application/ld+json">'."\n";
720  $ret .= '{
721  "@context": "https://schema.org/",
722  "@type": "QAPage",
723  "mainEntity": {
724  "@type": "Question",
725  "name": "'.dol_escape_json($data['name']).'",
726  "text": "'.dol_escape_json($data['name']).'",
727  "answerCount": 1,
728  "author": {
729  "@type": "Person",
730  "name": "'.dol_escape_json($data['author']).'"
731  }
732  "acceptedAnswer": {
733  "@type": "Answer",
734  "text": "'.dol_escape_json(dol_string_nohtmltag(dolStripPhpCode($data['description']))).'",
735  "author": {
736  "@type": "Person",
737  "name": "'.dol_escape_json($data['author']).'"
738  }
739  }
740  }
741  }'."\n";
742  $ret .= '</script>'."\n";
743  }
744  return $ret;
745 }
746 
753 function getSocialNetworkHeaderCards($params = null)
754 {
755  global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
756 
757  $out = '';
758 
759  if ($website->virtualhost) {
760  $pageurl = $websitepage->pageurl;
761  $title = $websitepage->title;
762  $image = $websitepage->image;
763  $companyname = $mysoc->name;
764  $description = $websitepage->description;
765 
766  $pageurl = str_replace('__WEBSITE_KEY__', $website->ref, $pageurl);
767  $title = str_replace('__WEBSITE_KEY__', $website->ref, $title);
768  $image = '/medias'.(preg_match('/^\//', $image) ? '' : '/').str_replace('__WEBSITE_KEY__', $website->ref, $image);
769  $companyname = str_replace('__WEBSITE_KEY__', $website->ref, $companyname);
770  $description = str_replace('__WEBSITE_KEY__', $website->ref, $description);
771 
772  $shortlangcode = '';
773  if ($websitepage->lang) {
774  $shortlangcode = substr($websitepage->lang, 0, 2); // en_US or en-US -> en
775  }
776  if (empty($shortlangcode)) {
777  $shortlangcode = substr($website->lang, 0, 2); // en_US or en-US -> en
778  }
779 
780  $fullurl = $website->virtualhost.'/'.$websitepage->pageurl.'.php';
781  $canonicalurl = $website->virtualhost.(($websitepage->id == $website->fk_default_home) ? '/' : (($shortlangcode != substr($website->lang, 0, 2) ? '/'.$shortlangcode : '').'/'.$websitepage->pageurl.'.php'));
782  $hashtags = trim(join(' #', array_map('trim', explode(',', $websitepage->keywords))));
783 
784  // Open Graph
785  $out .= '<meta name="og:type" content="website">'."\n"; // TODO If blogpost, use type article
786  $out .= '<meta name="og:title" content="'.$websitepage->title.'">'."\n";
787  if ($websitepage->image) {
788  $out .= '<meta name="og:image" content="'.$website->virtualhost.$image.'">'."\n";
789  }
790  $out .= '<meta name="og:url" content="'.$canonicalurl.'">'."\n";
791 
792  // Twitter
793  $out .= '<meta name="twitter:card" content="summary">'."\n";
794  if (!empty($params) && !empty($params['twitter_account'])) {
795  $out .= '<meta name="twitter:site" content="@'.$params['twitter_account'].'">'."\n";
796  $out .= '<meta name="twitter:creator" content="@'.$params['twitter_account'].'">'."\n";
797  }
798  $out .= '<meta name="twitter:title" content="'.$websitepage->title.'">'."\n";
799  if ($websitepage->description) {
800  $out .= '<meta name="twitter:description" content="'.$websitepage->description.'">'."\n";
801  }
802  if ($websitepage->image) {
803  $out .= '<meta name="twitter:image" content="'.$website->virtualhost.$image.'">'."\n";
804  }
805  //$out .= '<meta name="twitter:domain" content="'.getDomainFromURL($website->virtualhost, 1).'">';
806  /*
807  $out .= '<meta name="twitter:app:name:iphone" content="">';
808  $out .= '<meta name="twitter:app:name:ipad" content="">';
809  $out .= '<meta name="twitter:app:name:googleplay" content="">';
810  $out .= '<meta name="twitter:app:url:iphone" content="">';
811  $out .= '<meta name="twitter:app:url:ipad" content="">';
812  $out .= '<meta name="twitter:app:url:googleplay" content="">';
813  $out .= '<meta name="twitter:app:id:iphone" content="">';
814  $out .= '<meta name="twitter:app:id:ipad" content="">';
815  $out .= '<meta name="twitter:app:id:googleplay" content="">';
816  */
817  }
818 
819  return $out;
820 }
821 
828 {
829  global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
830 
831  $out = '<!-- section for social network sharing of page -->'."\n";
832 
833  if ($website->virtualhost) {
834  $fullurl = $website->virtualhost.'/'.$websitepage->pageurl.'.php';
835  $hashtags = trim(join(' #', array_map('trim', explode(',', $websitepage->keywords))));
836 
837  $out .= '<div class="dol-social-share">'."\n";
838 
839  // Twitter
840  $out .= '<div class="dol-social-share-tw">'."\n";
841  $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>';
842  $out .= '<script>!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>';
843  $out .= '</div>'."\n";
844 
845  // Reddit
846  $out .= '<div class="dol-social-share-reddit">'."\n";
847  $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">';
848  $out .= '<span class="dol-social-share-reddit-span">Reddit</span>';
849  $out .= '</a>';
850  $out .= '</div>'."\n";
851 
852  // Facebook
853  $out .= '<div class="dol-social-share-fbl">'."\n";
854  $out .= '<div id="fb-root"></div>'."\n";
855  $out .= '<script>(function(d, s, id) {
856  var js, fjs = d.getElementsByTagName(s)[0];
857  if (d.getElementById(id)) return;
858  js = d.createElement(s); js.id = id;
859  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0&amp;appId=dolibarr.org";
860  fjs.parentNode.insertBefore(js, fjs);
861  }(document, \'script\', \'facebook-jssdk\'));</script>
862  <fb:like
863  href="'.$fullurl.'"
864  layout="button_count"
865  show_faces="false"
866  width="90"
867  colorscheme="light"
868  share="1"
869  action="like" ></fb:like>'."\n";
870  $out .= '</div>'."\n";
871 
872  $out .= "\n</div>\n";
873  } else {
874  $out .= '<!-- virtual host not defined in CMS. No way to add sharing buttons -->'."\n";
875  }
876  $out .= '<!-- section end for social network sharing of page -->'."\n";
877 
878  return $out;
879 }
880 
896 function getPagesFromSearchCriterias($type, $algo, $searchstring, $max = 25, $sortfield = 'date_creation', $sortorder = 'DESC', $langcode = '', $otherfilters = 'null', $status = 1)
897 {
898  global $conf, $db, $hookmanager, $langs, $mysoc, $user, $website, $websitepage, $weblangs; // Very important. Required to have var available when running inluded containers.
899 
900  $error = 0;
901  $arrayresult = array('code'=>'', 'list'=>array());
902 
903  if (!is_object($weblangs)) {
904  $weblangs = $langs;
905  }
906 
907  if (empty($searchstring) && empty($type) && empty($langcode) && empty($otherfilters)) {
908  $error++;
909  $arrayresult['code'] = 'KO';
910  $arrayresult['message'] = $weblangs->trans("EmptySearchString");
911  } elseif ($searchstring && dol_strlen($searchstring) < 2) {
912  $weblangs->load("errors");
913  $error++;
914  $arrayresult['code'] = 'KO';
915  $arrayresult['message'] = $weblangs->trans("ErrorSearchCriteriaTooSmall");
916  } else {
917  $tmparrayoftype = explode(',', $type);
918  /*foreach ($tmparrayoftype as $tmptype) {
919  if (!in_array($tmptype, array('', 'page', 'blogpost'))) {
920  $error++;
921  $arrayresult['code'] = 'KO';
922  $arrayresult['message'] = 'Bad value for parameter type';
923  break;
924  }
925  }*/
926  }
927 
928  $searchdone = 0;
929  $found = 0;
930 
931  if (!$error && (empty($max) || ($found < $max)) && (preg_match('/meta/', $algo) || preg_match('/content/', $algo))) {
932  include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
933 
934  $sql = 'SELECT wp.rowid FROM '.MAIN_DB_PREFIX.'website_page as wp';
935  if (is_array($otherfilters) && !empty($otherfilters['category'])) {
936  $sql .= ', '.MAIN_DB_PREFIX.'categorie_website_page as cwp';
937  }
938  $sql .= " WHERE wp.fk_website = ".((int) $website->id);
939  if ($status >= 0) {
940  $sql .= " AND wp.status = ".((int) $status);
941  }
942  if ($langcode) {
943  $sql .= " AND wp.lang = '".$db->escape($langcode)."'";
944  }
945  if ($type) {
946  $tmparrayoftype = explode(',', $type);
947  $typestring = '';
948  foreach ($tmparrayoftype as $tmptype) {
949  $typestring .= ($typestring ? ", " : "")."'".$db->escape(trim($tmptype))."'";
950  }
951  $sql .= " AND wp.type_container IN (".$db->sanitize($typestring, 1).")";
952  }
953  $sql .= " AND (";
954  $searchalgo = '';
955  if (preg_match('/meta/', $algo)) {
956  $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.title LIKE '%".$db->escape($db->escapeforlike($searchstring))."%' OR wp.description LIKE '%".$db->escape($db->escapeforlike($searchstring))."%'";
957  $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
958  }
959  if (preg_match('/content/', $algo)) {
960  $searchalgo .= ($searchalgo ? ' OR ' : '')."wp.content LIKE '%".$db->escape($db->escapeforlike($searchstring))."%'";
961  }
962  $sql .= $searchalgo;
963  if (is_array($otherfilters) && !empty($otherfilters['category'])) {
964  $sql .= ' AND cwp.fk_website_page = wp.rowid AND cwp.fk_categorie = '.((int) $otherfilters['category']);
965  }
966  $sql .= ")";
967  $sql .= $db->order($sortfield, $sortorder);
968  $sql .= $db->plimit($max);
969  //print $sql;
970 
971  $resql = $db->query($sql);
972 
973  if ($resql) {
974  $i = 0;
975  while (($obj = $db->fetch_object($resql)) && ($i < $max || $max == 0)) {
976  if ($obj->rowid > 0) {
977  $tmpwebsitepage = new WebsitePage($db);
978  $tmpwebsitepage->fetch($obj->rowid);
979  if ($tmpwebsitepage->id > 0) {
980  $arrayresult['list'][$obj->rowid] = $tmpwebsitepage;
981  }
982  $found++;
983  }
984  $i++;
985  }
986  } else {
987  $error++;
988  $arrayresult['code'] = $db->lasterrno();
989  $arrayresult['message'] = $db->lasterror();
990  }
991 
992  $searchdone = 1;
993  }
994 
995  if (!$error && (empty($max) || ($found < $max)) && (preg_match('/sitefiles/', $algo))) {
996  global $dolibarr_main_data_root;
997 
998  $pathofwebsite = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$website->ref;
999  $filehtmlheader = $pathofwebsite.'/htmlheader.html';
1000  $filecss = $pathofwebsite.'/styles.css.php';
1001  $filejs = $pathofwebsite.'/javascript.js.php';
1002  $filerobot = $pathofwebsite.'/robots.txt';
1003  $filehtaccess = $pathofwebsite.'/.htaccess';
1004  $filemanifestjson = $pathofwebsite.'/manifest.json.php';
1005  $filereadme = $pathofwebsite.'/README.md';
1006 
1007  $filecontent = file_get_contents($filehtmlheader);
1008  if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
1009  $arrayresult['list'][] = array('type'=>'website_htmlheadercontent');
1010  }
1011 
1012  $filecontent = file_get_contents($filecss);
1013  if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
1014  $arrayresult['list'][] = array('type'=>'website_csscontent');
1015  }
1016 
1017  $filecontent = file_get_contents($filejs);
1018  if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
1019  $arrayresult['list'][] = array('type'=>'website_jscontent');
1020  }
1021 
1022  $filerobot = file_get_contents($filerobot);
1023  if ((empty($max) || ($found < $max)) && preg_match('/'.preg_quote($searchstring, '/').'/', $filecontent)) {
1024  $arrayresult['list'][] = array('type'=>'website_robotcontent');
1025  }
1026 
1027  $searchdone = 1;
1028  }
1029 
1030  if (!$error) {
1031  if ($searchdone) {
1032  $arrayresult['code'] = 'OK';
1033  if (empty($arrayresult['list'])) {
1034  $arrayresult['code'] = 'KO';
1035  $arrayresult['message'] = $weblangs->trans("NoRecordFound");
1036  }
1037  } else {
1038  $error++;
1039  $arrayresult['code'] = 'KO';
1040  $arrayresult['message'] = 'No supported algorithm found';
1041  }
1042  }
1043 
1044  return $arrayresult;
1045 }
1046 
1061 function getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks = 0, $grabimages = 1, $grabimagesinto = 'subpage')
1062 {
1063  global $conf;
1064 
1065  $error = 0;
1066 
1067  dol_syslog("Call getAllImages with grabimagesinto=".$grabimagesinto);
1068 
1069  $alreadygrabbed = array();
1070 
1071  if (preg_match('/\/$/', $urltograb)) {
1072  $urltograb .= '.';
1073  }
1074  $urltograb = dirname($urltograb); // So urltograb is now http://www.nltechno.com or http://www.nltechno.com/dir1
1075 
1076  // Search X in "img...src=X"
1077  $regs = array();
1078  preg_match_all('/<img([^\.\/]+)src="([^>"]+)"([^>]*)>/i', $tmp, $regs);
1079 
1080  foreach ($regs[0] as $key => $val) {
1081  if (preg_match('/^data:image/i', $regs[2][$key])) {
1082  continue; // We do nothing for such images
1083  }
1084 
1085  if (preg_match('/^\//', $regs[2][$key])) {
1086  $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
1087  $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
1088  } else {
1089  $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file
1090  }
1091 
1092  $linkwithoutdomain = $regs[2][$key];
1093  $dirforimages = '/'.$objectpage->pageurl;
1094  if ($grabimagesinto == 'root') {
1095  $dirforimages = '';
1096  }
1097 
1098  // Define $filetosave and $filename
1099  $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $regs[2][$key]) ? '' : '/').$regs[2][$key];
1100  if (preg_match('/^http/', $regs[2][$key])) {
1101  $urltograbbis = $regs[2][$key];
1102  $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
1103  $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
1104  }
1105  $filename = 'image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
1106 
1107  // Clean the aa/bb/../cc into aa/cc
1108  $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
1109  $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
1110 
1111  //var_dump($filetosave);
1112  //var_dump($filename);
1113  //exit;
1114 
1115  if (empty($alreadygrabbed[$urltograbbis])) {
1116  if ($grabimages) {
1117  $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
1118  if ($tmpgeturl['curl_error_no']) {
1119  $error++;
1120  setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
1121  $action = 'create';
1122  } elseif ($tmpgeturl['http_code'] != '200') {
1123  $error++;
1124  setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
1125  $action = 'create';
1126  } else {
1127  $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed.
1128 
1129  dol_mkdir(dirname($filetosave));
1130 
1131  $fp = fopen($filetosave, "w");
1132  fputs($fp, $tmpgeturl['content']);
1133  fclose($fp);
1134  if (!empty($conf->global->MAIN_UMASK)) {
1135  @chmod($filetosave, octdec($conf->global->MAIN_UMASK));
1136  }
1137  }
1138  }
1139  }
1140 
1141  if ($modifylinks) {
1142  $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);
1143  }
1144  }
1145 
1146  // Search X in "background...url(X)"
1147  preg_match_all('/background([^\.\/\(;]+)url\([\"\']?([^\)\"\']*)[\"\']?\)/i', $tmp, $regs);
1148 
1149  foreach ($regs[0] as $key => $val) {
1150  if (preg_match('/^data:image/i', $regs[2][$key])) {
1151  continue; // We do nothing for such images
1152  }
1153 
1154  if (preg_match('/^\//', $regs[2][$key])) {
1155  $urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
1156  $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot
1157  } else {
1158  $urltograbbis = $urltograb.'/'.$regs[2][$key]; // We use dir of grabbed file
1159  }
1160 
1161  $linkwithoutdomain = $regs[2][$key];
1162 
1163  $dirforimages = '/'.$objectpage->pageurl;
1164  if ($grabimagesinto == 'root') {
1165  $dirforimages = '';
1166  }
1167 
1168  $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $regs[2][$key]) ? '' : '/').$regs[2][$key];
1169 
1170  if (preg_match('/^http/', $regs[2][$key])) {
1171  $urltograbbis = $regs[2][$key];
1172  $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
1173  $filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
1174  }
1175 
1176  $filename = 'image/'.$object->ref.$dirforimages.(preg_match('/^\//', $linkwithoutdomain) ? '' : '/').$linkwithoutdomain;
1177 
1178  // Clean the aa/bb/../cc into aa/cc
1179  $filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
1180  $filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
1181 
1182  //var_dump($filetosave);
1183  //var_dump($filename);
1184  //exit;
1185 
1186  if (empty($alreadygrabbed[$urltograbbis])) {
1187  if ($grabimages) {
1188  $tmpgeturl = getURLContent($urltograbbis, 'GET', '', 1, array(), array('http', 'https'), 0);
1189  if ($tmpgeturl['curl_error_no']) {
1190  $error++;
1191  setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
1192  $action = 'create';
1193  } elseif ($tmpgeturl['http_code'] != '200') {
1194  $error++;
1195  setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
1196  $action = 'create';
1197  } else {
1198  $alreadygrabbed[$urltograbbis] = 1; // Track that file was alreay grabbed.
1199 
1200  dol_mkdir(dirname($filetosave));
1201 
1202  $fp = fopen($filetosave, "w");
1203  fputs($fp, $tmpgeturl['content']);
1204  fclose($fp);
1205  if (!empty($conf->global->MAIN_UMASK)) {
1206  @chmod($filetosave, octdec($conf->global->MAIN_UMASK));
1207  }
1208  }
1209  }
1210  }
1211 
1212  if ($modifylinks) {
1213  $tmp = preg_replace('/'.preg_quote($regs[0][$key], '/').'/i', 'background'.$regs[1][$key].'url("'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'")', $tmp);
1214  }
1215  }
1216 }
getSocialNetworkSharingLinks
getSocialNetworkSharingLinks()
Return HTML content to add structured data for an article, news or Blog Post.
Definition: website.lib.php:827
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
dolStripPhpCode
dolStripPhpCode($str, $replacewith='')
Remove PHP code part from a string.
Definition: website.lib.php:32
WebsitePage
Class Websitepage.
Definition: websitepage.class.php:36
includeContainer
includeContainer($containerref)
Clean an HTML page to report only content, so we can include it into another page.
Definition: website.lib.php:494
dolKeepOnlyPhpCode
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
Definition: website.lib.php:76
getStructuredData
getStructuredData($type, $data=array())
Return HTML content to add structured data for an article, news or Blog Post.
Definition: website.lib.php:548
getRootURLFromURL
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
Definition: geturl.lib.php:349
getURLContent
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
Definition: geturl.lib.php:41
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
getSocialNetworkHeaderCards
getSocialNetworkHeaderCards($params=null)
Return HTML content to add as header card for an article, news or Blog Post or home page.
Definition: website.lib.php:753
dolWebsiteReplacementOfLinks
dolWebsiteReplacementOfLinks($website, $content, $removephppart=0, $contenttype='html', $containerid='')
Convert a page content to have correct links (based on DOL_URL_ROOT) into an html content.
Definition: website.lib.php:118
redirectToContainer
redirectToContainer($containerref, $containeraliasalt='', $containerid=0, $permanent=0)
Format img tags to introduce viewimage on img src.
Definition: website.lib.php:418
getAllImages
getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks=0, $grabimages=1, $grabimagesinto='subpage')
Download all images found into page content $tmp.
Definition: website.lib.php:1061
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6694
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
getPagesFromSearchCriterias
getPagesFromSearchCriterias($type, $algo, $searchstring, $max=25, $sortfield='date_creation', $sortorder='DESC', $langcode='', $otherfilters='null', $status=1)
Return list of containers object that match a criteria.
Definition: website.lib.php:896
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
dolWebsiteOutput
dolWebsiteOutput($content, $contenttype='html', $containerid='')
Render a string of an HTML content and output it.
Definition: website.lib.php:230
dol_escape_json
dol_escape_json($stringtoescape)
Returns text escaped for inclusion into javascript code.
Definition: functions.lib.php:1452
if
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Definition: journals_list.php:25