Completed
Branch develop (b0e62f)
by
unknown
27:54
created

index.php ➔ dolWebsiteReplacementOfLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2016-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/website/index.php
20
 *		\ingroup    website
21
 *		\brief      Page to website view/edit
22
 */
23
24
define('NOSCANPOSTFORINJECTION',1);
25
define('NOSTYLECHECK',1);
26
27
28
/**
29
 *	Show HTML header HTML + BODY + Top menu + left menu + DIV
30
 *
31
 * @param 	string 	$head				Optionnal head lines
32
 * @param 	string 	$title				HTML title
33
 * @param	string	$help_url			Url links to help page
34
 * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
35
 *                                  	For other external page: http://server/url
36
 * @param	string	$target				Target to use on links
37
 * @param 	int    	$disablejs			More content into html header
38
 * @param 	int    	$disablehead		More content into html header
39
 * @param 	array  	$arrayofjs			Array of complementary js files
40
 * @param 	array  	$arrayofcss			Array of complementary css files
41
 * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (set this only if autodetect fails)
42
 * @return	void
43
 */
44
function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='')
0 ignored issues
show
Best Practice introduced by
The function llxHeader() has been defined more than once; this definition is ignored, only the first definition in htdocs/asterisk/wrapper.php (L46-52) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
45
{
46
    global $conf;
47
48
    // html header
49
    top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
50
51
    print '<body id="mainbody">';
52
53
    // top menu and left menu area
54
    if (empty($conf->dol_hide_topmenu))
55
    {
56
        top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
57
    }
58
    if (empty($conf->dol_hide_leftmenu))
59
    {
60
        left_menu('', $help_url, '', '', 1, $title, 1);
61
    }
62
63
    // main area
64
    //main_area($title);
65
    print '<!-- Begin div class="fiche" -->'."\n".'<div class="fichebutwithotherclass">'."\n";
66
}
67
68
69
require '../main.inc.php';
70
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
71
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
72
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
73
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
74
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formwebsite.class.php';
75
require_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php';
76
require_once DOL_DOCUMENT_ROOT.'/websites/class/websitepage.class.php';
77
78
$langs->load("admin");
79
$langs->load("other");
80
$langs->load("website");
81
82
if (! $user->admin) accessforbidden();
83
84
if (! ((GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)))
85
{
86
    $conf->dol_hide_leftmenu = 1;   // Force hide of left menu.
87
}
88
89
$error=0;
90
$website=GETPOST('website', 'alpha');
91
$page=GETPOST('page', 'alpha');
92
$pageid=GETPOST('pageid', 'int');
93
$pageref=GETPOST('pageref', 'aZ09');
94
$action=GETPOST('action','alpha');
95
96
if (GETPOST('delete')) { $action='delete'; }
97
if (GETPOST('preview')) $action='preview';
98
if (GETPOST('create')) { $action='create'; }
99
if (GETPOST('editmedia')) { $action='editmedia'; }
100
if (GETPOST('editcss')) { $action='editcss'; }
101
if (GETPOST('editmenu')) { $action='editmenu'; }
102
if (GETPOST('setashome')) { $action='setashome'; }
103
if (GETPOST('editmeta')) { $action='editmeta'; }
104
if (GETPOST('editsource')) { $action='editsource'; }
105
if (GETPOST('editcontent')) { $action='editcontent'; }
106
if (GETPOST('createfromclone')) { $action='createfromclone'; }
107
if (GETPOST('createpagefromclone')) { $action='createpagefromclone'; }
108
109
if (empty($action)) $action='preview';
110
111
$object=new Website($db);
112
$objectpage=new WebsitePage($db);
113
114
$object->fetchAll();    // Init $object->records
115
116
// If website not defined, we take first found
117
if (empty($website))
118
{
119
    foreach($object->records as $key => $valwebsite)
120
    {
121
        $website=$valwebsite->ref;
122
        break;
123
    }
124
}
125
if ($website)
126
{
127
    $res = $object->fetch(0, $website);
128
}
129
130
if ($pageid < 0) $pageid = 0;
131
if (($pageid > 0 || $pageref) && $action != 'add')
132
{
133
	$res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref);
134
    $pageid = $objectpage->id;
135
}
136
137
global $dolibarr_main_data_root;
138
$pathofwebsite=$dolibarr_main_data_root.'/websites/'.$website;
139
$filehtmlheader=$pathofwebsite.'/htmlheader.html';
140
$filecss=$pathofwebsite.'/styles.css.php';
141
$filerobot=$pathofwebsite.'/robots.txt';
142
$filehtaccess=$pathofwebsite.'/.htaccess';
143
$filetpl=$pathofwebsite.'/page'.$pageid.'.tpl.php';
144
$fileindex=$pathofwebsite.'/index.php';
145
146
// Define $urlwithroot
147
$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
148
$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
149
//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
150
151
152
153
/*
154
 * Actions
155
 */
156
157
if (GETPOST('refreshsite')) $pageid=0;      // If we change the site, we reset the pageid.
158
if (GETPOST('refreshpage') && ! in_array($action, array('updatecss'))) $action='preview';
159
160
// Add page
161
if ($action == 'add')
162
{
163
    $db->begin();
164
165
    $objectpage->fk_website = $object->id;
166
167
    $objectpage->title = GETPOST('WEBSITE_TITLE');
168
    $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME');
169
    $objectpage->description = GETPOST('WEBSITE_DESCRIPTION');
170
    $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS');
171
    $objectpage->lang = GETPOST('WEBSITE_LANG');
172
173
    if (empty($objectpage->pageurl))
174
    {
175
        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors');
176
        $error++;
177
        $action='create';
178
    }
179
    else if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl))
180
    {
181
    	setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors');
182
    	$error++;
183
    	$action='create';
184
    }
185
    if (empty($objectpage->title))
186
    {
187
        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors');
188
        $error++;
189
        $action='create';
190
    }
191
192
    if (! $error)
193
    {
194
        $res = $objectpage->create($user);
195
        if ($res <= 0)
196
        {
197
            $error++;
198
            setEventMessages($objectpage->error, $objectpage->errors, 'errors');
199
        }
200
    }
201
	if (! $error)
202
	{
203
		$db->commit();
204
	    setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs');
205
	    $action='';
206
	}
207
	else
208
	{
209
		$db->rollback();
210
	}
211
212
	if (! $error)
213
	{
214
	   $action = 'preview';
215
	   $id = $objectpage->id;
216
	}
217
}
218
219
// Update page
220
if ($action == 'delete')
221
{
222
    $db->begin();
223
224
    $res = $object->fetch(0, $website);
225
226
    $res = $objectpage->fetch($pageid, $object->fk_website);
227
228
    if ($res > 0)
229
    {
230
        $res = $objectpage->delete($user);
231
        if (! $res > 0)
232
        {
233
            $error++;
234
            setEventMessages($objectpage->error, $objectpage->errors, 'errors');
235
        }
236
237
        if (! $error)
238
        {
239
            $db->commit();
240
            setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs');
241
242
            header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website);
243
            exit;
244
        }
245
        else
246
        {
247
            $db->rollback();
248
        }
249
    }
250
    else
251
    {
252
        dol_print_error($db);
253
    }
