Completed
Branch develop (2c126c)
by Laurent
24:08
created

website.lib.php ➔ getAllImages()   F

Complexity

Conditions 24
Paths > 20000

Size

Total Lines 123
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
eloc 63
nc 75272
nop 6
dl 0
loc 123
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * Render a string of an HTML content and output it.
27
 *
28
 * @param   string  $content    Content string
29
 * @return  void
30
 * @see	dolWebsiteSaveContent
31
 */
32
function dolWebsiteOutput($content)
33
{
34
    global $db, $langs, $conf, $user;
35
    global $dolibarr_main_url_root, $dolibarr_main_data_root;
36
37
    dol_syslog("dolWebsiteOutput start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
38
39
    // Define $urlwithroot
40
    $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
41
    $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
42
    //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
43
44
    // Note: This seems never called when page is output inside the website editor (search 'REPLACEMENT OF LINKS When page called by website editor')
45
46
    if (! defined('USEDOLIBARRSERVER'))	// REPLACEMENT OF LINKS When page called from virtual host
47
    {
48
        $symlinktomediaexists=1;
49
50
		// Make a change into HTML code to allow to include images from medias directory correct with direct link for virtual server
51
		// <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
52
		// become
53
		// <img alt="" src="'.$urlwithroot.'/medias/image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
54
        $nbrep=0;
55
        if (! $symlinktomediaexists)
56
        {
57
            $content=preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
58
            $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/',  '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $content, -1, $nbrep);
59
        }
60
        else
61
        {
62
        	$content=preg_replace('/(<img[^>]*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/?>)/', '\1medias/\4\5', $content, -1, $nbrep);
63
            $content=preg_replace('/(url\(["\']?)[^\)]*viewimage\.php([^\)]*)modulepart=medias([^\)]*)file=([^\)]*)(["\']?\))/', '\1medias/\4\5', $content, -1, $nbrep);
64
        }
65
    }
66
    else								// REPLACEMENT OF LINKS When page called from dolibarr server
67
    {
68
    	global $website;
69
70
    	// Replace relative link / with dolibarr URL:  ...href="/"...
71
    	$content=preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep);
72
    	// Replace relative link /xxx.php with dolibarr URL:  ...href="....php"
73
    	$content=preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
74
75
    	// Fix relative link /document.php with correct URL after the DOL_URL_ROOT:  ...href="/document.php?modulepart="
76
    	$content=preg_replace('/(href=")(\/?document\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep);
77
    	// Fix relative link /viewimage.php with correct URL after the DOL_URL_ROOT:  ...href="/viewimage.php?modulepart="
78
    	$content=preg_replace('/(href=")(\/?viewimage\.php\?[^\"]*modulepart=[^\"]*)(\")/', '\1'.DOL_URL_ROOT.'\2\3"', $content, -1, $nbrep);
79
80
    	// Fix relative link into medias with correct URL after the DOL_URL_ROOT: ../url("medias/
81
    	$content=preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
82
    }
83
84
    dol_syslog("dolWebsiteOutput end");
85
86
    print $content;
87
}
88
89
90
/**
91
 * Convert a page content to have correct links into a new html content.
92
 * Used to ouput the page on the Preview.
93
 *
94
 * @param	Website		$website			Web site object
95
 * @param	string		$content			Content to replace
96
 * @return	boolean							True if OK
97
 */
98
function dolWebsiteReplacementOfLinks($website, $content)
99
{
100
	// Replace php code. Note $content may come from database and does not contains body tags.
101
	$content = preg_replace('/<\?php[^\?]+\?>\n*/ims', '<span style="background: #ddd; border: 1px solid #ccc; border-radius: 4px;">...php...</span>', $content);
102
103
	// Replace relative link / with dolibarr URL
104
	$content = preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$website->ref.'&pageid='.$website->fk_default_home.'"', $content, -1, $nbrep);
105
	// Replace relative link /xxx.php with dolibarr URL
106
	$content = preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$website->ref.'&pageref=\2"', $content, -1, $nbrep);
107
108
	$content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
109
110
	// <img src="image.png... => <img src="dolibarr/viewimage.php/modulepart=medias&file=image.png...
