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