Completed
Branch develop (bb7c03)
by
unknown
34:20
created

website.lib.php ➔ dolWebsiteReplacementOfLinks()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 4
nop 3
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2017 Laurent Destailleur	<[email protected]>
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 <http://www.gnu.org/licenses/>.
16
 */
17
18
/**
19
 *      \file       htdocs/core/lib/website.lib.php
20
 *      \ingroup    website
21
 *      \brief      Library for website module
22
 */
23
24
25
26
/**
27
 * Convert a page content to have correct links (based on DOL_URL_ROOT) into an html content.
28
 * Used to ouput the page on the Preview.
29
 *
30
 * @param	Website		$website			Web site object
31
 * @param	string		$content			Content to replace
32
 * @param	int			$removephppart		0=Replace PHP sections with a PHP badge. 1=Remove completely PHP sections.
33
 * @return	boolean							True if OK
34
 */
35
function dolWebsiteReplacementOfLinks($website, $content, $removephppart=0)
36
{
37
	// Replace php code. Note $content may come from database and does not contains body tags.
38
	$replacewith='...php...';
39
	if ($removephppart) $replacewith='';
40
	$content = preg_replace('/value="<\?php((?!\?>).)*\?>\n*/ims', 'value="'.$replacewith.'"', $content);
41
42
	$replacewith='<span style="background: #ddd; border: 1px solid #ccc; border-radius: 4px;">...php...</span>';
43
	if ($removephppart) $replacewith='';
44
	$content = preg_replace('/<\?php((?!\?>).)*\?>\n*/ims', $replacewith, $content);
45
46
	// Replace relative link / with dolibarr URL
47
	$content = preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep);
48
	// Replace relative link /xxx.php with dolibarr URL