254
}
255
256
// Update css
257
if ($action == 'updatecss')
258
{
259
	if (GETPOST('refreshsite') || GETPOST('refreshpage'))		// If we tried to reload another site/page, we stay on editcss mode.
260
	{
261
		$action='editcss';
262
	}
263
	else
264
	{
265
	    $res = $object->fetch(0, $website);
266
267
	    // Html header file
268
	    $htmlheadercontent ='';
269
270
	    $htmlheadercontent.= "<?php // BEGIN PHP\n";
271
	    $htmlheadercontent.= '$websitekey=basename(dirname(__FILE__));'."\n";
272
	    $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n";
273
	    $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
274
	    $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
275
	    $htmlheadercontent.= "ob_start();\n";
276
	    // $htmlheadercontent.= "header('Content-type: text/html');\n";		// Not required. htmlheader.html is never call as a standalone page
277
	    $htmlheadercontent.= "// END PHP ?>\n";
278
279
	    $htmlheadercontent.= preg_replace(array('/<html>\n*/ims','/<\/html>\n*/ims'),array('',''),GETPOST('WEBSITE_HTML_HEADER'));
280
281
	    $htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n";
282
	    $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
283
	    $htmlheadercontent.= "// END PHP ?>"."\n";
284
285
	    dol_syslog("Save file css into ".$filehtmlheader);
286
287
	    dol_mkdir($pathofwebsite);
288
	    $result = file_put_contents($filehtmlheader, $htmlheadercontent);
289
	    if (! empty($conf->global->MAIN_UMASK))
290
	        @chmod($filehtmlheader, octdec($conf->global->MAIN_UMASK));
291
292
	    if (! $result)
293
	    {
294
	        $error++;
295
	        setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors');
296
	    }
297
298
	    // Css file
299
	    $csscontent ='';
300
301
	    $csscontent.= "<?php // BEGIN PHP\n";
302
	    $csscontent.= '$websitekey=basename(dirname(__FILE__));'."\n";
303
	    $csscontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once dirname(__FILE__).'/master.inc.php'; } // Not already loaded"."\n";	// For the css, we need to set path of master using the dirname of css file.
304
	    $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
305
	    $csscontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
306
	    $csscontent.= "ob_start();\n";
307
	    $csscontent.= "header('Content-type: text/css');\n";
308
	    $csscontent.= "// END PHP ?>\n";
309
310
	    $csscontent.= GETPOST('WEBSITE_CSS_INLINE');
311
312
	    $csscontent.= "\n".'<?php // BEGIN PHP'."\n";
313
	    $csscontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
314
	    $csscontent.= "// END PHP ?>"."\n";
315
316
	    dol_syslog("Save file css into ".$filecss);
317
318
	    dol_mkdir($pathofwebsite);
319
	    $result = file_put_contents($filecss, $csscontent);
320
	    if (! empty($conf->global->MAIN_UMASK))
321
	        @chmod($filecss, octdec($conf->global->MAIN_UMASK));
322
323
	    if (! $result)
324
	    {
325
	        $error++;
326
	        setEventMessages('Failed to write file '.$filecss, null, 'errors');
327
	    }
328
329
330
	    // Css file
331
	    $robotcontent ='';
332
333
	    /*$robotcontent.= "<?php // BEGIN PHP\n";
334
	    $robotcontent.= '$websitekey=basename(dirname(__FILE__));'."\n";
335
	    $robotcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n";
336
	    $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
337
	    $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
338
	    $robotcontent.= "ob_start();\n";
339
	    $robotcontent.= "header('Content-type: text/css');\n";
340
	    $robotcontent.= "// END PHP ?>\n";*/
341
342
	    $robotcontent.= GETPOST('WEBSITE_ROBOT');
343
344
	    /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n";
345
	    $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
346
	    $robotcontent.= "// END PHP ?>"."\n";*/
347
348
	    dol_syslog("Save file robot into ".$filerobot);
349
350
	    dol_mkdir($pathofwebsite);
351
	    $result = file_put_contents($filerobot, $robotcontent);
352
	    if (! empty($conf->global->MAIN_UMASK))
353
	    	@chmod($filerobot, octdec($conf->global->MAIN_UMASK));
354
355
    	if (! $result)
356
    	{
357
    		$error++;
358
    		setEventMessages('Failed to write file '.$filerobot, null, 'errors');
359
    	}
360
361
362
    	// Css file
363
    	$htaccesscontent ='';
364
365
    	/*$robotcontent.= "<?php // BEGIN PHP\n";
366
    	 $robotcontent.= '$websitekey=basename(dirname(__FILE__));'."\n";
367
    	 $robotcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n";
368
    	 $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
369
    	 $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
370
    	 $robotcontent.= "ob_start();\n";
371
    	 $robotcontent.= "header('Content-type: text/css');\n";
372
    	 $robotcontent.= "// END PHP ?>\n";*/
373
374
    	$htaccesscontent.= GETPOST('WEBSITE_HTACCESS');
375
376
    	/*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n";
377
    	 $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
378
    	 $robotcontent.= "// END PHP ?>"."\n";*/
379
380
    	dol_syslog("Save file htaccess into ".$filehtaccess);
381
382
    	dol_mkdir($pathofwebsite);
383
    	$result = file_put_contents($filehtaccess, $htaccesscontent);
384
    	if (! empty($conf->global->MAIN_UMASK))
385
    		@chmod($filehtaccess, octdec($conf->global->MAIN_UMASK));
386
387
   		if (! $result)
388
   		{
389
   			$error++;
390
   			setEventMessages('Failed to write file '.$filehtaccess, null, 'errors');
391
   		}
392
393
		// Message if no error
394
	    if (! $error)
395
	    {
396
	        setEventMessages($langs->trans("Saved"), null, 'mesgs');
397
	    }
398
399
	    $action='preview';
400
	}
401
}
402
403
// Update page
404
if ($action == 'setashome')
405
{
406
    $db->begin();
407
    $object->fetch(0, $website);
408
409
    $object->fk_default_home = $pageid;
0 ignored issues
show
Documentation Bug introduced by
It seems like $pageid can also be of type string or array<integer,string>. However, the property $fk_default_home is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
410
    $res = $object->update($user);
411
    if (! $res > 0)
412
    {
413
        $error++;
414
        setEventMessages($objectpage->error, $objectpage->errors, 'errors');
415
    }
416
417
    if (! $error)
418
    {
419
        $db->commit();
420
421
        // Generate the index.php page to be the home page
422
        //-------------------------------------------------
423
        dol_mkdir($pathofwebsite);
424
        dol_delete_file($fileindex);
425
426
        $indexcontent = '<?php'."\n";
427
        $indexcontent.= '// File generated to provide a shortcut to the Home Page - DO NOT MODIFY - It is just an include.'."\n";
428
        $indexcontent.= "include_once './".basename($filetpl)."'\n";
429
        $indexcontent.= '?>'."\n";
430
        $result = file_put_contents($fileindex, $indexcontent);
431
        if (! empty($conf->global->MAIN_UMASK))
432
            @chmod($fileindex, octdec($conf->global->MAIN_UMASK));
433
434
        if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs');
435
        else setEventMessages('Failed to write file '.$fileindex, null, 'errors');
436
437
        $action='preview';
438
    }
439
    else
440
    {
441
        $db->rollback();
442
    }
443
}
444
445
// Update page (meta)
446
if ($action == 'updatemeta')
447
{
448
    $db->begin();
449
    $object->fetch(0, $website);
450
451
    $objectpage->fk_website = $object->id;
452
453
	// Check parameters
454
    if (! preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl))