111
	$content = preg_replace('/(<img[^>]*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
112
113
	return $content;
114
}
115
116
117
/**
118
 * Format img tags to introduce viewimage on img src.
119
 *
120
 * @param   string  $content    Content string
121
 * @return  void
122
 * @see	dolWebsiteOutput
123
 */
124
/*
125
function dolWebsiteSaveContent($content)
126
{
127
	global $db, $langs, $conf, $user;
128
	global $dolibarr_main_url_root, $dolibarr_main_data_root;
129
130
	//dol_syslog("dolWebsiteSaveContent start (mode=".(defined('USEDOLIBARRSERVER')?'USEDOLIBARRSERVER':'').')');
131
132
	// Define $urlwithroot
133
	$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
134
	$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
135
	//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
136
137
	//$content = preg_replace('/(<img.*src=")(?!(http|'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage))/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
138
139
	return $content;
140
}
141
*/
142
143
144
/**
145
 * Clean an HTML page to report only content, so we can include it into another page.
146
 * It outputs content of file sanitized from html and body part.
147
 *
148
 * @param 	string	$contentfile		Path to file to include (must include website root. Example: 'mywebsite/mypage.php')
149
 * @return  void
150
 */
151
function dolIncludeHtmlContent($contentfile)
152
{
153
	global $conf, $db, $langs, $mysoc, $user, $website;
154
	global $includehtmlcontentopened;
155
156
	$MAXLEVEL=20;
157
158
	$fullpathfile=DOL_DATA_ROOT.'/websites/'.$contentfile;
159
160
	if (empty($includehtmlcontentopened)) $includehtmlcontentopened=0;
161
	$includehtmlcontentopened++;
162
	if ($includehtmlcontentopened > $MAXLEVEL)
163
	{
164
		print 'ERROR: RECURSIVE CONTENT LEVEL. Depth of recursive call is more than the limit of '.$MAXLEVEL.".\n";
165
		return;
166
	}
167
	// file_get_contents is not possible. We must execute code with include
168
	//$content = file_get_contents($fullpathfile);
169
	//print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $content);*/
170
171
	ob_start();
172
	$res = include $fullpathfile;		// Include because we want to execute code content
173
	$tmpoutput = ob_get_contents();
174
	ob_end_clean();
175
176
	print "\n".'<!-- include '.$fullpathfile.' level = '.$includehtmlcontentopened.' -->'."\n";
177
	print preg_replace(array('/^.*<body[^>]*>/ims','/<\/body>.*$/ims'), array('', ''), $tmpoutput);
178
179
	if (! $res)
180
	{
181
		print 'ERROR: FAILED TO INCLUDE PAGE '.$contentfile.".\n";
182
	}
183
184
	$includehtmlcontentopened--;
185
}
186
187
/**
188
 * Generate a zip with all data of web site.
189
 *
190
 * @param 	Website		$website		Object website
191
 * @return  void
192
 */