49
	$content = preg_replace('/(href=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
50
51
	$content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
52
53
	// <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
54
	$content = preg_replace('/(<img[^>]*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
55
56
	// action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
57
	$content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
58
59
	return $content;
60
}
61
62
63
/**
64
 * Render a string of an HTML content and output it.
65
 * Used to ouput the page when viewed from server (Dolibarr or Apache).
66
 *
67
 * @param   string  $content    Content string
68
 * @return  void
69
 * @see	dolWebsiteSaveContent
70
 */
71
function dolWebsiteOutput($content)
72
{
73
	global $db, $langs, $conf, $user;
74
	global $dolibarr_main_url_root, $dolibarr_main_data_root;
75
76
	dol_syslog("dolWebsiteOutput start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
77
78
	// Define $urlwithroot
79
	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
80
	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
81
	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
82
83
	// Note: This seems never called when page is output inside the website editor (search 'REPLACEMENT OF LINKS When page called by website editor')
84
85
	if (defined('USEDOLIBARRSERVER'))	// REPLACEMENT OF LINKS When page called from Dolibarr server
86
	{
87
		global $website;
88
89
		// Replace relative link / with dolibarr URL:  ...href="/"...
90
		$content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep);
91
		// Replace relative link /xxx.php with dolibarr URL:  ...href="....php"
92
		$content=preg_replace('/(href=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
93
94
		// Fix relative link /document.php with correct URL after the DOL_URL_ROOT:  ...href="/document.php?modulepart="
95
		$content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep);
96
		// Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT:  ...href="/viewimage.php?modulepart="
97
		$content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep);
98
99
		// Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
100
		$content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
101
102
		// action="newpage.php" => action="dolibarr/website/index.php?website=...&pageref=newpage
103
		$content = preg_replace('/(action=")\/?([^:\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/website/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
104
	}
105
	else								// REPLACEMENT OF LINKS When page called from virtual host
106
	{
107
		$symlinktomediaexists=1;
108
109
		// Make a change into HTML code to allow to include images from medias directory correct with direct link for virtual server
110
		// <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
111
		// become
112
		// <img alt="" src="'.$urlwithroot.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
113
		$nbrep=0;
114
		if (! $symlinktomediaexists)
115
		{
116
			$content=preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
117
			$content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/',  '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
118
		}
119
		else
120
		{
121
			$content=preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1medias/\4\5', $content, -1, $nbrep);
122
			$content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1medias/\4\5', $content, -1, $nbrep);
123
		}
124
	}
125
126
	dol_syslog("dolWebsiteOutput end");
127
128
	print $content;
129
}
130
131
132
/**
133
 * Format img tags to introduce viewimage on img src.
134
 *
135
 * @param   string  $content    Content string
136
 * @return  void
137
 * @see	dolWebsiteOutput
138
 */
139
/*
140
function dolWebsiteSaveContent($content)
141
{
142
	global $db, $langs, $conf, $user;
143
	global $dolibarr_main_url_root, $dolibarr_main_data_root;
144
145
	//dol_syslog("dolWebsiteSaveContent start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
146
147
	// Define $urlwithroot
148
	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
149
	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
150
	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
151
152
	//$content = preg_replace('/(<img.*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
153
154
	return $content;
155
}
156
*/
157
158
159
/**
160
 * Clean an HTML page to report only content, so we can include it into another page.
161
 * It outputs content of file sanitized from html and body part.
162
 *
163
 * @param 	string	$contentfile		Path to file to include (must include website root. Example: 'mywebsite/mypage.php')
164
 * @return  void
165
 */
166
function dolIncludeHtmlContent($contentfile)
167
{
168
	global $conf, $db, $langs, $mysoc, $user, $website;
169
	global $includehtmlcontentopened;
170
171
	$MAXLEVEL=20;
172
173
	$fullpathfile=DOL_DATA_ROOT.'/website/'.$contentfile;
174
175
	if (empty($includehtmlcontentopened)) $includehtmlcontentopened=0;
176
	$includehtmlcontentopened++;
177
	if ($includehtmlcontentopened > $MAXLEVEL)
178
	{
179
		print 'ERROR: RECURSIVE CONTENT LEVEL. Depth of recursive call is more than the limit of '.$MAXLEVEL.".\n";
180
		return;
181
	}
182
	// file_get_contents is not possible. We must execute code with include
183
	//$content = file_get_contents($fullpathfile);
184
	//print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $content);*/
185
186
	ob_start();
187
	$res = include $fullpathfile;		// Include because we want to execute code content
188
	$tmpoutput = ob_get_contents();
189
	ob_end_clean();
190
191
	print "\n".'<!-- include '.$fullpathfile.' level = '.$includehtmlcontentopened.' -->'."\n";
192
	print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $tmpoutput);
193
194
	if (! $res)
195
	{
196
		print 'ERROR: FAILED TO INCLUDE PAGE '.$contentfile.".\n";
197
	}
198
199
	$includehtmlcontentopened--;
200
}
201
202
203
204
/**
205
 * Download all images found into page content $tmp.
206
 * If $modifylinks is set, links to images will be replace with a link to viewimage wrapper.
207
 *
208
 * @param 	Website	 	$object			Object website
209
 * @param 	WebsitePage	$objectpage		Object website page
210
 * @param 	string		$urltograb		URL to grab (exemple: http://www.nltechno.com/ or http://www.nltechno.com/dir1/ or http://www.nltechno.com/dir1/mapage1)
211
 * @param 	string		$tmp			Content to parse
212
 * @param 	string		$action			Var $action
213
 * @param	string		$modifylinks	0=Do not modify content, 1=Replace links with a link to viewimage
214
 * @return	void
215
 */