455
    {
456
    	$error++;
457
    	setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors');
458
    	$action='editmeta';
459
    }
460
461
    $res = $objectpage->fetch($pageid, $object->fk_website);
462
    if ($res <= 0)
463
    {
464
    	$error++;
465
        dol_print_error($db, 'Page not found');
466
    }
467
468
    if (! $error)
469
    {
470
        $objectpage->old_object = clone $objectpage;
471
472
        $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME');
473
        $objectpage->title = GETPOST('WEBSITE_TITLE');
474
        $objectpage->description = GETPOST('WEBSITE_DESCRIPTION');
475
        $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS');
476
        $objectpage->lang = GETPOST('WEBSITE_LANG');
477
478
        $res = $objectpage->update($user);
479
        if (! $res > 0)
480
        {
481
            $error++;
482
            setEventMessages($objectpage->error, $objectpage->errors, 'errors');
483
        }
484
485
        if (! $error)
486
        {
487
            $db->commit();
488
489
            $filemaster=$pathofwebsite.'/master.inc.php';
490
            $fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php';
491
            $filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php';
492
493
            dol_mkdir($pathofwebsite);
494
495
496
            // Now generate the master.inc.php page
497
            dol_syslog("We regenerate the master file (because we update meta)");
498
            dol_delete_file($filemaster);
499
500
            $mastercontent = '<?php'."\n";
501
            $mastercontent.= '// File generated to link to the master file - DO NOT MODIFY - It is just an include'."\n";
502
            $mastercontent.= "if (! defined('USEDOLIBARRSERVER')) require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n";
503
            //$mastercontent.= "include_once DOL_DOCUMENT_ROOT.'/websites/class/website.class.php';"."\n";
504
            //$mastercontent.= '$website = new WebSite($db)'."\n";
505
            $mastercontent.= '?>'."\n";
506
            $result = file_put_contents($filemaster, $mastercontent);
507
            if (! empty($conf->global->MAIN_UMASK))
508
                @chmod($filemaster, octdec($conf->global->MAIN_UMASK));
509
510
            if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors');
511
512
513
            // Now generate the alias.php page
514
            if (! empty($fileoldalias))
515
            {
516
                dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias);
517
                dol_delete_file($fileoldalias);
518
            }
519
520
   		    $aliascontent = '<?php'."\n";
521
   		    $aliascontent.= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a copy of database page content\n";
522
   		    $aliascontent.= 'global $dolibarr_main_data_root;'."\n";
523
   		    $aliascontent.= 'if (empty($dolibarr_main_data_root)) require \'./page'.$objectpage->id.'.tpl.php\'; ';
524
   		    $aliascontent.= 'else require $dolibarr_main_data_root.\'/websites/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
525
   		    $aliascontent.= '?>'."\n";
526
   		    $result = file_put_contents($filealias, $aliascontent);
527
            if (! empty($conf->global->MAIN_UMASK))
528
                @chmod($filealias, octdec($conf->global->MAIN_UMASK));
529
530
            if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors');
531
532
			// Save page of content
533
            $result=dolSavePageContent($filetpl, $object, $objectpage);
534
535
            if ($result)
536
            {
537
                setEventMessages($langs->trans("Saved"), null, 'mesgs');
538
                //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid);
539
                //exit;
540
            }
541
            else
542
            {
543
            	setEventMessages('Failed to write file '.$filetpl, null, 'errors');
544
        	    //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid);
545
       	        //exit;
546
            }
547
548
            $action='preview';
549
        }
550
        else
551
        {
552
            $db->rollback();
553
        }
554
    }
555
}
556
557
// Update page
558
if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createpagefromclone')
559
	|| ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview'))))
560
{
561
    $object->fetch(0, $website);
562
563
	if ($action == 'confirm_createpagefromclone')
564
	{
565
		$istranslation=(GETPOST('is_a_translation','aZ09')=='on'?1:0);
566
		if ($istranslation)
567
		{
568
			if (GETPOST('newlang','aZ09') == $objectpage->lang)
569
			{
570
				$error++;
571
				setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors');
572
				$action='preview';
573
			}
574
		}
575
576
		if (! $error)
577
		{
578
	    	$objectpage = new WebsitePage($db);
579
			$result = $objectpage->createFromClone($pageid, GETPOST('pageurl','aZ09'), (GETPOST('newlang','aZ09')?GETPOST('newlang','aZ09'):''), $istranslation, GETPOST('newwebsite','int'));
580
			if ($result < 0)
581
			{
582
				$error++;
583
				setEventMessages($objectpage->error, $objectpage->errors, 'errors');
584
				$action='createpagefromclone';
585
			}
586
		}
587
    }
588
589
    $res = 0;
590
591
    if (! $error)
592
    {
593
	    // Check symlink to medias and restore it if ko
594
	    $pathtomedias=DOL_DATA_ROOT.'/medias';
595
	    $pathtomediasinwebsite=$pathofwebsite.'/medias';
596
	    if (! is_link(dol_osencode($pathtomediasinwebsite)))
597
	    {
598
	        dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite);
599
	        dol_mkdir(dirname($pathtomediasinwebsite));     // To be sure dir for website exists
600
	        $result = symlink($pathtomedias, $pathtomediasinwebsite);
601
	    }
602
603
	    /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite'))
604
	    {
605
	        $object->virtualhost = GETPOST('previewsite', 'alpha');
606
	        $object->update($user);
607
	    }*/
608
609
	    $objectpage->fk_website = $object->id;
610
611
	    if ($pageid > 0)
612
	    {
613
	        $res = $objectpage->fetch($pageid);
614
	    }
615
	    else
616
	    {
617
	        $res=0;
618
	        if ($object->fk_default_home > 0)
619
	        {
620
	            $res = $objectpage->fetch($object->fk_default_home);
621
	        }
622
	        if (! ($res > 0))
623
	        {
624
	            $res = $objectpage->fetch(0, $object->id);
625
	        }
626
	    }
627
    }
628
629
    if (! $error && $res > 0)