193
function exportWebSite($website)
194
{
195
	global $db, $conf;
196
197
	dol_mkdir($conf->websites->dir_temp);
198
	$srcdir = $conf->websites->dir_output.'/'.$website->ref;
199
	$destdir = $conf->websites->dir_temp.'/'.$website->ref;
200
201
	$arrayreplacement=array();
202
203
	dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
204
205
	$srcdir = DOL_DATA_ROOT.'/medias/images/'.$website->ref;
206
	$destdir = $conf->websites->dir_temp.'/'.$website->ref.'/medias/images/'.$website->ref;
207
208
	dolCopyDir($srcdir, $destdir, 0, 1, $arrayreplacement);
209
210
	// Build sql file
211
	dol_mkdir($conf->websites->dir_temp.'/'.$website->ref.'/export');
212
213
	$filesql = $conf->websites->dir_temp.'/'.$website->ref.'/export/pages.sql';
214
	$fp = fopen($filesql,"w");
215
216
	$objectpages = new WebsitePage($db);
217
	$listofpages = $objectpages->fetchAll($website->id);
218
219
	// Assign ->newid and ->newfk_page
220
	$i=1;
221
	foreach($listofpages as $pageid => $objectpageold)
222
	{
223
		$objectpageold->newid=$i;
224
		$i++;
225
	}
226
	$i=1;
227
	foreach($listofpages as $pageid => $objectpageold)
228
	{
229
		// Search newid
230
		$newfk_page=0;
231
		foreach($listofpages as $pageid2 => $objectpageold2)
232
		{
233
			if ($pageid2 == $objectpageold->fk_page)
234
			{
235
				$newfk_page = $objectpageold2->newid;
236
				break;
237
			}
238
		}
239
		$objectpageold->newfk_page=$newfk_page;
240
		$i++;
241
	}
242
	foreach($listofpages as $pageid => $objectpageold)
243
	{
244
		$line = 'INSERT INTO llx_website_page(rowid, fk_page, fk_website, pageurl, title, description, keyword, status, date_creation, tms, lang, import_key, grabbed_from, content)';
245
		$line.= " VALUES(";
246
		$line.= $objectpageold->newid."+__MAXROWID__, ";
247
		$line.= ($objectpageold->newfk_page ? $db->escape($objectpageold->newfk_page)."+__MAXROWID__" : "null").", ";
248
		$line.= "__WEBSITE_ID__, ";
249
		$line.= "'".$db->escape($objectpageold->pageurl)."', ";
250
		$line.= "'".$db->escape($objectpageold->title)."', ";
251
		$line.= "'".$db->escape($objectpageold->description)."', ";
252
		$line.= "'".$db->escape($objectpageold->keyword)."', ";
253
		$line.= "'".$db->escape($objectpageold->status)."', ";
254
		$line.= "'".$db->idate($objectpageold->date_creation)."', ";
255
		$line.= "'".$db->idate($objectpageold->date_modification)."', ";
256
		$line.= "'".$db->escape($objectpageold->lang)."', ";
257
		$line.= ($objectpageold->import_key ? "'".$db->escape($objectpageold->import_key)."'" : "null").", ";
258
		$line.= "'".$db->escape($objectpageold->grabbed_from)."', ";
259
		$line.= "'".$db->escape($objectpageold->content)."'";
260
		$line.= ");";
261
		$line.= "\n";
262
		fputs($fp, $line);
263
	}
264
265
	fclose($fp);
266
	if (! empty($conf->global->MAIN_UMASK))
267
		@chmod($filesql, octdec($conf->global->MAIN_UMASK));
268
269
	// Build zip file
270
	$filedir = $conf->websites->dir_temp.'/'.$website->ref;
271
	$fileglob = $conf->websites->dir_temp.'/'.$website->ref.'/export/'.$website->ref.'_export_*.zip';
272
	$filename = $conf->websites->dir_temp.'/'.$website->ref.'/export/'.$website->ref.'_export_'.dol_print_date(dol_now(),'dayhourlog').'.zip';
273
274
	dol_delete_file($fileglob, 0);
275
	dol_compress_file($filedir, $filename, 'zip');
276
277
	return $filename;
278
}
279
280
281
/**
282
 * Download all images found into page content $tmp.
283
 * If $modifylinks is set, links to images will be replace with a link to viewimage wrapper.
284
 *
285
 * @param 	Website	 	$object			Object website
286
 * @param 	WebsitePage	$objectpage		Object website page
287
 * @param 	string		$urltograb		URL to grab (exemple: http://www.nltechno.com/ or http://www.nltechno.com/dir1/ or http://www.nltechno.com/dir1/mapage1)
288
 * @param 	string		$tmp			Content to parse
289
 * @param 	string		$action			Var $action
290
 * @param	string		$modifylinks	0=Do not modify content, 1=Replace links with a link to viewimage
291
 * @return	void
292
 */