216
function getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks=0)
217
{
218
	global $conf;
219
220
	$error=0;
221
222
	$alreadygrabbed=array();
223
224
	if (preg_match('/\/$/', $urltograb)) $urltograb.='.';
225
	$urltograb = dirname($urltograb);							// So urltograb is now http://www.nltechno.com or http://www.nltechno.com/dir1
226
227
	preg_match_all('/<img([^\.\/]+)src="([^>"]+)"([^>]*)>/i', $tmp, $regs);
228
229
	foreach ($regs[0] as $key => $val)
230
	{
231
		if (preg_match('/^data:image/i', $regs[2][$key])) continue;		// We do nothing for such images
232
233
		if (preg_match('/^\//', $regs[2][$key]))
234
		{
235
			$urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
236
			$urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key];	// We use dirroot
237
		}
238
		else
239
		{
240
			$urltograbbis = $urltograb.'/'.$regs[2][$key];	// We use dir of grabbed file
241
		}
242
243
		$linkwithoutdomain = $regs[2][$key];
244
		$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
245
		if (preg_match('/^http/', $regs[2][$key]))
246
		{
247
			$urltograbbis = $regs[2][$key];
248
			$linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
249
			$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
250
		}
251
252
		$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
253
254
		// Clean the aa/bb/../cc into aa/cc
255
		$filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
256
		$filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
257
258
		//var_dump($filetosave);
259
		//var_dump($filename);
260
		//exit;
261
262
		if (empty($alreadygrabbed[$urltograbbis]))
263
		{
264
			$tmpgeturl = getURLContent($urltograbbis);
265
			if ($tmpgeturl['curl_error_no'])
266
			{
267
				$error++;
268
				setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
269
				$action='create';
270
			}
271
			elseif ($tmpgeturl['http_code'] != '200')
272
			{
273
				$error++;
274
				setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
275
				$action='create';
276
			}
277
			else
278
			{
279
				$alreadygrabbed[$urltograbbis]=1;	// Track that file was alreay grabbed.
280
281
				dol_mkdir(dirname($filetosave));
282
283
				$fp = fopen($filetosave, "w");
284
				fputs($fp, $tmpgeturl['content']);
285
				fclose($fp);
286
				if (! empty($conf->global->MAIN_UMASK))
287
					@chmod($filetosave, octdec($conf->global->MAIN_UMASK));
288
			}
289
		}
290
291
		if ($modifylinks)
292
		{
293
			$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);
294
		}
295
	}
296
297
	// Search X in "background...url(X)"
298
	preg_match_all('/background([^\.\/\(;]+)url\([\"\']?([^\)\"\']*)[\"\']?\)/i', $tmp, $regs);
299
300
	foreach ($regs[0] as $key => $val)
301
	{
302
		if (preg_match('/^data:image/i', $regs[2][$key])) continue;		// We do nothing for such images
303
304
		if (preg_match('/^\//', $regs[2][$key]))
305
		{
306
			$urltograbdirrootwithoutslash = getRootURLFromURL($urltograb);
307
			$urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key];	// We use dirroot
308
		}
309
		else
310
		{
311
			$urltograbbis = $urltograb.'/'.$regs[2][$key];	// We use dir of grabbed file
312
		}
313
314
		$linkwithoutdomain = $regs[2][$key];
315
		$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
316
317
		if (preg_match('/^http/', $regs[2][$key]))
318
		{
319
			$urltograbbis = $regs[2][$key];
320
			$linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
321
			$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
322
		}
323
324
		$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
325
326
		// Clean the aa/bb/../cc into aa/cc
327
		$filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
328
		$filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
329
330
		//var_dump($filetosave);
331
		//var_dump($filename);
332
		//exit;
333
334
		if (empty($alreadygrabbed[$urltograbbis]))
335
		{
336
			$tmpgeturl = getURLContent($urltograbbis);
337
			if ($tmpgeturl['curl_error_no'])
338
			{
339
				$error++;
340
				setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors');
341
				$action='create';
342
			}
343
			elseif ($tmpgeturl['http_code'] != '200')
344
			{
345
				$error++;
346
				setEventMessages('Error getting '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors');
347
				$action='create';
348
			}
349
			else
350
			{
351
				$alreadygrabbed[$urltograbbis]=1;	// Track that file was alreay grabbed.
352
353
				dol_mkdir(dirname($filetosave));
354
355
				$fp = fopen($filetosave, "w");
356
				fputs($fp, $tmpgeturl['content']);
357
				fclose($fp);
358
				if (! empty($conf->global->MAIN_UMASK))
359
					@chmod($filetosave, octdec($conf->global->MAIN_UMASK));
360
			}
361
		}
362
363
		if ($modifylinks)
364
		{
365
			$tmp = preg_replace('/'.preg_quote($regs[0][$key],'/').'/i', 'background'.$regs[1][$key].'url("'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'")', $tmp);
366
		}
367
	}
368
369
}
370
371