630
    {
631
        if ($action == 'updatesource' || $action == 'updatecontent')
632
        {
633
            $db->begin();
634
635
            $objectpage->content = GETPOST('PAGE_CONTENT');
636
637
            // Clean data. We remove all the head section.
638
            $objectpage->content = preg_replace('/<head>.*<\/head>/s', '', $objectpage->content);
639
            /* $objectpage->content = preg_replace('/<base\s+href=[\'"][^\'"]+[\'"]\s/?>/s', '', $objectpage->content); */
640
641
            $res = $objectpage->update($user);
642
            if ($res < 0)
643
            {
644
                $error++;
645
                setEventMessages($objectpage->error, $objectpage->errors, 'errors');
646
            }
647
648
        	if (! $error)
649
        	{
650
        		$db->commit();
651
652
        		$filemaster=$pathofwebsite.'/master.inc.php';
653
        		//$fileoldalias=$pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php';
654
        		$filealias=$pathofwebsite.'/'.$objectpage->pageurl.'.php';
655
656
        	    dol_mkdir($pathofwebsite);
657
658
659
        		// Now generate the master.inc.php page
660
        		dol_syslog("We regenerate the master file");
661
        		dol_delete_file($filemaster);
662
663
        		$mastercontent = '<?php'."\n";
664
        		$mastercontent.= '// File generated to link to the master file'."\n";
665
        		$mastercontent.= "if (! defined('USEDOLIBARRSERVER')) require_once '".DOL_DOCUMENT_ROOT."/master.inc.php';\n";
666
        		$mastercontent.= '?>'."\n";
667
        		$result = file_put_contents($filemaster, $mastercontent);
668
        		if (! empty($conf->global->MAIN_UMASK))
669
        		    @chmod($filemaster, octdec($conf->global->MAIN_UMASK));
670
671
    		    if (! $result) setEventMessages('Failed to write file '.$filemaster, null, 'errors');
672
673
674
    		    // Now generate the alias.php page
675
                if (! empty($fileoldalias))
676
                {
677
        		    dol_syslog("We regenerate alias page new name=".$filealias.", old name=".$fileoldalias);
678
        		    dol_delete_file($fileoldalias);
679
                }
680
681
    		    $aliascontent = '<?php'."\n";
682
    		    $aliascontent.= "// File generated to wrap the alias page - DO NOT MODIFY - It is just a copy of database page content\n";
683
    		    $aliascontent.= 'global $dolibarr_main_data_root;'."\n";
684
    		    $aliascontent.= 'if (empty($dolibarr_main_data_root)) require \'./page'.$objectpage->id.'.tpl.php\';';
685
    		    $aliascontent.= 'else require $dolibarr_main_data_root.\'/websites/\'.$website->ref.\'/page'.$objectpage->id.'.tpl.php\';'."\n";
686
    		    $aliascontent.= '?>'."\n";
687
    		    $result = file_put_contents($filealias, $aliascontent);
688
    		    if (! empty($conf->global->MAIN_UMASK))
689
    		        @chmod($filealias, octdec($conf->global->MAIN_UMASK));
690
691
                if (! $result) setEventMessages('Failed to write file '.$filealias, null, 'errors');
692
693
694
				// Save page content
695
        	    $result=dolSavePageContent($filetpl, $object, $objectpage);
696
697
        	    if ($result)
698
        	    {
699
        	        setEventMessages($langs->trans("Saved"), null, 'mesgs');
700
        	        header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid);
701
       	            exit;
702
        	    }
703
        	    else
704
        	    {
705
        	        setEventMessages('Failed to write file '.$filetpl, null, 'errors');
706
        	        header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid);
707
       	            exit;
708
        	    }
709
        	}
710
        	else
711
        	{
712
        		$db->rollback();
713
        	}
714
        }
715
        else
716
        {
717
            header("Location: ".$_SERVER["PHP_SELF"].'?website='.$website.'&pageid='.$pageid);
718
            exit;
719
        }
720
    }
721
    else
722
    {
723
        if (! $error) setEventMessages($langs->trans("NoPageYet"), null, 'warnings');
724
    }
725
}
726
727
728
729
/*
730
 * View
731
 */
732
733
$form = new Form($db);
734
$formadmin = new FormAdmin($db);
735
$formwebsite = new FormWebsite($db);
736
737
$help_url='';
738
739
llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, 0,
740
	array(
741
		'/includes/ace/ace.js',
742
		'/includes/ace/ext-statusbar.js',
743
		'/includes/ace/ext-language_tools.js',
744
		//'/includes/ace/ext-chromevox.js'
745
	), array());
746
747
print "\n".'<form action="'.$_SERVER["PHP_SELF"].'" method="POST"><div>';
748
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
749
if ($action == 'create')
750
{
751
    print '<input type="hidden" name="action" value="add">';
752
}
753
if ($action == 'editcss')
754
{
755
    print '<input type="hidden" name="action" value="updatecss">';
756
}
757
if ($action == 'editmenu')
758
{
759
    print '<input type="hidden" name="action" value="updatemenu">';
760
}
761
if ($action == 'setashome')
762
{
763
    print '<input type="hidden" name="action" value="updateashome">';
764
}
765
if ($action == 'editmeta')
766
{
767
    print '<input type="hidden" name="action" value="updatemeta">';
768
}
769
if ($action == 'editsource')
770
{
771
    print '<input type="hidden" name="action" value="updatesource">';
772
}
773
if ($action == 'editcontent')
774
{
775
    print '<input type="hidden" name="action" value="updatecontent">';
776
}
777
if ($action == 'edit')
778
{
779
    print '<input type="hidden" name="action" value="update">';
780
}
781
782
783
// Add a margin under toolbar ?
784
$style='';
785
if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') $style=' margin-bottom: 5px;';
786
787
//var_dump($objectpage);exit;
788
print '<div class="centpercent websitebar">';
789
790
if (count($object->records) > 0)
791
{
792
    // ***** Part for web sites
793
794
    print '<div class="websiteselection hideonsmartphoneimp">';
795
    print $langs->trans("Website").': ';
796
    print '</div>';
797
798
    // List of websites
799
    print '<div class="websiteselection">';
800
    $out='';
801
    $out.='<select name="website" class="minwidth100" id="website">';
802
    if (empty($object->records)) $out.='<option value="-1">&nbsp;</option>';
803
    // Loop on each sites
804
    $i=0;
805
    foreach($object->records as $key => $valwebsite)
806
    {
807
        if (empty($website)) $website=$valwebsite->ref;
808
809
        $out.='<option value="'.$valwebsite->ref.'"';
810
        if ($website == $valwebsite->ref) $out.=' selected';		// To preselect a value
811
        $out.='>';
812
        $out.=$valwebsite->ref;
813
        $out.='</option>';
814
        $i++;
815
    }
816
    $out.='</select>';
817
    $out.=ajax_combobox('website');
818
    print $out;
819
    print '<input type="submit" class="button" name="refreshsite" value="'.$langs->trans("Load").'">';
820
821
    if ($website)
822
    {
823
        $virtualurl='';
824
        $dataroot=DOL_DATA_ROOT.'/websites/'.$website;
825
        if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost;
826
    }
827
828
    if ($website && $action == 'preview')
829
    {
830
        $disabled='';
831
        if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"';
832
833
        print ' &nbsp; ';
834
835
        //print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="editmedia">';
836
        print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">';
837
        print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditMenu")).'" name="editmenu">';
838
        //print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("CloneSite")).'" name="createfromclone">';
839
    }
840
841
    print '</div>';
842
843
    // Button for websites
844
    print '<div class="websitetools">';
845
846
    if ($action == 'preview')
847
    {
848
        print '<div class="websiteinputurl" id="websiteinputurl">';
849
        print '<input type="text" id="previewsiteurl" class="minwidth200imp" name="previewsite" placeholder="'.$langs->trans("http://myvirtualhost").'" value="'.$virtualurl.'">';
850
        //print '<input type="submit" class="button" name="previewwebsite" target="tab'.$website.'" value="'.$langs->trans("ViewSiteInNewTab").'">';
851
        $htmltext=$langs->trans("SetHereVirtualHost", $dataroot);
852
        print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helpvirtualhost');
853
        print '</div>';
854
855
        $urlext=$virtualurl;
856
        $urlint=$urlwithroot.'/public/websites/index.php?website='.$website;
857
        print '<a class="websitebuttonsitepreview'.($urlext?'':' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewsiteext" href="'.$urlext.'" target="tab'.$website.'ext" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext)).'">';
858
        print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $dataroot, $urlext?$urlext:'<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'), 1, 'preview_ext');
859
        print '</a>';
860
861
        print '<a class="websitebuttonsitepreview" id="previewsite" href="'.$urlwithroot.'/public/websites/index.php?website='.$website.'" target="tab'.$website.'" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint)).'">';
862
        print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Site"), $langs->transnoentitiesnoconv("Site"), $urlint, $dataroot), 1, 'preview');
863
        print '</a>';
864
    }
