Skip to content

Commit

Permalink
refactor(HashCash): + feat localPath
Browse files Browse the repository at this point in the history
  • Loading branch information
mrflos authored and J9rem committed Sep 15, 2023
1 parent 2b963e9 commit 4c89a98
Show file tree
Hide file tree
Showing 42 changed files with 406 additions and 414 deletions.
16 changes: 15 additions & 1 deletion includes/YesWiki.php
Original file line number Diff line number Diff line change
Expand Up @@ -386,14 +386,28 @@ public function GetMessage()
return $message;
}

public function getBaseUrl()
public function getBaseUrl($useDataPath = false)
{
$url = explode('wakka.php', $this->config['base_url']);
$url = explode('index.php', $url[0]);
$url = preg_replace(array('/\/\?$/', '/\/$/'), '', $url[0]);
if ($useDataPath && !empty($this->config['dataPath']) ) {
// we add an imaginary folder in order to retrieve yeswiki assets from yeswiki's source folder. web servers need to be configured to redirect yeswiki-assets to the main yeswiki folder
$url .= '/yeswiki-assets';
}
return $url;
}

public function getLocalPath($folder = '')
{
$dataFolders = ['', 'cache', 'files', 'custom'];
if (in_array($folder, $dataFolders) && !empty($this->config['dataPath']) ) {
// we add an imaginary folder in order to retrieve yeswiki assets from yeswiki's source folder. web servers need to be configured to redirect yeswiki-assets to the main yeswiki folder
$folder = $this->config['dataPath'].'/'.$folder ;
}
return $folder;
}