293
function getAllImages($object, $objectpage, $urltograb, &$tmp, &$action, $modifylinks=0)
294
{
295
	global $conf;
296
297
	$alreadygrabbed=array();
298
299
	if (preg_match('/\/$/', $urltograb)) $urltograb.='.';
300
	$urltograb = dirname($urltograb);							// So urltograb is now http://www.nltechno.com or http://www.nltechno.com/dir1
301
302
	preg_match_all('/<img([^\.\/]+)src="([^>"]+)"([^>]*)>/i', $tmp, $regs);
303
304
	foreach ($regs[0] as $key => $val)
305
	{
306
		if (preg_match('/^data:image/i', $regs[2][$key])) continue;		// We do nothing for such images
307
308
		$urltograbbis = $urltograb.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
309
		$linkwithoutdomain = $regs[2][$key];
310
		$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
311
		if (preg_match('/^http/', $regs[2][$key]))
312
		{
313
			$urltograbbis = $regs[2][$key];
314
			$linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
315
			$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
316
		}
317
318
		$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
319
320
		// Clean the aa/bb/../cc into aa/cc
321
		$filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
322
		$filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
323
324
		//var_dump($filetosave);
325
		//var_dump($filename);
326
		//exit;
327
328
		if (empty($alreadygrabbed[$urltograbbis]))
329
		{
330
			$tmpgeturl = getURLContent($urltograbbis);
331
			if ($tmpgeturl['curl_error_no'])
332
			{
333
				$error++;
0 ignored issues
show
Bug introduced by
The variable $error does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
334
				setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors');
335
				$action='create';
336
			}
337
			else
338
			{
339
				$alreadygrabbed[$urltograbbis]=1;	// Track that file was alreay grabbed.
340
341
				dol_mkdir(dirname($filetosave));
342
343
				$fp = fopen($filetosave, "w");
344
				fputs($fp, $tmpgeturl['content']);
345
				fclose($fp);
346
				if (! empty($conf->global->MAIN_UMASK))
347
					@chmod($file, octdec($conf->global->MAIN_UMASK));
0 ignored issues
show
Bug introduced by
The variable $file does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
348
			}
349
		}
350
351
		if ($modifylinks)
352
		{
353
			$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);
354
		}
355
	}
356
357
	// Search X in "background...url(X)"
358
	preg_match_all('/background([^\.\/\(;]+)url\([\"\']?([^\)\"\']*)[\"\']?\)/i', $tmp, $regs);
359
360
	foreach ($regs[0] as $key => $val)
361
	{
362
		if (preg_match('/^data:image/i', $regs[2][$key])) continue;		// We do nothing for such images
363
364
		$urltograbbis = $urltograb.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
365
366
		$linkwithoutdomain = $regs[2][$key];
367
		$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key];
368
369
		if (preg_match('/^http/', $regs[2][$key]))
370
		{
371
			$urltograbbis = $regs[2][$key];
372
			$linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]);
373
			$filetosave = $conf->medias->multidir_output[$conf->entity].'/image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
374
		}
375
376
		$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain;
377
378
		// Clean the aa/bb/../cc into aa/cc
379
		$filetosave = preg_replace('/\/[^\/]+\/\.\./', '', $filetosave);
380
		$filename = preg_replace('/\/[^\/]+\/\.\./', '', $filename);
381
382
		//var_dump($filetosave);
383
		//var_dump($filename);
384
		//exit;
385
386
		if (empty($alreadygrabbed[$urltograbbis]))
387
		{
388
			$tmpgeturl = getURLContent($urltograbbis);
389
			if ($tmpgeturl['curl_error_no'])
390
			{
391
				$error++;
392
				setEventMessages($tmpgeturl['curl_error_msg'], null, 'errors');
393
				$action='create';
394
			}
395
			else
396
			{
397
				$alreadygrabbed[$urltograbbis]=1;	// Track that file was alreay grabbed.
398
399
				dol_mkdir(dirname($filetosave));
400
401
				$fp = fopen($filetosave, "w");
402
				fputs($fp, $tmpgeturl['content']);
403
				fclose($fp);
404
				if (! empty($conf->global->MAIN_UMASK))
405
					@chmod($file, octdec($conf->global->MAIN_UMASK));
406
			}
407
		}
408
409
		if ($modifylinks)
410
		{
411
			$tmp = preg_replace('/'.preg_quote($regs[0][$key],'/').'/i', 'background'.$regs[1][$key].'url("'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file='.$filename.'")', $tmp);
412
		}
413
	}
414
415
}
416
417