865
866
    if (in_array($action, array('editcss','editmenu','create')))
867
    {
868
        if (preg_match('/^create/',$action)) print '<input type="submit" id="savefile" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
869
        if (preg_match('/^edit/',$action)) print '<input type="submit" id="savefile" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
870
        if ($action != 'preview') print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="preview">';
871
    }
872
873
    print '</div>';
874
875
876
    // ***** Part for pages
877
878
    if ($website)
879
    {
880
        print '</div>';
881
882
        $array=$objectpage->fetchAll($object->id);
883
        if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors);
884
        $atleastonepage=(is_array($array) && count($array) > 0);
885
886
        print '<div class="centpercent websitebar"'.($style?' style="'.$style.'"':'').'">';
887
888
        print '<div class="websiteselection hideonsmartphoneimp">';
889
        print '<input type="submit"'.$disabled.' class="button" value="'.dol_escape_htmltag($langs->trans("AddPage")).'" name="create">';
890
        print '</div>';
891
892
        print '<div class="websiteselection hideonsmartphoneimp">';
893
        print $langs->trans("Page").': ';
894
        print '</div>';
895
        print '<div class="websiteselection">';
896
897
        if ($action != 'add')
898
        {
899
            $out='';
900
            $out.='<select name="pageid" id="pageid" class="minwidth200 maxwidth300">';
901
            if ($atleastonepage)
902
            {
903
                if (empty($pageid) && $action != 'create')      // Page id is not defined, we try to take one
904
                {
905
                    $firstpageid=0;$homepageid=0;
906
                    foreach($array as $key => $valpage)
907
                    {
908
                        if (empty($firstpageid)) $firstpageid=$valpage->id;
909
                        if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id;
910
                    }
911
                    $pageid=$homepageid?$homepageid:$firstpageid;   // We choose home page and if not defined yet, we take first page
912
                }
913
914
                foreach($array as $key => $valpage)
915
                {
916
                    $out.='<option value="'.$key.'"';
917
                    if ($pageid > 0 && $pageid == $key) $out.=' selected';		// To preselect a value
918
                    $out.='>';
919
                    $out.=$valpage->pageurl.' - '.$valpage->title;
920
                    if ($object->fk_default_home && $key == $object->fk_default_home) $out.=' ('.$langs->trans("HomePage").')';
921
                    $out.='</option>';
922
                }
923
            }
924
            else $out.='<option value="-1">&nbsp;</option>';
925
            $out.='</select>';
926
            $out.=ajax_combobox('pageid');
927
            print $out;
928
        }
929
        else
930
        {
931
            print $langs->trans("New");
932
        }
933
934
        print '<input type="submit" class="button" name="refreshpage" value="'.$langs->trans("Load").'"'.($atleastonepage?'':' disabled="disabled"').'>';
935
936
        if ($action == 'preview' || $action == 'createpagefromclone')
937
        {
938
            $disabled='';
939
            if (empty($user->rights->websites->write)) $disabled=' disabled="disabled"';
940
941
            if ($pageid > 0)
942
            {
943
                // Confirmation to delete
944
                if ($action == 'createpagefromclone') {
945
	                // Create an array for form
946
					$formquestion = array(
947
						array('type' => 'text', 'name' => 'pageurl', 'label'=> $langs->trans("WEBSITE_PAGENAME")  ,'value'=> 'copy_of_'.$objectpage->pageurl),
948
						array('type' => 'checkbox', 'name' => 'is_a_translation', 'label' => $langs->trans("PageIsANewTranslation"), 'value' => 0),
949
						array('type' => 'other','name' => 'newlang','label' => $langs->trans("Language"), 'value' => $formadmin->select_language(GETPOST('newlang', 'az09')?GETPOST('newlang', 'az09'):$langs->defaultlang, 'newlang', 0, null, '', 0, 0, 'minwidth200')),
950
						array('type' => 'other','name' => 'newwebsite','label' => $langs->trans("Website"), 'value' => $formwebsite->selectWebsite($object->id, 'newwebsite', 0))
951
					);
952
953
	               	$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?pageid=' . $pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 250);
954
955
					print $formconfirm;
956
	            }
957
958
                print ' &nbsp; ';
959
960
                print '<input type="submit" class="button"'.$disabled.'  value="'.dol_escape_htmltag($langs->trans("EditPageSource")).'" name="editsource">';
961
                print '<input type="submit" class="button"'.$disabled.'  value="'.dol_escape_htmltag($langs->trans("EditPageContent")).'" name="editcontent">';
962
                print '<input type="submit" class="button"'.$disabled.'  value="'.dol_escape_htmltag($langs->trans("EditPageMeta")).'" name="editmeta">';
963
                if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) print '<input type="submit" class="button" disabled="disabled" value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">';
964
                else print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">';
965
        		print '<input type="submit" class="button"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("ClonePage")).'" name="createpagefromclone">';
966
                print '<input type="submit" class="buttonDelete" name="delete" value="'.$langs->trans("Delete").'"'.($atleastonepage?'':' disabled="disabled"').'>';
967
            }
968
        }
969
970
        print '</div>';
971
972
        print '<div class="websitetools">';
973
974
        if ($website && $pageid > 0 && ($action == 'preview' || $action == 'createpagefromclone'))
975
        {
976
            $websitepage = new WebSitePage($db);
977
            $websitepage->fetch($pageid);
978
979
            $realpage=$urlwithroot.'/public/websites/index.php?website='.$website.'&pageref='.$websitepage->pageurl;
980
            $pagealias = $websitepage->pageurl;
981
982
            print '<div class="websiteinputurl" id="websiteinputpage">';
983
            print '<input type="text" id="previewpageurl" class="minwidth200imp" name="previewsite" value="'.$pagealias.'" disabled="disabled">';
984
            $htmltext=$langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta"));
985
            print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias');
986
            print '</div>';
987
988
            $urlext=$virtualurl.'/'.$pagealias.'.php';
989
            $urlint=$urlwithroot.'/public/websites/index.php?website='.$website;
990
            print '<a class="websitebuttonsitepreview'.($virtualurl?'':' websitebuttonsitepreviewdisabled cursornotallowed').'" id="previewpageext" href="'.$urlext.'" target="tab'.$website.'ext" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $urlext)).'">';
991
            print $form->textwithpicto('', $langs->trans("PreviewSiteServedByWebServer", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $dataroot, $virtualurl?$urlext:'<span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span>'), 1, 'preview_ext');
992
            print '</a>';
993
994
            print '<a class="websitebuttonsitepreview" id="previewpage" href="'.$realpage.'&nocache='.dol_now().'" class="button" target="tab'.$website.'" alt="'.dol_escape_htmltag($langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage)).'">';