public function Redirect($url)
{
header("Location: $url");
Expand Down
6 changes: 5 additions & 1 deletion includes/YesWikiInit.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,12 @@ class Init
public function __construct($config = array())
{
$this->getRoute();
if (!empty($_SERVER['YESWIKI_DATA_PATH']) && is_dir($_SERVER['YESWIKI_DATA_PATH'])) {
$this->configFile = $_SERVER['YESWIKI_DATA_PATH'].'/yeswiki.config.php';
}
$this->config = $this->getConfig($config);
$this->setIframeHeaders();

/* @todo : compare versions, start installer for update if necessary */
if (!file_exists($this->configFile)) {
$this->doInstall();
Expand Down Expand Up @@ -231,6 +234,7 @@ public function getConfig($wakkaConfig = array())
'timezone' => 'Europe/Paris', // Only used if not set in wakka.config.php nor in php.ini
'root_page' => 'PagePrincipale', // backup root_page if deleted from wakka.config.php
'wakka_name' => '', // backup wakka_name if deleted from wakka.config.php
'dataPath' => !empty($_SERVER['YESWIKI_DATA_PATH']) ? $_SERVER['YESWIKI_DATA_PATH'] : '',
'htmlPurifierActivated' => false, // TODO ectoplasme set to true
'favorites_activated' => true,
ArchiveService::PARAMS_KEY_IN_WAKKA => [
Expand Down
8 changes: 4 additions & 4 deletions includes/services/AssetsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function LinkCSSFile($file, $conditionstart = '', $conditionend = '', $at
$isUrl = strpos($file, "http://") === 0 || strpos($file, "https://") === 0;

if ($isUrl || !empty($file) && file_exists($file)) {
$href = $isUrl ? $file : "{$this->wiki->getBaseUrl()}/{$file}";
$href = $isUrl ? $file : "{$this->wiki->getBaseUrl(true)}/{$file}";
$revision = $this->wiki->GetConfigValue('yeswiki_release', null);
return <<<HTML
$conditionstart
Expand Down Expand Up @@ -112,7 +112,7 @@ public function AddJavascriptFile($file, $first = false, $module = false)

if (!empty($file) && file_exists($file)) {
// include local files
$code = "<script src='{$this->wiki->getBaseUrl()}/$file$rev'";
$code = "<script src='{$this->wiki->getBaseUrl(true)}/$file$rev'";
if (!str_contains($GLOBALS['js'], $code) || $first) {
if (!$first) {
$code .= " defer";
Expand All @@ -139,12 +139,12 @@ public function AddJavascriptFile($file, $first = false, $module = false)

private function mapFilePath($file)
{
// Handle backwar compatibility
// Handle backward compatibility
if (array_key_exists($file, self::BACKWARD_PATH_MAPPING)) {
$file = self::BACKWARD_PATH_MAPPING[$file];
}

// Handle production environement
// Handle production environment
if ($this->wiki->GetConfigValue('debug') != 'yes') {
if (array_key_exists($file, self::PRODUCTION_PATH_MAPPING)) {
$file = self::PRODUCTION_PATH_MAPPING[$file];
Expand Down
6 changes: 4 additions & 2 deletions includes/services/CommentService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class CommentService implements EventSubscriberInterface
protected $eventDispatcher;
protected $mailer;
protected $pageManager;
protected $hashcashService;
protected $params;
protected $pagesWhereCommentWereRendered;
protected $userManager;
Expand All @@ -35,6 +36,7 @@ public function __construct(
EventDispatcher $eventDispatcher,
Mailer $mailer,
PageManager $pageManager,
HashCashService $hashcashService,
ParameterBagInterface $params,
TemplateEngine $templateEngine,
UserManager $userManager
Expand All @@ -47,6 +49,7 @@ public function __construct(
$this->pageManager = $pageManager;
$this->templateEngine = $templateEngine;
$this->userManager = $userManager;
$this->hashcashService = $hashcashService;
$this->params = $params;
$this->pagesWhereCommentWereRendered = [];
$this->commentsActivated = $this->params->get('comments_activated');
Expand All @@ -71,8 +74,7 @@ public function addCommentIfAuthorized($content, $idComment = '')
} else {
if ($this->wiki->HasAccess("comment", $content['pagetag']) && $this->wiki->Loadpage($content['pagetag'])) {
if ($this->params->get('use_hashcash')) {
require_once('tools/security/secret/wp-hashcash.lib');
if (!isset($content["hashcash_value"]) || ($content["hashcash_value"] != hashcash_field_value())) {
if (!isset($content["hashcash_value"]) || ($content["hashcash_value"] != $this->hashcashService->hashcash_field_value())) {
return [
'code' => 400,
'error' => _t('HASHCASH_COMMENT_NOT_SAVED_MAYBE_YOU_ARE_A_ROBOT')
Expand Down
1 change: 1 addition & 0 deletions includes/services/Mailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ public function subscribeToMailingList($email, $mailingList)
// TODO when PR #967 merged, refactor this part with YesWiki::getBaseUrl
public function getBaseUrl(): string
{
// TODO: use getBaseUrl from core unless there is a trap ?
return preg_replace('/(\\/wakka\\.php\\?wiki=|\\/\\?wiki=|\\/\\?|\\/)$/m', '', $this->params->get('base_url')) ;
}

Expand Down
7 changes: 6 additions & 1 deletion includes/services/TemplateEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,11 @@ public function __construct(
}
}

$dataPath = (!empty($this->wiki->config['dataPath'])) ? $this->wiki->config['dataPath'].'/' : '';

// Set up twig
$this->twig = new \Twig\Environment($this->twigLoader, [
'cache' => 'cache/templates/',
'cache' => $dataPath.'cache/templates/',
'auto_reload' => true
]);

Expand All @@ -104,6 +106,9 @@ public function __construct(
$this->addTwigHelper('_t', function ($key, $params = []) {
return html_entity_decode(_t($key, $params));
});
$this->addTwigHelper('baseUrl', function ($useDataPath = null) {
return $this->wiki->getBaseUrl($useDataPath);
});
$this->addTwigHelper('url', function ($options) {
$options = array_merge(['tag' => '', 'handler' => '', 'params' => []], $options);
$iframe = !empty($options['handler']) ? $options['handler'] : testUrlInIframe();
Expand Down
5 changes: 3 additions & 2 deletions includes/urlutils.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ function getAbsoluteUrl()
* as it affects the resulting url. Defaults to false.
* @return string The base url of the wiki
*/
function computeBaseURL($rewrite_mode = false)
function computeBaseURL($rewrite_mode = false, $dataPath = null)
{
$scriptlocation = str_replace(array('/index.php', '/wakka.php'), '', $_SERVER["SCRIPT_NAME"]);
$prefix = (!empty($dataPath) && is_dir($dataPath)) ? '/yeswiki-assets' : '';
$scriptlocation = $prefix.str_replace(array('/index.php', '/wakka.php'), '', $_SERVER["SCRIPT_NAME"]);

return getRootUrl()
. $scriptlocation
Expand Down
4 changes: 2 additions & 2 deletions setup/footer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
ob_end_flush();
?>
</div>
<script src="<?php echo computeBaseURL(true); ?>javascripts/vendor/jquery/jquery.min.js"></script>
<script src="<?php echo computeBaseURL(true); ?>javascripts/vendor/bootstrap/bootstrap.min.js"></script>
<script src="<?php echo computeBaseURL(true, $yesWikiDataPath); ?>javascripts/vendor/jquery/jquery.min.js"></script>
<script src="<?php echo computeBaseURL(true, $yesWikiDataPath); ?>javascripts/vendor/bootstrap/bootstrap.min.js"></script>
</body>
</html>
7 changes: 4 additions & 3 deletions setup/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
if (!defined('YW_CHARSET')) {
define('YW_CHARSET', $charset);
}
$yesWikiDataPath = !empty($_SERVER['YESWIKI_DATA_PATH']) ? $_SERVER['YESWIKI_DATA_PATH'] : '';
header("Content-Type: text/html; charset=$charset");
ob_start();
?>
Expand All @@ -17,9 +18,9 @@
<head>
<meta charset="<?php echo $charset; ?>">
<title><?php echo _t('INSTALLATION_OF_YESWIKI'); ?></title>
<link href="<?php echo computeBaseUrl(true); ?>styles/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo computeBaseUrl(true); ?>styles/yeswiki-base.css" rel="stylesheet">
<link href="<?php echo computeBaseUrl(true); ?>themes/margot/styles/margot.css" rel="stylesheet">
<link href="<?php echo computeBaseUrl(true, $yesWikiDataPath); ?>styles/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo computeBaseUrl(true, $yesWikiDataPath); ?>styles/yeswiki-base.css" rel="stylesheet">
<link href="<?php echo computeBaseUrl(true, $yesWikiDataPath); ?>themes/margot/styles/margot.css" rel="stylesheet">
</head>

<body>
Expand Down
17 changes: 10 additions & 7 deletions setup/install.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@
foreach ($tablesNames as $tableName) {
try {
if (mysqli_num_rows(mysqli_query($dblink, "SHOW TABLES LIKE \"{$config['table_prefix']}$tableName\";")) !== 0 // existing table
&& mysqli_num_rows(mysqli_query($dblink, "SELECT * FROM `{$config['table_prefix']}$tableName`;")) === 0) /* empty table */{
&& mysqli_num_rows(mysqli_query($dblink, "SELECT * FROM `{$config['table_prefix']}$tableName`;")) === 0) { /* empty table */
mysqli_query($dblink, "DROP TABLE IF EXISTS `{$config['table_prefix']}$tableName`;");
}
} catch (\Throwable $th) {
Expand All @@ -148,11 +148,14 @@
);
mysqli_autocommit($dblink, true);

// get path is src and data are separated
$dataPath = (!empty($_SERVER['YESWIKI_DATA_PATH']) && is_dir($_SERVER['YESWIKI_DATA_PATH'])) ? $_SERVER['YESWIKI_DATA_PATH'].'/' : '';

// Config indexation by robots
if (!isset($config['allow_robots']) || $config['allow_robots'] != '1') {
// update robots.txt file
if (file_exists('robots.txt')) {
$robotFile = file_get_contents('robots.txt');
if (file_exists("{$dataPath}robots.txt")) {
$robotFile = file_get_contents("{$dataPath}robots.txt");
// replace text
if (preg_match(
"/User-agent: \*(\r?\n?)(?:\s*(?:Disa|A)llow:\s*\/\s*)?/",
Expand All @@ -173,16 +176,16 @@
$robotFile .= "Disallow: /\n";
}
// save robots.txt file
file_put_contents('robots.txt', $robotFile);
file_put_contents($dataPath.'robots.txt', $robotFile);

// set meta
$config['meta'] = array_merge(
$config['meta'] ?? [],
['robots' => 'noindex,nofollow,max-image-preview:none,noarchive,noimageindex']
);
} else {
if (file_exists('robots.txt')) {
$robotFile = file_get_contents('robots.txt');
if (file_exists("{$dataPath}robots.txt")) {
$robotFile = file_get_contents("{$dataPath}robots.txt");
// replace text
if (preg_match(
"/User-agent: \*(\r?\n?)(?:\s*(?:Disa|A)llow:\s*\/\s*)?/",
Expand All @@ -203,7 +206,7 @@
$robotFile .= "Allow: /\n";
}
// save robots.txt file
file_put_contents('robots.txt', $robotFile);
file_put_contents("{$dataPath}robots.txt", $robotFile);
}


Expand Down
4 changes: 2 additions & 2 deletions setup/writeconfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
$config['db_charset'] = 'utf8mb4';

// convert config array into PHP code
$configCode = "<?php\n// wakka.config.php "._t('CREATED').' '.date('c')."\n// "._t('DONT_CHANGE_YESWIKI_VERSION_MANUALLY')." !\n\n\$wakkaConfig = ";
$configCode = "<?php\n// YesWiki config file "._t('CREATED').' '.date('c')."\n// "._t('DONT_CHANGE_YESWIKI_VERSION_MANUALLY')." !\n\n\$wakkaConfig = ";
if (function_exists('var_export')) {
// var_export gives a better result but was added in php 4.2.0 (wikini asks only php 4.1.0)
$configCode .= var_export($config, true).";\n?>";
Expand All @@ -48,7 +48,7 @@
// write
fclose($fp);

echo "<br />\n<div class=\"alert alert-success\"><strong>"._t('FINISHED_CONGRATULATIONS').' !</strong><br />'._t('IT_IS_RECOMMANDED_TO_REMOVE_WRITE_ACCESS_TO_CONFIG_FILE').' <tt>wakka.config.php</tt> ('._t('THIS_COULD_BE_UNSECURE').').</div>';
echo "<br />\n<div class=\"alert alert-success\"><strong>"._t('FINISHED_CONGRATULATIONS').' !</strong><br />'._t('IT_IS_RECOMMANDED_TO_REMOVE_WRITE_ACCESS_TO_CONFIG_FILE').' <tt>'.$wakkaConfigLocation.'</tt> ('._t('THIS_COULD_BE_UNSECURE').').</div>';
echo "<div class=\"form-actions\">\n<a class=\"btn btn-lg btn-primary\" href=\"",$config['base_url'].$config['root_page'],'">'._t('GO_TO_YOUR_NEW_YESWIKI_WEBSITE')."</a>\n</div>\n";
//header('Location: '.$config['base_url'].$config['root_page']);
} else {
Expand Down
2 changes: 1 addition & 1 deletion tools/attach/actions/player.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
</div>';
echo $output;
} elseif ($extension=="mm") {
$output = '<embed id="visorFreeMind" height="'.$height.'" align="middle" width="'.$width.'" flashvars="openUrl=_blank&initLoadFile='.$url.'&startCollapsedToLevel=5" quality="high" bgcolor="#ffffff" src="tools/attach/players/visorFreemind.swf" type="application/x-shockwave-flash"/>';
$output = '<embed id="visorFreeMind" height="'.$height.'" align="middle" width="'.$width.'" flashvars="openUrl=_blank&initLoadFile='.$url.'&startCollapsedToLevel=5" quality="high" bgcolor="#ffffff" src="'.$this->getBaseUrl(true).'/tools/attach/players/visorFreemind.swf" type="application/x-shockwave-flash"/>';
$output .="[<a href=\"$url\" title=\""._t('ATTACH_DOWNLOAD_THE_FILE')."\">mm</a>]";
echo $output;
} else {
Expand Down
2 changes: 1 addition & 1 deletion tools/attach/handlers/AjaxUploadHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function run()
$sizeLimit = $att->attachConfig['max_file_size'];

$uploader = new qqFileUploader($allowedExtensions, $sizeLimit, $this->hasTempTag);
$result = $uploader->handleUpload($att->attachConfig['upload_path']);
$result = $uploader->handleUpload($att->getUploadPath());
} catch (\Throwable $th) {
$errorsMessage .= "{$th->getMessage()} in {$th->getFile()}, line {$th->getLine()}";
}
Expand Down
29 changes: 14 additions & 15 deletions tools/attach/libs/attach.lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,17 +130,6 @@ public function mkdir_recursif($dir)
public function GetScriptPath()
{
return $this->wiki->getBaseUrl().'/';
// if (preg_match("/.(php)$/i", $_SERVER["PHP_SELF"])) {
// $a = explode('/', $_SERVER["PHP_SELF"]);
// $a[count($a) - 1] = '';
// $path = implode('/', $a);
// } else {
// $path = $_SERVER["PHP_SELF"];
// }
// $http = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://');
// return !empty($_SERVER["HTTP_HOST"]) ?
// $http . $_SERVER["HTTP_HOST"] . $path
// : $http . $_SERVER["SERVER_NAME"] . $path;
}
/**
* Calcul le repertoire d'upload en fonction du safe_mode
Expand All @@ -155,7 +144,11 @@ public function GetUploadPath()
$this->mkdir_recursif($path);
}
}
return $path;
if (!empty($this->wiki->config['dataPath'])) {
return $this->wiki->config['dataPath'].'/'.$path;
} else {
return $path;
}
}
/**
* Calcul le repertoire de cache en fonction du safe_mode
Expand All @@ -170,7 +163,11 @@ public function GetCachePath()
$this->mkdir_recursif($path);
}
}
return $path;
if (!empty($this->wiki->config['dataPath'])) {
return $this->wiki->config['dataPath'].'/'.$path;
} else {
return $path;
}
}
/**
* Calcule le nom complet du fichier attach&eacute; en fonction du safe_mode, du nom et de la date de
Expand Down Expand Up @@ -499,14 +496,16 @@ public function showAsImage($fullFilename)
$height = $this->height;
$img_name = $fullFilename;
}
$imgUrl = $this->GetScriptPath() . str_replace($this->wiki->getLocalPath(), '', $img_name);

// pour l'image avec bordure on enleve la taille de la bordure!
if (strstr($this->classes, 'whiteborder')) {
$width = $width - 20;
$height = $height - 20;
}

//c'est une image : balise <IMG..../>
$img = "<img loading=\"lazy\" class=\"img-responsive\" src=\"" . $this->GetScriptPath() . $img_name . "\" " .
$img = "<img loading=\"lazy\" class=\"img-responsive\" src=\"$imgUrl\" " .
"alt=\"" . $this->desc . ($this->link ? "\nLien vers: $this->link" : "") . "\" width=\"" . $width . "\" height=\"" . $height . "\" />";
//test si c'est une image sensible
$classDataForLinks =
Expand Down Expand Up @@ -1078,7 +1077,7 @@ public function getResizedFilename($fullFilename, $width, $height, string $mode
{
$uploadPath = $this->GetUploadPath();
$cachePath = $this->GetCachePath();
$newFileName = preg_replace("/^$uploadPath/", "$cachePath", $fullFilename);
$newFileName = preg_replace("~^$uploadPath~", "$cachePath", $fullFilename);
$newFileName = $this->calculer_nom_fichier_vignette($newFileName, $width, $height);
if ($mode == "crop") {
$newFileName = preg_replace("/_vignette_/", "_cropped_", $newFileName);
Expand Down
2 changes: 1 addition & 1 deletion tools/attach/templates/actions/pdf.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{% block main %}
<span class="throbber pdf-block-loading"></span>
<iframe
src="javascripts/vendor/pdfjs-dist/web/pdf-viewer.php?file={{ url|e('url') }}"
src="{{ baseUrl(true) }}/javascripts/vendor/pdfjs-dist/web/pdf-viewer.php?file={{ url|e('url') }}"
class="embed-responsive-item" frameborder="0" allowfullscreen
onload="$(this).siblings('.pdf-block-loading').hide();"
>
Expand Down
Loading

0 comments on commit 4c89a98

Please sign in to comment.