openstamanager/lib/functions.php

442 lines
11 KiB
PHP
Raw Normal View History

<?php
2018-07-17 12:05:21 +02:00
/**
* Funzioni fondamentali per il corretto funzionamento del nucleo del progetto.
*
* @since 2.3
*/
/**
* Esegue il redirect.
*
* @param string $url
* @param string $type
*
* @return bool
*/
function redirect($url, $type = 'php')
{
switch ($type) {
case 'php':
header('Location: '.$url);
break;
case 'js':
echo '<script type="text/javascript">location.href="'.$url.'";</script>';
break;
}
}
/**
* Verifica e corregge il nome di un file.
*
* @param string $filename
*
* @return mixed
*/
function sanitizeFilename($filename)
{
$filename = str_replace(' ', '-', $filename);
$filename = preg_replace("/[^A-Za-z0-9_\-\.?!]/", '', $filename);
return $filename;
}
2018-07-17 12:05:21 +02:00
/**
* Elimina i file indicati.
*
* @param array $files
*
* @return bool
*/
function delete($files)
{
// Filesystem Symfony
$fs = new Symfony\Component\Filesystem\Filesystem();
// Eliminazione
try {
$fs->remove($files);
} catch (Symfony\Component\Filesystem\Exception\IOException $e) {
return false;
}
return true;
}
2018-07-17 12:05:21 +02:00
/**
* Controlla l'esistenza e i permessi di scrittura sul percorso indicato.
*
* @param string $path
*
* @return bool
*/
function directory($path)
{
if (is_dir($path) && is_writable($path)) {
return true;
} elseif (!is_dir($path)) {
// Filesystem Symfony
$fs = new Symfony\Component\Filesystem\Filesystem();
// Tentativo di creazione
try {
$fs->mkdir($path);
return true;
} catch (Symfony\Component\Filesystem\Exception\IOException $e) {
}
}
return false;
}
/**
* Copy a file, or recursively copy a folder and its contents.
*
2018-07-17 12:05:21 +02:00
* @param string $source Source path
* @param string $dest Destination path
* @param array|string $ignores Paths to ingore
*
* @return bool Returns TRUE on success, FALSE on failure
*/
function copyr($source, $destination, $ignores = [])
{
$finder = Symfony\Component\Finder\Finder::create()
->files()
->exclude((array) $ignores['dirs'])
->ignoreDotFiles(true)
->ignoreVCS(true)
->in($source);
2017-09-06 12:50:44 +02:00
foreach ((array) $ignores['files'] as $value) {
$finder->notName($value);
}
2017-09-06 12:50:44 +02:00
foreach ($finder as $file) {
$filename = rtrim($destination, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file->getRelativePathname();
// Filesystem Symfony
$fs = new Symfony\Component\Filesystem\Filesystem();
// Copia
try {
$fs->copy($file, $filename);
} catch (Symfony\Component\Filesystem\Exception\IOException $e) {
}
}
return true;
}
/**
* Crea un file zip comprimendo ricorsivamente tutte le sottocartelle a partire da una cartella specificata.
* *.
*
* @param string $source
* @param string $destination
* @param array $ignores
*/
function create_zip($source, $destination, $ignores = [])
{
if (!extension_loaded('zip')) {
2018-07-19 17:29:21 +02:00
flash()->error(tr('Estensione zip non supportata!'));
return false;
}
$zip = new ZipArchive();
2017-09-06 12:50:44 +02:00
$result = $zip->open($destination, ZIPARCHIVE::CREATE);
if ($result === true && is_writable(dirname($destination))) {
$finder = Symfony\Component\Finder\Finder::create()
->files()
->exclude((array) $ignores['dirs'])
->ignoreDotFiles(true)
->ignoreVCS(true)
->in($source);
foreach ((array) $ignores['files'] as $value) {
$finder->notName($value);
}
foreach ($finder as $file) {
$zip->addFile($file, $file->getRelativePathname());
}
$zip->close();
} else {
2018-07-19 17:29:21 +02:00
flash()->error(tr("Errore durante la creazione dell'archivio!"));
}
2017-09-06 12:50:44 +02:00
return $result === true;
}
/**
* Controllo dei file zip e gestione errori.
*
* @param string $zip_file
*
* @return string|bool
*/
function checkZip($zip_file)
{
$errno = zip_open($zip_file);
zip_close($errno);
if (!is_resource($errno)) {
// using constant name as a string to make this function PHP4 compatible
$errors = [
ZIPARCHIVE::ER_MULTIDISK => tr('archivi multi-disco non supportati'),
ZIPARCHIVE::ER_RENAME => tr('ridenominazione del file temporaneo fallita'),
ZIPARCHIVE::ER_CLOSE => tr('impossibile chiudere il file zip'),
ZIPARCHIVE::ER_SEEK => tr('errore durante la ricerca dei file'),
ZIPARCHIVE::ER_READ => tr('errore di lettura'),
ZIPARCHIVE::ER_WRITE => tr('errore di scrittura'),
ZIPARCHIVE::ER_CRC => tr('errore CRC'),
ZIPARCHIVE::ER_ZIPCLOSED => tr("l'archivio zip è stato chiuso"),
ZIPARCHIVE::ER_NOENT => tr('file non trovato'),
ZIPARCHIVE::ER_EXISTS => tr('il file esiste già'),
ZIPARCHIVE::ER_OPEN => tr('impossibile aprire il file'),
ZIPARCHIVE::ER_TMPOPEN => tr('impossibile creare il file temporaneo'),
ZIPARCHIVE::ER_ZLIB => tr('errore nella libreria Zlib'),
ZIPARCHIVE::ER_MEMORY => tr("fallimento nell'allocare memoria"),
ZIPARCHIVE::ER_CHANGED => tr('voce modificata'),
ZIPARCHIVE::ER_COMPNOTSUPP => tr('metodo di compressione non supportato'),
ZIPARCHIVE::ER_EOF => tr('fine del file non prevista'),
ZIPARCHIVE::ER_INVAL => tr('argomento non valido'),
ZIPARCHIVE::ER_NOZIP => tr('file zip non valido'),
ZIPARCHIVE::ER_INTERNAL => tr('errore interno'),
ZIPARCHIVE::ER_INCONS => tr('archivio zip inconsistente'),
ZIPARCHIVE::ER_REMOVE => tr('impossibile rimuovere la voce'),
ZIPARCHIVE::ER_DELETED => tr('voce eliminata'),
];
if (isset($errors[$errno])) {
return tr('Errore').': '.$errors[$errno];
}
return false;
} else {
return true;
}
}
/**
* Recupera informazioni sistema operativo dell'utente.
*
* @return string
*/
function getOS()
{
$os = [
'Windows NT 6.1' => 'Windows 7',
'Windows NT 6.0' => 'Windows Vista',
'Windows NT 5.1' => 'Windows XP',
'Windows NT 5.0' => 'Windows 2000',
'Windows NT 4.90' => 'Windows ME',
'Win95' => 'Windows 95',
'Win98' => 'Windows 98',
'Windows NT 5.2' => 'Windows NET',
'WinNT4.0' => 'Windows NT',
'Mac' => 'Mac',
'PPC' => 'Mac',
'Linux' => 'Linux',
'FreeBSD' => 'FreeBSD',
'SunOS' => 'SunOS',
'Irix' => 'Irix',
'BeOS' => 'BeOS',
'OS/2' => 'OS/2',
'AIX' => 'AIX',
];
foreach ($os as $key => $value) {
if (strpos($_SERVER['HTTP_USER_AGENT'], $key)) {
return $value;
}
}
return tr('Altro');
}
/**
* Ottiene l'indirizzo IP del client.
*
* @return string
*/
function get_client_ip()
{
$ipaddress = '';
2018-06-26 14:30:26 +02:00
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
} elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED'];
2018-06-26 14:30:26 +02:00
} elseif (!empty($_SERVER['REMOTE_ADDR']) and $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
$ipaddress = $_SERVER['REMOTE_ADDR'];
2018-06-26 14:30:26 +02:00
} elseif (!empty(gethostbyname(gethostname()))) {
$ipaddress = gethostbyname(gethostname());
} else {
$ipaddress = 'UNKNOWN';
}
return $ipaddress;
}
/**
* Traduce il template semplificato in componenti HTML.
*
* @since 2.3
*/
function translateTemplate()
{
$id_module = filter('id_module');
$id_plugin = filter('id_plugin');
$id_record = filter('id_record');
$id_email = filter('id_email');
$id_parent = filter('id_parent');
$template = ob_get_clean();
$template = \HTMLBuilder\HTMLBuilder::replace($template);
$template = str_replace('$id_module$', $id_module, $template);
$template = str_replace('$id_plugin$', $id_plugin, $template);
$template = str_replace('$id_record$', $id_record, $template);
// Informazioni estese sulle azioni dell'utente
if (Auth::check() && !empty(post('op'))) {
$database = \Database::getConnection();
$database->insert('zz_operations', [
'id_module' => $id_module,
'id_record' => $id_record,
'id_plugin' => !empty($id_plugin) ? $id_plugin : null,
'id_email' => !empty($id_email) ? $id_email : null,
'id_utente' => Auth::user()['id'],
'op' => post('op'),
]);
2017-09-15 15:52:40 +02:00
}
2018-07-19 12:47:28 +02:00
// Retrocompatibilità
if (!empty($_SESSION['infos'])) {
foreach ($_SESSION['infos'] as $message) {
2018-07-19 17:29:21 +02:00
flash()->info($message);
2018-07-19 12:47:28 +02:00
}
}
2018-07-19 12:47:28 +02:00
if (!empty($_SESSION['warnings'])) {
foreach ($_SESSION['warnings'] as $message) {
2018-07-19 17:29:21 +02:00
flash()->warning($message);
2018-07-19 12:47:28 +02:00
}
}
2018-07-19 12:47:28 +02:00
if (!empty($_SESSION['errors'])) {
foreach ($_SESSION['errors'] as $message) {
2018-07-19 17:29:21 +02:00
flash()->error($message);
2018-07-19 12:47:28 +02:00
}
}
// Annullo le notifiche (AJAX)
if (isAjaxRequest()) {
2018-07-19 17:29:21 +02:00
flash()->clearMessage('info');
}
echo $template;
}
/**
2018-04-09 09:42:03 +02:00
* Restituisce il percorso del filesystem in modo indipendente dal sistema operativo.
*
* @param string $string Percorso da correggere
*
* @since 2.3
*
* @return string
*/
function slashes($string)
{
return str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $string);
}
/**
* Controlla se è in corso una richiesta AJAX generata dal progetto.
*
* @since 2.3
*
* @return bool
*/
function isAjaxRequest()
{
return \Whoops\Util\Misc::isAjaxRequest() && filter('ajax') !== null;
}
/**
* Effettua le operazioni automatiche di redirect tra le pagine.
*
* @param int $id_module
* @param int $id_record
*
* @since 2.3
*/
function redirectOperation($id_module, $id_record)
{
$backto = filter('backto');
2017-09-15 16:37:19 +02:00
// Scelta del redirect dopo un submit
if (!empty($backto)) {
$hash = filter('hash');
$hash = !starts_with($hash, '#') ? '#'.$hash : $hash;
2017-09-15 16:37:19 +02:00
if ($backto == 'record-edit') {
redirect(ROOTDIR.'/editor.php?id_module='.$id_module.'&id_record='.$id_record.$hash);
} elseif ($backto == 'record-list') {
redirect(ROOTDIR.'/controller.php?id_module='.$id_module.$hash);
}
2017-09-15 16:37:19 +02:00
exit();
}
}
/**
* Predispone un testo per l'inserimento all'interno di un attributo HTML.
*
* @param string $string
*
* @return string
*/
function prepareToField($string)
{
return str_replace('"', '&quot;', $string);
}
2017-09-15 16:52:59 +02:00
/**
* Restituisce se l'user-agent (browser web) è una versione mobile.
*
* @return bool
*/
function isMobile()
{
return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER['HTTP_USER_AGENT']);
}
/**
* Restituisce il percorso derivante dal file in esecuzione.
*
* @return string
*/
function getURLPath()
{
$path = $_SERVER['SCRIPT_FILENAME'];
2018-01-03 13:24:04 +01:00
$prefix = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
if (substr($path, 0, strlen($prefix)) == $prefix) {
$path = substr($path, strlen($prefix));
} else {
$path = str_replace(DOCROOT, ROOTDIR, $path);
}
return slashes($path);
}