995
            print $form->textwithpicto('', $langs->trans("PreviewSiteServedByDolibarr", $langs->transnoentitiesnoconv("Page"), $langs->transnoentitiesnoconv("Page"), $realpage, $dataroot), 1, 'preview');
996
            print '</a>';       // View page in new Tab
997
            //print '<input type="submit" class="button" name="previewpage" target="tab'.$website.'"value="'.$langs->trans("ViewPageInNewTab").'">';
998
999
            // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext
1000
        }
1001
        if (! in_array($action, array('editcss','editmenu','create','createpagefromclone')))
1002
        {
1003
            if (preg_match('/^create/',$action)) print '<input type="submit" id="savefile" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
1004
            if (preg_match('/^edit/',$action)) print '<input type="submit" id="savefile" class="button" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">';
1005
            if ($action != 'preview') print '<input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="preview">';
1006
        }
1007
1008
        print '</div>';
1009
1010
        print '<div class="websitehelp">';
1011
        if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha'))
1012
        {
1013
        	$htmltext=$langs->transnoentitiesnoconv("YouCanEditHtmlSource");
1014
        	print $form->textwithpicto($langs->trans("SyntaxHelp"), $htmltext, 1, 'help', 'inline-block', 0, 2, 'tooltipsubstitution');
1015
        }
1016
        print '</div>';
1017
1018
1019
1020
        if ($action == 'preview' || $action == 'createpagefromclone')
1021
        {
1022
            // Adding jquery code to change on the fly url of preview ext
1023
            if (! empty($conf->use_javascript_ajax))
1024
            {
1025
                print '<script type="text/javascript" language="javascript">
1026
                    jQuery(document).ready(function() {
1027
                		jQuery("#websiteinputurl").keyup(function() {
1028
                            console.log("Website external url modified "+jQuery("#previewsiteurl").val());
1029
                			if (jQuery("#previewsiteurl").val() != "") jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 1 });
1030
                			else jQuery("a.websitebuttonsitepreviewdisabled img").css({ opacity: 0.2 });
1031
                		});
1032
                    	jQuery("#previewsiteext,#previewpageext").click(function() {
1033
                            newurl=jQuery("#previewsiteurl").val();
1034
                            newpage=jQuery("#previewsiteurl").val() + "/" + jQuery("#previewpageurl").val() + ".php";
1035
                            console.log("Open url "+newurl);
1036
                            /* Save url */
1037
                            jQuery.ajax({
1038
                                method: "POST",
1039
                                url: "'.DOL_URL_ROOT.'/core/ajax/saveinplace.php",
1040
                                data: {
1041
                                    field: \'editval_virtualhost\',
1042
                                    element: \'websites\',
1043
                                    table_element: \'website\',
1044
                                    fk_element: '.$object->id.',
1045
                                    value: newurl,
1046
                                },
1047
                                context: document.body
1048
                            });
1049
1050
                            jQuery("#previewsiteext").attr("href",newurl);
1051
                            jQuery("#previewpageext").attr("href",newpage);
1052
                        });
1053
                    });
1054
                    </script>';
1055
            }
1056
        }
1057
    }
1058
}
1059
else
1060
{
1061
    print '<div class="websiteselection">';
1062
    $langs->load("errors");
1063
    print $langs->trans("ErrorModuleSetupNotComplete");
1064
    print '<div>';
1065
    $action='';
1066
}
1067
1068
1069
print '</div>';
1070
1071
$head = array();
1072
1073
1074
/*
1075
 * Edit mode
1076
 */
1077
1078
if ($action == 'editcss')
1079
{
1080
    print '<div class="fiche">';
1081
1082
    print '<br>';
1083
1084
    $csscontent = @file_get_contents($filecss);
1085
    // Clean the php css file to remove php code and get only css part
1086
    $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent);
1087
    $csscontent.= GETPOST('WEBSITE_CSS_INLINE');
1088
    if (! trim($csscontent)) $csscontent='/* CSS content (all pages) */'."\n".'body.bodywebsite { margin: 0; }';
1089
1090
    $htmlheader = @file_get_contents($filehtmlheader);
1091
    // Clean the php htmlheader file to remove php code and get only html part
1092
    $htmlheader = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheader);
1093
    if (! trim($htmlheader)) $htmlheader='<html>'."\n".'<!-- HTML header content (all pages) -->'."\n".'</html>';
1094
    else $htmlheader='<html>'."\n".$htmlheader."\n".'</html>';
1095
1096
    $robotcontent = @file_get_contents($filerobot);
1097
    // Clean the php htmlheader file to remove php code and get only html part
1098
    $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent);
1099
    if (! trim($robotcontent))
1100
    {
1101
    	$robotcontent.="# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n";
1102
    	$robotcontent.="User-agent: *\n";
1103
    	$robotcontent.="Allow: /public/\n";
1104
    	$robotcontent.="Disallow: /administrator/\n";
1105
    }
1106
1107
    $htaccesscontent = @file_get_contents($filehtaccess);
1108
    // Clean the php htmlheader file to remove php code and get only html part
1109
    $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent);
1110
    if (! trim($htaccesscontent))
1111
    {
1112
    	$htaccesscontent.="# Order allow,deny\n";
1113
		$htaccesscontent.="# Deny from all\n";
1114
    }
1115
    //else $htaccesscontent='<html>'."\n".$htaccesscontent."\n".'</html>';*/
1116
1117
    dol_fiche_head();
1118
1119
    print '<!-- Edit CSS -->'."\n";
1120
    print '<table class="border" width="100%">';
1121
1122
    // Website
1123
    print '<tr><td class="titlefieldcreate">';
1124
    print $langs->trans('WebSite');
1125
    print '</td><td>';
1126
    print $website;
1127
    print '</td></tr>';
1128
1129
    // CSS file
1130
    print '<tr><td class="tdtop">';
1131
    print $langs->trans('WEBSITE_CSS_INLINE');
1132
    print '</td><td>';
1133
1134
    $doleditor=new DolEditor('WEBSITE_CSS_INLINE', $csscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', '');
1135
	print $doleditor->Create(1, '', true, 'CSS', 'css');
1136
1137
    print '</td></tr>';
1138
1139
    // Common HTML header
1140
	print '<tr><td class="tdtop">';
1141
    print $langs->trans('WEBSITE_HTML_HEADER');
1142
    print '</td><td>';
1143
1144
    $doleditor=new DolEditor('WEBSITE_HTML_HEADER', $htmlheader, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', '');
1145
	print $doleditor->Create(1, '', true, 'HTML Header', 'html');
1146
1147
    print '</td></tr>';
1148
1149
    // Robot file
1150
	print '<tr><td class="tdtop">';
1151
    print $langs->trans('WEBSITE_ROBOT');
1152
    print '</td><td>';
1153
1154
    $doleditor=new DolEditor('WEBSITE_ROBOT', $robotcontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', '');
1155
	print $doleditor->Create(1, '', true, 'Robot file', 'txt');
1156
1157
    print '</td></tr>';
1158
1159
    // .htaccess
1160
	print '<tr><td class="tdtop">';
1161
    print $langs->trans('WEBSITE_HTACCESS');
1162
    print '</td><td>';
1163
1164
    $doleditor=new DolEditor('WEBSITE_HTACCESS', $htaccesscontent, '', '220', 'ace', 'In', true, false, 'ace', 0, '100%', '');
1165
	print $doleditor->Create(1, '', true, $langs->trans("File").' .htaccess', 'txt');
1166
1167
    print '</td></tr>';
1168
1169
    print '</table>';
1170
1171
    dol_fiche_end();
1172
1173
    print '</div>';
1174
1175
    print '<br>';
1176
}
1177
1178
if ($action == 'editmeta' || $action == 'create')
1179
{
1180
    print '<div class="fiche">';
1181
1182
    print '<br>';
1183
1184
    dol_fiche_head();
1185
1186
    print '<!-- Edit Meta -->'."\n";
1187
    print '<table class="border" width="100%">';
1188
1189
    if ($action != 'create')
1190
    {
1191
        print '<tr><td>';
1192
        print $langs->trans('WEBSITE_PAGEURL');
1193
        print '</td><td>';
1194
        print '/public/websites/index.php?website='.urlencode($website).'&pageid='.urlencode($pageid);
1195
        print '</td></tr>';
1196
        $pageurl=$objectpage->pageurl;
1197
        $pagetitle=$objectpage->title;
1198
        $pagedescription=$objectpage->description;
1199
        $pagekeywords=$objectpage->keywords;
1200
        $pagelang=$objectpage->lang;
1201
    }
1202
    if (GETPOST('WEBSITE_PAGENAME'))    $pageurl=GETPOST('WEBSITE_PAGENAME','alpha');
1203
    if (GETPOST('WEBSITE_TITLE'))       $pagetitle=GETPOST('WEBSITE_TITLE','alpha');
1204
    if (GETPOST('WEBSITE_DESCRIPTION')) $pagedescription=GETPOST('WEBSITE_DESCRIPTION','alpha');
1205
    if (GETPOST('WEBSITE_KEYWORDS'))    $pagekeywords=GETPOST('WEBSITE_KEYWORDS','alpha');
1206
    if (GETPOST('WEBSITE_LANG'))        $pagelang=GETPOST('WEBSITE_LANG','aZ09');
1207
1208
    print '<tr><td class="titlefieldcreate fieldrequired">';
1209
    print $langs->trans('WEBSITE_PAGENAME');
1210
    print '</td><td>';
1211
    print '<input type="text" class="flat" size="96" name="WEBSITE_PAGENAME" value="'.dol_escape_htmltag($pageurl).'">';
1212
    print '</td></tr>';
1213
1214
    print '<tr><td class="fieldrequired">';
1215
    print $langs->trans('WEBSITE_TITLE');
1216
    print '</td><td>';
1217
    print '<input type="text" class="flat" size="96" name="WEBSITE_TITLE" value="'.dol_escape_htmltag($pagetitle).'">';
1218
    print '</td></tr>';
1219
1220
    print '<tr><td>';
1221
    print $langs->trans('WEBSITE_DESCRIPTION');
1222
    print '</td><td>';
1223
    print '<input type="text" class="flat" size="96" name="WEBSITE_DESCRIPTION" value="'.dol_escape_htmltag($pagedescription).'">';
1224
    print '</td></tr>';
1225
1226
    print '<tr><td>';
1227
    print $langs->trans('WEBSITE_KEYWORDS');
1228
    print '</td><td>';
1229
    print '<input type="text" class="flat" size="128" name="WEBSITE_KEYWORDS" value="'.dol_escape_htmltag($pagekeywords).'">';
1230
    print '</td></tr>';
1231
1232
    print '<tr><td>';
1233
    print $langs->trans('Language');
1234
    print '</td><td>';
1235
    print $formadmin->select_language($pagelang?$pagelang:$langs->defaultlang, 'WEBSITE_LANG');
1236
    print '</td></tr>';
1237
1238
    print '</table>';
1239
1240
    dol_fiche_end();
1241
1242
    print '</div>';
1243
1244
    print '<br>';
1245
}
1246
1247
if ($action == 'editmedia')
1248
{
1249
    print '<!-- Edit Media -->'."\n";
1250
    print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>';
1251
}
1252
1253
if ($action == 'editmenu')
1254
{
1255
    print '<!-- Edit Menu -->'."\n";
1256
    print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>';
1257
}
1258
1259
if ($action == 'editsource')
1260
{
1261
	/*
1262
	 * Editing global variables not related to a specific theme
1263
	 */
1264
1265
	//$csscontent = @file_get_contents($filecss);
1266
1267
	$contentforedit = '';
1268
	/*$contentforedit.='<style scoped>'."\n";        // "scoped" means "apply to parent element only". Not yet supported by browsers
1269
	 $contentforedit.=$csscontent;
1270
	 $contentforedit.='</style>'."\n";*/
1271
	$contentforedit .= $objectpage->content;
1272
1273
	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1274
	$doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,'ace',ROWS_5,'90%');
1275
	$doleditor->Create(0, '', false, 'HTML Source', 'php');
1276
}
1277
1278
if ($action == 'editcontent')
1279
{
1280
    /*
1281
     * Editing global variables not related to a specific theme
1282
     */
1283
1284
    //$csscontent = @file_get_contents($filecss);
1285
1286
    $contentforedit = '';
1287
    /*$contentforedit.='<style scoped>'."\n";        // "scoped" means "apply to parent element only". Not yet supported by browsers
1288
    $contentforedit.=$csscontent;
1289
    $contentforedit.='</style>'."\n";*/
1290
    $contentforedit .= $objectpage->content;
1291
1292
    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1293
    $doleditor=new DolEditor('PAGE_CONTENT',$contentforedit,'',500,'Full','',true,true,true,ROWS_5,'90%');
1294
    $doleditor->Create(0, '', false);
1295
}
1296
1297
print "</div>\n</form>\n";
1298
1299
1300
1301
if ($action == 'preview' || $action == 'createpagefromclone')
1302
{
1303
    if ($pageid > 0)
1304
    {
1305
    	// Ouput page under the Dolibarr top menu
1306
        $objectpage->fetch($pageid);
1307
        $csscontent = @file_get_contents($filecss);
1308
1309
        $out = '<!-- Page content '.$filetpl.' : Div with (CSS + Page content from database) -->'."\n";
1310
1311
        $out.='<div id="websitecontentundertopmenu" class="websitecontentundertopmenu">'."\n";
1312
1313
        // REPLACEMENT OF LINKS When page called by website editor
1314
1315
        $out.='<style scoped>'."\n";        // "scoped" means "apply to parent element only". Not yet supported by browsers
1316
        $out.=dolWebsiteReplacementOfLinks($csscontent);
1317
        $out.='</style>'."\n";
1318
1319
		$out.='<div id="bodywebsite" class="bodywebsite">'."\n";
1320
1321
        $out.=dolWebsiteReplacementOfLinks($objectpage->content)."\n";
1322
1323
        $out.='</div>';
1324
1325
        $out.='</div>';
1326
1327
        $out.= "\n".'<!-- End page content '.$filetpl.' -->'."\n\n";
1328
1329
        print $out;
1330
1331
        /*file_put_contents($filetpl, $out);
1332
        if (! empty($conf->global->MAIN_UMASK))
1333
            @chmod($filetpl, octdec($conf->global->MAIN_UMASK));
1334
1335
        // Output file on browser
1336
        dol_syslog("index.php include $filetpl $filename content-type=$type");
1337
        $original_file_osencoded=dol_osencode($filetpl);	// New file name encoded in OS encoding charset
1338
1339
        // This test if file exists should be useless. We keep it to find bug more easily
1340
        if (! file_exists($original_file_osencoded))
1341
        {
1342
            dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file));
1343
            exit;
1344
        }
1345
1346
        //include_once $original_file_osencoded;
1347
        */
1348
1349
        /*print '<iframe class="websiteiframenoborder centpercent" src="'.DOL_URL_ROOT.'/public/websites/index.php?website='.$website.'&pageid='.$pageid.'"/>';
1350
        print '</iframe>';*/
1351
    }
1352
    else
1353
    {
1354
        print '<br><br><div class="center">'.$langs->trans("PreviewOfSiteNotYetAvailable", $website).'</center><br><br><br>';
1355
        print '<div class="center"><div class="logo_setup"></div></div>';
1356
    }
1357
}
1358
1359
1360
1361
llxFooter();
1362
1363
$db->close();
1364
1365
1366
1367
/**
1368
 * Save content of a page on disk
1369
 *
1370
 * @param	string		$content			Content to replace
1371
 * @return	boolean							True if OK
1372
 */
1373
function dolWebsiteReplacementOfLinks($content)
1374
{
1375
	// Replace php code. Note $objectpage->content come from database and does not contains body tags.
1376
	$content = preg_replace('/<\?php[^\?]+\?>\n*/ims', '<span style="background: #ddd; border: 1px solid #ccc; border-radius: 4px;">...php...</span>', $content);
1377
1378
	// Replace relative link / with dolibarr URL
1379
	$content = preg_replace('/(href=")\/\"/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$object->ref.'&pageid='.$object->fk_default_home.'"', $content, -1, $nbrep);
0 ignored issues
show
Bug introduced by
The variable $object 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...
1380
	// Replace relative link /xxx.php with dolibarr URL
1381
	$content = preg_replace('/(href=")\/?([^\"]*)(\.php\")/', '\1'.DOL_URL_ROOT.'/websites/index.php?website='.$object->ref.'&pageref=\2"', $content, -1, $nbrep);
1382
1383
	$content = preg_replace('/url\((["\']?)medias\//', 'url(\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $content, -1, $nbrep);
1384
1385
	return $content;
1386
}
1387
1388
/**
1389
 * Save content of a page on disk
1390
 *
1391
 * @param	string		$filetpl			Full path of filename to generate
1392
 * @param	Website		$object				Object website
1393
 * @param	WebsitePage	$objectpage			Object websitepage
1394
 * @return	boolean							True if OK
1395
 */
1396
function dolSavePageContent($filetpl, $object, $objectpage)
1397
{
1398
	global $conf;
1399
1400
	// Now create the .tpl file (duplicate code with actions updatesource or updatecontent but we need this to save new header)
1401
	dol_syslog("We regenerate the tpl page filetpl=".$filetpl);
1402
1403
	dol_delete_file($filetpl);
1404
1405
	$shortlangcode = '';
1406
	if ($objectpage->lang) $shortlangcode=preg_replace('/[_-].*$/', '', $objectpage->lang);		// en_US or en-US -> en
1407
1408
	$tplcontent ='';
1409
	$tplcontent.= "<?php // BEGIN PHP\n";
1410
	$tplcontent.= '$websitekey=basename(dirname(__FILE__));'."\n";
1411
	$tplcontent.= "if (! defined('USEDOLIBARRSERVER')) { require_once './master.inc.php'; } // Not already loaded"."\n";
1412
	$tplcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n";
1413
	$tplcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n";
1414
	$tplcontent.= "ob_start();\n";
1415
	$tplcontent.= "// END PHP ?>\n";
1416
	$tplcontent.= '<html'.($shortlangcode ? ' lang="'.$shortlangcode.'"':'').'>'."\n";
1417
	$tplcontent.= '<head>'."\n";
1418
	$tplcontent.= '<title>'.dol_string_nohtmltag($objectpage->title, 0, 'UTF-8').'</title>'."\n";
1419
	$tplcontent.= '<meta charset="UTF-8">'."\n";
1420
	$tplcontent.= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'."\n";
1421
	$tplcontent.= '<meta name="robots" content="index, follow" />'."\n";
1422
	$tplcontent.= '<meta name="viewport" content="width=device-width, initial-scale=0.8">'."\n";
1423
	$tplcontent.= '<meta name="keywords" content="'.join(', ', explode(',',$objectpage->keywords)).'" />'."\n";
1424
	$tplcontent.= '<meta name="title" content="'.dol_string_nohtmltag($objectpage->title, 0, 'UTF-8').'" />'."\n";
1425
	$tplcontent.= '<meta name="description" content="'.dol_string_nohtmltag($objectpage->description, 0, 'UTF-8').'" />'."\n";
1426
	$tplcontent.= '<meta name="generator" content="'.DOL_APPLICATION_TITLE.' '.DOL_VERSION.'" />'."\n";
1427
	$tplcontent.= '<!-- Include link to CSS file -->'."\n";
1428
	$tplcontent.= '<link rel="stylesheet" href="styles.css.php?websiteid='.$object->id.'" type="text/css" />'."\n";
1429
	$tplcontent.= '<!-- Include common HTML header file -->'."\n";
1430
	$tplcontent.= '<?php print file_get_contents(DOL_DATA_ROOT."/websites/'.$object->ref.'/htmlheader.html"); ?>'."\n";
1431
	$tplcontent.= '</head>'."\n";
1432
1433
	$tplcontent.= '<!-- File generated by Dolibarr website module editor -->'."\n";
1434
	$tplcontent.= '<body id="bodywebsite" class="bodywebsite">'."\n";
1435
	$tplcontent.= $objectpage->content."\n";
1436
	$tplcontent.= '</body>'."\n";
1437
1438
	$tplcontent.= '<?php // BEGIN PHP'."\n";
1439
	$tplcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n";
1440
	$tplcontent.= "// END PHP ?>"."\n";
1441
1442
	//var_dump($filetpl);exit;
1443
	$result = file_put_contents($filetpl, $tplcontent);
1444
	if (! empty($conf->global->MAIN_UMASK))
1445
		@chmod($filetpl, octdec($conf->global->MAIN_UMASK));
1446
1447
	return $result;
1448
}
1449