Inizio dockerizzazione

This commit is contained in:
2022-08-29 23:20:16 +02:00
parent b348b3a83d
commit 3d22f4cc6a
851 changed files with 1117 additions and 904 deletions
+18
View File
@@ -0,0 +1,18 @@
<VirtualHost *:80>
DocumentRoot /var/www/§PROJECT_BUILDNAME§
<Directory /var/www/§PROJECT_BUILDNAME§>
Options FollowSymLinks
AllowOverride None
Order allow,deny
allow from all
RewriteEngine On
RewriteRule "^(.*)$" "index.php" [NC,L,QSA]
</Directory>
</VirtualHost>
+25
View File
@@ -0,0 +1,25 @@
<VirtualHost *:80>
DocumentRoot /var/www/§PROJECT_BUILDNAME§
<Directory /var/www/§PROJECT_BUILDNAME§>
Options FollowSymLinks
AllowOverride None
Order allow,deny
allow from all
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule "^(.*)$" "$1.php" [NC,L,QSA]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule "^(api/.*)$" "api/index.php" [NC,L,QSA]
</Directory>
</VirtualHost>
+11
View File
@@ -0,0 +1,11 @@
[opcache]
opcache.enable=0
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=360
opcache.validate_timestamps=0
;opcache.preload=/var/www/§PROJECT_BUILDNAME§/load.php
opcache.preload_user=www-data
;opcache.blacklist_filename=/var/www/eden/index.php
opcache.fast_shutdown=1
+12
View File
@@ -0,0 +1,12 @@
display_errors = Off
display_startup_errors = On
zend.exception_ignore_args = On
error_reporting = E_ALL
session.save_handler=memcached
session.save_path=memcached:11211
session.gc_maxlifetime=1800
# post_max_size = 60M
# upload_max_filesize = 60M
+15
View File
@@ -0,0 +1,15 @@
#!/bin/bash
function exit_func {
echo "SIGTERM detected"
exit 1
}
trap exit_func SIGTERM SIGINT
ASD_BINDIR="/home/${DDNINJA_AUTHOR}/private/${DDNINJA_BUILDNAME}/bin"
mkdir -p "/tmp/${DDNINJA_AUTHOR}/${DDNINJA_BUILDNAME}"
chown -R www-data:www-data "/tmp/${DDNINJA_AUTHOR}/${DDNINJA_BUILDNAME}"
asdphp-entrypoint & wait
exit $?
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
my_dir="$(dirname "$0")"
source "$my_dir/.build.config"
LOG_PREFIX="$APPLICATION_BUILDNAME-CRONEXEC"
if [ -z "$1" ];
then
echo "$LOG_PREFIX ERROR!!! Missing time specifier" >> "$APPLICATION_LOG_PATH/task.log"
exit 1
fi
if [ "$1" == "5minutes" ] || [ "$1" == "minute" ] || [ "$1" == "daily" ] || [ "$1" == "hourly" ] || [ "$1" == "monthly" ] || [ "$1" == "weekly" ];
then
echo "$LOG_PREFIX Executing '$1' tasks" >> "$APPLICATION_LOG_PATH/task.log"
BASEDIR=`pwd`
cd "$APPLICATION_CRON_PATH"
for i in `ls | grep -P "\.$1\."`
do
echo "$LOG_PREFIX Executing '$i' task" >> "$APPLICATION_LOG_PATH/task.log"
RESULT=`./$i`
if [[ "$RESULT" = "" ]]; then
echo "$LOG_PREFIX Execution of task '$i' completed" >> "$APPLICATION_LOG_PATH/task.log"
else
echo "$LOG_PREFIX Task '$i' returned message '$RESULT'" >> "$APPLICATION_LOG_PATH/task.log"
fi
done
cd "$BASEDIR"
else
echo "$LOG_PREFIX ERROR!!! Invalid time specifier" >> "$APPLICATION_LOG_PATH/task.log"
exit 1
fi
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/php
<?php
/*
Author: Riccardo Di Dato
Creation Date: 04/mar/2016
*/
require_once(dirname(__FILE__)."/../load.php");
$pdo = new PDO("mysql:host=localhost;dbname=fdn_old","root","root",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$admin = GlobalVariables::get("dao")->getFirst("AdminModel",array("username"=>"antonio.pianelli"));
if (is_null($admin)){
$statement = $pdo->query("select * from admin where id = 2;");
$data = reset($statement->fetchALL(PDO::FETCH_CLASS,"stdClass"));
$admin = new stdClass();
$admin->username = $data->username;
$admin->password = $data->password;
$admin->nome = $data->nome;
$admin->cognome = $data->cognome;
$admin->roles = 1022;
$admin->active = true;
$admin->activationSent = true;
$admin->email = "info@ifattidinapoli.it";
$admin = new AdminModel($admin);
GlobalVariables::get("dao")->save($admin);
}
else {
$admin->email = "info@ifattidinapoli.it";
GlobalVariables::get("dao")->save($admin);
}
$count = 0;
$imgDir = "/home/r.didato/mediaimg/notizie";
$statement = $pdo->query("select * from notizia order by id desc limit $count,100");
$dati = $statement->fetchALL(PDO::FETCH_CLASS,"stdClass");
while (is_array($dati) && sizeof($dati)>0){
foreach ($dati as $ele){
$notizia = new stdClass();
$notizia->status = NotiziaModel::STATUS_ACCEPTED;
$notizia->about = new stdClass();
$notizia->about->owner = $admin->id;
$notizia->about->author = $admin->nome." ".$admin->cognome;
$notizia->isAnsa = $ele->primaPagina==1;
// $notizia->about->data = new MongoDate(strtotime($ele->data));
$notizia->about->data = new MongoDB\BSON\UTCDateTime(strtotime($ele->data)*1000) ; //New version
$notizia->titolo = $ele->mainTitle;
$notizia->sottotitolo = $ele->secTitle;
$corpo = $ele->corpo;
$corpo = preg_replace("~link[(]([^,]+),([^)]+)[)];~", '<a href="$2" target="_blank">$1</a>', $corpo);
$corpo = preg_replace("~mail[(]([^,]+),([^)]+)[)];~", '<a href="mailto:$2" target="_blank">$1</a>', $corpo);
$notizia->testo = $corpo;
switch ($ele->menu){
case 1://POLITICA
$notizia->category = NotiziaModel::CATEGORY_POLITICA;
break;
case 2://CRONACA
$notizia->category = NotiziaModel::CATEGORY_CRONACA;
break;
case 3://SPORT
$notizia->category = NotiziaModel::CATEGORY_SPORT;
break;
case 4://CULTURA
$notizia->category = NotiziaModel::CATEGORY_CULTURA;
break;
case 5://SPETTACOLO
$notizia->category = NotiziaModel::CATEGORY_CULTURA;
break;
case 4://FISCO E LAVORO
$notizia->category = NotiziaModel::CATEGORY_FISCOELAVORO;
break;
}
$notizia = new NotiziaModel($notizia);
GlobalVariables::get("dao")->save($notizia);
if (preg_match("/^http/",$ele->img)){
$media = new stdClass();
$media->mediaType = MediaModel::TYPE_YOUTUBE;
$matches = array();
if ( preg_match("~^http[s]?[:]//youtu\.be/(.+)$~", trim($ele->img), $matches) ){
$media->link = $matches[1];
}
else if (preg_match("~http[s]?[:]//www\.youtube\.com/embed/([^\"]++)~", trim($ele->img), $matches)){
$media->link = $matches[1];
}
else if (preg_match("~http[s]?[:]//www\.youtube\.com/watch[?]v[=](.+)$~", trim($ele->img), $matches)){
$media->link = $matches[1];
}
// LEGACY FORMAT http://www.youtube.com/v/c0B1snrcoPk&amp;hl=it_IT&amp;fs=1&amp;
else if (preg_match("~http[:]//www\.youtube\.com/v/([^&]++)~", trim($ele->img), $matches)){
$media->link = $matches[1];
}
// $media->link = $ele->img;
$media = new MediaModel($media);
GlobalVariables::get("dao")->save($media);
DaoMediaHandler::addMedia($notizia, $media);
}
$curDir = $imgDir."/".$ele->id;
if (is_dir($curDir) && is_dir($curDir."/big")){
$i=0;
$continue = true;
$curFile = $curDir."/big/".$i++.".jpg";
while(file_exists($curFile)){
$media = new stdClass();
$media->mediaType = MediaModel::TYPE_IMAGE;
$media = DaoMediaHandler::createNewFileBasedMedia($media, $curFile, "jpg");
DaoMediaHandler::addMedia($notizia, $media);
$curFile = $curDir."/big/".$i++.".jpg";
}
}
// $statement = $pdo->query("select * from commenti where notizia = ".$ele->id);
// $commenti = $statement->fetchALL(PDO::FETCH_CLASS,"stdClass");
// if (sizeof($commenti)>0){
// foreach ($commenti as $commento){
// $comm = new stdClass();
// $comm->notizia = $notizia->id;
// $comm->status = CommentoModel::STATUS_ACCEPTED;
// $comm->date = new MongoDate(strtotime($commento->data));
// $comm->titolo = $commento->titolo;
// $comm->testo = $commento->testo;
// }
// }
}
$count+=100;
$statement = $pdo->query("select * from notizia order by id desc limit $count,100");
$dati = $statement->fetchALL(PDO::FETCH_CLASS,"stdClass");
}
?>
@@ -0,0 +1,24 @@
#!/usr/bin/php
<?php
/*
* regenerateAutoUrlsForIndexing.php
* Author: Riccardo Di Dato
* Creation Date: 27 lug 2017
*/
require_once(dirname(__FILE__)."/../load.php");
$options = ['limit'=>100, 'skip'=>0, 'sort'=> [ 'creationDate' => 1 ] ];
$notizie = GlobalVariables::get("dao")->query("NotiziaModel", [], $options);
while (sizeof($notizie)>0 ){
foreach ($notizie as $notizia){
$notizia->buildAutoShortenedUrl();
GlobalVariables::get("dao")->save($notizia);
}
$options['skip']+=$options['limit'];
$notizie = GlobalVariables::get("dao")->query("NotiziaModel", [], $options);
}
?>
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/php
<?php
/*
Author: Riccardo Di Dato
Creation Date: 19/apr/2016
*/
require_once(dirname(__FILE__)."/../load.php");
$pdo = new PDO("mysql:host=localhost;dbname=fdn_old","root","root",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$count = 0;
$statement = $pdo->query("select * from notizia order by id desc limit $count,100");
$dati = $statement->fetchALL(PDO::FETCH_CLASS,"stdClass");
while (is_array($dati) && sizeof($dati)>0){
foreach ($dati as $ele){
$notizia = GlobalVariables::get("dao")->getFirst("NotiziaModel",array("titolo"=>$ele->mainTitle));
if (is_null($notizia)){
$notizia = GlobalVariables::get("dao")->getFirst("NotiziaModel",array("titolo"=>htmlspecialchars_decode($ele->mainTitle)));
}
if (!is_null($notizia)){
$notizia->oldId = intval($ele->id);
GlobalVariables::get("dao")->save($notizia);
}
else {
echo "Failed id ". $ele->id."\n";
}
}
$count+=100;
$statement = $pdo->query("select * from notizia order by id desc limit $count,100");
$dati = $statement->fetchALL(PDO::FETCH_CLASS,"stdClass");
}
?>
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/php
<?php
/**
* Script per aggiungere a tutte le notizie il campo 'about.lastEdit'
*/
require_once(dirname(__FILE__)."/../load.php");
$skip = 0;
$n=1;
$limit = 100;
$allNotizie = GlobalVariables::get("dao")->query("NotiziaModel",array("deleted"=>array('$exists'=>true)),array("skip"=>$skip,"limit"=>$limit));
while(sizeof($allNotizie)>0){
foreach ($allNotizie as $notizia){
if(property_exists($notizia->about, "data")){
$notizia->about->lastEdit = $notizia->about->data;
GlobalVariables::get("dao")->save($notizia);
echo $n.") last Edit: ".$notizia->about->lastEdit.PHP_EOL;
$n++;
}
}
$skip += $limit;
$allNotizie = GlobalVariables::get("dao")->query("NotiziaModel",array("deleted"=>array('$exists'=>true)),array("skip"=>$skip,"limit"=>$limit));
}
echo "totale notizie: ".sizeof(GlobalVariables::get("dao")->query("NotiziaModel",array("deleted"=>array('$exists'=>true)),array()))."\n";
?>
+1
View File
@@ -0,0 +1 @@
/config.local.php
+105
View File
@@ -0,0 +1,105 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
$project = new stdClass();
$project->name = "I Fatti di Napoli 2.0";
$project->buildName = "fdn2";
$project->defaultLocale = "it";
if (file_exists(dirname(__FILE__)."/config.local.php") ){
require_once (dirname(__FILE__)."/config.local.php");
}
else if (file_exists(dirname(__FILE__)."/config.test.php") ){
require_once (dirname(__FILE__)."/config.test.php");
}
else{
require_once (dirname(__FILE__)."/config.prod.php");
}
// Generic voices
$config = new stdClass();
$config->info = new stdClass();
$config->info->projectName = "I Fatti di Napoli";
$config->info->projectDescription = "Giornale quotidiano di Napoli con ultime notizie di politica, cultura, sport e spettacolo. Informazioni ed interviste su calcio e municipalit&agrave; Informazioni su tutti i paesi e quartieri di Napoli";
$config->info->owner = "Antonio Pianelli";
$config->info->author = "Antonio Pianelli";
$config->locale = new stdClass();
$config->locale->gui = $project->defaultLocale;
$config->locale->system = $project->defaultLocale;
// PATHS
$config->paths = new StdClass();
$config->paths->storage = $currentSystem->storageBaseDir . "/" . $project->buildName;
$config->paths->private = $currentSystem->privateBaseDir . "/" . $project->buildName;
$config->paths->public = $currentSystem->apache->workdir . "/" . $project->buildName;
$config->paths->log = $currentSystem->logBaseDir . "/" . $project->buildName;
$config->paths->tmp = $currentSystem->tmpBaseDir . "/" . $project->buildName;
$config->paths->backup = $config->paths->storage . "/backup";
$config->paths->binaries = $config->paths->private . "/bin";
$config->paths->common = $config->paths->private . "/common";
$config->paths->libraries = $config->paths->private . "/lib";
$config->paths->task = $config->paths->private . "/task";
$config->paths->cbsQueue = $config->paths->tmp . "/cbsQueue";
$config->paths->backupTmp = $config->paths->tmp . "/bak";
$config->paths->imageCache = $config->paths->tmp . "/imageCache";
$config->paths->pubImages = $config->paths->public . "/style/images";
$config->paths->media = $config->paths->storage . "/media";
// $config->paths->defMedia = $config->paths->pubImages . "/defaults";
$config->paths->xsendfile = $currentSystem->xSendFileDir . "/" . $project->buildName;
// FILES
$config->files = new StdClass();
$config->files->core_log = $config->paths->log . "/core.log";
$config->files->dao_log = $config->paths->log . "/dao.log";
$config->files->task_log = $config->paths->log . "/task.log";
$config->files->general_log = $config->paths->log . "/general.log";
$config->files->gui_log = $config->paths->log . "/gui.log";
$config->files->mail_log = $config->paths->log . "/mail.log";
$config->files->api_log = $config->paths->log . "/api.log";
$config->files->meteoCache = $config->paths->tmp . "/meteo.json";
// Pages
$config->pages = new StdClass();
$config->pages->remoteLocationPath = $currentSystem->remoteLocationPath;
// Emails
$config->emails = new StdClass();
$config->emails->newsletter = "newsletter@ifattidinapoli.it";
$config->emails->techSupport = "tecnicalSupport@ifattidinapoli.it";
$config->emails->info = "info@ifattidinapoli.it";
$config->emails->system = "system@ifattidinapoli.it";
$config->emails->postmaster = "postmaster@ifattidinapoli.it";
// $config->pages->index = $currentSystem->remoteLocation . "/index.php";
// $config->pages->login = $currentSystem->remoteLocation . "/login.php";
// $config->pages->logout = $currentSystem->remoteLocation . "/logout.php";
$config->api = new stdClass();
$config->api->account = $backupSystem->account;
$config->api->passphrase = $backupSystem->passphrase;
// CBS 2
$config->cbs2 = new stdClass();
$config->cbs2->keyFile = $config->paths->common . "/" . $cbs2->keyfile;
$config->cbs2->serverPort = $cbs2->serverPort;
$config->database = $database;
?>
+54
View File
@@ -0,0 +1,54 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 19/nov/2013
*/
// $dbconn = new DatabaseConnection();
// $dbconn->dbname = "cbs";
// $dbconn->dbtype = "mysql";
// $dbconn->location = "localhost";
// $dbconn->username = "root";
// $dbconn->password = "root";
// Password mongo produzione: p14n3ll1FDN2
$database = new stdClass();
$database->dbName = "fdn2";
$database->user = "fdn2";
$database->pass = "p14n3ll1FDN2";
$database->useAuth = true;
$database->connectionString = "mongodb://".$database->user.":".$database->pass."@localhost/".$database->dbName;
$currentSystem = new stdClass();
$currentSystem->storageBaseDir = "/home/ddninja/storage"; // Il path con storage ecc in cui mettere immagini, file temporanei ecc
$currentSystem->privateBaseDir = "/home/ddninja/private"; // Il path in cui inserire la cartella con lib, task, binari ecc
$currentSystem->tmpBaseDir = "/tmp/ddninja";
$currentSystem->logBaseDir = "/var/log/ddninja"; // Il path dei log....
$currentSystem->xSendFileDir = "/tmp/xsend";
// $currentSystem->safeStorage = "/home/cbs/storage";
$currentSystem->apache = new StdClass();
$currentSystem->apache->user = "var-www";
$currentSystem->apache->group = "var-www";
$currentSystem->apache->workdir = "/var/www"; // Il path in cui inserire la cartella con le pagine html
$currentSystem->remoteLocationPath = "http://www.ifattidinapoli.it/";
$backupSystem = new stdClass();
$backupSystem->account = "1582528f056a7ea7f391149fddc75553";
$backupSystem->passphrase = "232728b3e504a400a62a9f94893a9a962ecc6543ed7d3c293340414b259aac727f14d60a4f2cd52e228c9694a55774ff5652520b38d120a299394715247645b8293a880901162f268c8c8777a3ee9c6e410455cb4c8137f58f9d7162d45582ab363679ed456e56bf3b36d0384368b62eced40abd0fe117f04c9322f07ee33a7c";
$cbs2 = new stdClass();
$cbs2->keyfile = "id_rsa_cbs_prod";
$cbs2->serverPort = "22";
// $config->locations = new stdClass();
// $config->application->applicationInterfacePath = "/tnc15";
// $config->application->systemTmp = "/tmp";
?>
+50
View File
@@ -0,0 +1,50 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 14/nov/2013
*/
// $dbconn = new DatabaseConnection();
// $dbconn->dbname = "cbs";
// $dbconn->dbtype = "mysql";
// $dbconn->location = "localhost";
// $dbconn->username = "root";
// $dbconn->password = "root";
$database = new stdClass();
$database->dbName = "fdn2";
$database->user = "test";
$database->pass = "test";
$database->useAuth = false;
$database->connectionString = "mongodb://".$database->user.":".$database->pass."@localhost/".$database->dbname;
$currentSystem = new stdClass();
$currentSystem->storageBaseDir = "/home"; // Il path con storage ecc in cui mettere immagini, file temporanei ecc
$currentSystem->privateBaseDir = "/home/ddninja"; // Il path in cui inserire la cartella con lib, task, binari ecc
$currentSystem->tmpBaseDir = "/tmp/ddninja";
$currentSystem->logBaseDir = "/var/log"; // Il path dei log....
$currentSystem->xSendFileDir = "/tmp/xsend";
// $currentSystem->safeStorage = "/home/cbs/storage";
$currentSystem->apache = new StdClass();
$currentSystem->apache->user = "var-www";
$currentSystem->apache->group = "var-www";
$currentSystem->apache->workdir = "/var/www"; // Il path in cui inserire la cartella con le pagine html
$currentSystem->remoteLocationPath = "http://db.ifattidinapoli.it/";
$backupSystem = new stdClass();
$backupSystem->account = "40a911e14db8ad6faf0a0e7385e7c267";
$backupSystem->passphrase = "a54af48c2ec44bba903666b6d12290750178154a6965c9165d3b387e7fd0f14c5f2d62cb93f468be640d469c80f1260feed3ad98f5f52d52c045b0487e59981bf365f4037f6c7cb93572cdd5d20daeb8185afcc65dba1bd2067829f827d9b795451f6e5e8fafe5e1fbe29675feb93e7d208a6b53a14df5aeec62d97fbf34d56a";
$cbs2 = new stdClass();
$cbs2->keyfile = "id_rsa_cbs_test";
$cbs2->serverPort = "22";
// $config->locations = new stdClass();
// $config->application->applicationInterfacePath = "/tnc15";
// $config->application->systemTmp = "/tmp";
?>
+1
View File
@@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCiuXz8DfvkF0t6/QghqZ77sy/NmncDLWvbcrwxTn4TxFaEr1kJrfrxoDApitkokFS967Ti1d/9th1tvn8o1ivhclUxiOGIrKsW1dJSelEsmmFdjkw7w270UdHsllAVBxmZMpBUU3fvOMl+FGFcOpJqUVf3A86ZPzYfHZPKdrfYd9Qp5q4qw1DF8O1EQM9s28MIgoHYuzyOH9GMpyyBQDo244r64g55oZr4eqVzXfXTTIW/I7+sbux4wa1Hemu+XHJxSIYzVrpyrCi/d+jSXxusL1i149N/Yy8qozTKbdHldovF/IKHyPf1EtfE1swMquw8pme3Aq3MigtsV7Ekvf5pQ6btbpU5HtpkFuSrAQThANiN4saEiLEW6xmVF9/AxHmxYXuaBGRWX5Bky6He5zcNnmK4zpiRKFseJlmBpkxPnSv5bAaXEA6SjRtmwdTjPHqCFspD6knEeNwA4xDr8OAr0KE+/yKkL+bXGwwKGhKHLSub0hYl9t89YkxPgQNMLx52EJ8UmrZMg3aykFMjQ7XnTSFk9FsXf5EV70ZGsVRnSpccZ2SDAbTgRdcJkjoQ28J4R/b9xXnYeMdoQtZclogxOYoVe8U+j8xZfsW0FW5Ek9cQKiMWd6ODmWJ26EDgaEcJMlq2Q8nkTAXb7HCbzW41PUL9VupH/to61haHuwQxrw== fdn2@cbs.asdynamics.com
+51
View File
@@ -0,0 +1,51 @@
-----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEAorl8/A375BdLev0IIame+7MvzZp3Ay1r23K8MU5+E8RWhK9Z
Ca368aAwKYrZKJBUveu04tXf/bYdbb5/KNYr4XJVMYjhiKyrFtXSUnpRLJphXY5M
O8Nu9FHR7JZQFQcZmTKQVFN37zjJfhRhXDqSalFX9wPOmT82Hx2Tyna32HfUKeau
KsNQxfDtREDPbNvDCIKB2Ls8jh/RjKcsgUA6NuOK+uIOeaGa+Hqlc13100yFvyO/
rG7seMGtR3prvlxycUiGM1a6cqwov3fo0l8brC9YtePTf2MvKqM0ym3R5XaLxfyC
h8j39RLXxNbMDKrsPKZntwKtzIoLbFexJL3+aUOm7W6VOR7aZBbkqwEE4QDYjeLG
hIixFusZlRffwMR5sWF7mgRkVl+QZMuh3uc3DZ5iuM6YkShbHiZZgaZMT50r+WwG
lxAOko0bZsHU4zx6ghbKQ+pJxHjcAOMQ6/DgK9ChPv8ipC/m1xsMChoShy0rm9IW
JfbfPWJMT4EDTC8edhCfFJq2TIN2spBTI0O1500hZPRbF3+RFe9GRrFUZ0qXHGdk
gwG04EXXCZI6ENvCeEf2/cV52HjHaELWXJaIMTmKFXvFPo/MWX7FtBVuRJPXECoj
Fnejg5liduhA4GhHCTJatkPJ5EwF2+xwm81uNT1C/VbqR/7aOtYWh7sEMa8CAwEA
AQKCAgBN48+prt/lnCjrI/ciddi9zlWRauCQyssX7eGbEGFVAOQQ+wX5lifKRM0I
9Ydg3UVS62JYOdvPy75ma4redzXl4h5ZaZXbIBt9ALh99kKowPTeHWDsMm4H0KpV
PtXyWsWsCQIA+zsrbNk12neH+BlhfrJGcLIRtKopVrUJcq4plaIetGal3XvqY5qO
0x72knLWvfF9VpJzzVM2qkapT58N6vj5gf8/xVUynzJW+KDUlYpnpar31NioLLzO
vBCavBGjm/1w0ZDJlxKiI7l0CUZrsvYZioYQMd+/3wND6jFQTuA00tuAN3hI/M3/
UHm3jpEprtVySnv6rhEtuQP3/GGsKaXnFMFKWfdUm0dR34i32aflz/HNda0yoTMM
OgZQA8Gr3xT9gox7gjBSPP03vmvHXuLAXd/KmYUAyOA30oGIQ7pXaHu4M9VHfa44
HVx5pYePkGbUCkMcrPJGrrJBEubibHcG6ClNebuWDoJnvKjfO58lIq2yCsQL6yYV
o85h+RhXqF2pqPvB4lFh8EcVoGIvB//3wmfZr7sSpJui82P6j2nrHUY44iulLplk
X722dkplKznXSpWSSecw6IJEMO9WfOoXSxWGq6519VAoDvgMWREkHm2baOK8yTc5
ChLFeQJrP0FlR2CGL7K8w4+dZh5/FdwgEtCLf5SaSn8jvb9+oQKCAQEA1x2bWRSc
GxPDvXzPnEacMCao5e+Z5o+GrGMvtJLJTz9KyMsesAg0FdaMU34kwA5ZQs4vOdGi
8Cm5nwKRbAL5VFCuRyWie4MNkCxbWv2Id1bjVwWz07/J4Ca+yHou3IgIguDT3b7x
nZMhdcVBCv6WHh/seGRAW23r9hRX1pQCXPHf34mEyX5lW1ppiD1ZgXsq8ZZax7nl
djjyqbBe3u/WLFseiRRZ6SBYGQnKvywkypRSoHOCco3hG8yh5xPvl4Chjdgr9SGn
mUPiPbV4x/zCFVZLoljkFg3nTupd6OJ8e0NLbxNacnl4WdQV/tlVd3gDTKK51RAt
Bpc9V5okj1CI2QKCAQEAwabOrPYV0KCgKiwgvGJJblxoYChuGxlzAp637rJauUIK
zJWL9vgmJpI68QUNrBFEz/dzZTcm8RWLyE5+m+ja+6bcM4atMcXGm7XCI4LNR8w+
PcxDTbpyEXIIoOfbgmIM6ontO/3SonGcqClfUhaaVuvzO3HYnJWccS4m4l4i7nkH
libDpgVEYivi6WzhJsljkW2QvZlPvqbWDugm/koknm84UljLEM6TaxykBhL65zYN
D6sGKnyddAu+DacADtDsEEt+g4PUlR4/5OEusXnW1WsRJXCT5afHYSwJxoXocMLg
0txA9naNRbxakGBxjoxwevjXD4hIs3uX92pNKY25xwKCAQEAyI4c4K97Xy9NJiPw
N6YJRkc03rNFTBTyHVSYDIVx1EWRBqWBJeNwFBAkYk9QGhMGm2c51nEhtUFhguNV
C1u2cyqJYWGwG/EyOwFv5uRLT+AdMmvpnXjI0QeuhaCMgiT9sm/Ed4/nGd8rqe5O
1t5GvS1MPW5SJivUe2e6AR+bGGaVL4a521XRT5t6mn+ALFzVy8k/N8iUK2WqsBP0
T2tRxabqUCk+LkBugmGDujqAzrH8WwV2UDEA9/cP1y3aCejuNh2d1fwbkqQckSXY
xrNbi6MZ/vFbLUinKAcPqOlH32/9K0Di6algUHeQTjr4GNs2UEPCd+eN4wAsO7lF
bqxJ+QKCAQAwTYZB2EQKvPYWbtlfg/ijAYO7cHo+YjOw1Jw2euBsU0/URf0ahj0l
49W15rfJUqliYmuzNHWPLvul5AZqp0Nv/+fvJkmvH5Dxp/2b0/WWUhi4W2nySm5H
cbU7RXoYZJKqMestypsuj74up9sx45dt1P7ftf7818ik5okmb6qw5xmAV3z3vVqY
TjAUX2ctwJAIZ1byI/qjKIQ+RaPsS9wkdMOMrr9AGvbkgclcBoH1CCNr5BHuqRSx
LHikeSJnj69CRUJyVYDCDUCMu6pk9Gok48bsGs+ZOideUpjBnwcikUl47x15HIsS
eO/yEUxh7R/lXIpwQmM3+b0nJqnGkqZjAoIBAH9YJIPturTnQsFEWWOPSz8dZDpM
BawUp/Ki6tSrAtsughC4/Y+q0ZIeDXwgA4hmV3cospgMa4gKEZbZydouBJbPr92L
xi4dFoIPXDIk0L/ZCP+wB+nkO6hHP87YK2KoA6kAUZVGs9kObmPLcyIMSJAqG3sH
zP/Vv+yHiSZGhmCbzxvHoTF+Q01cwitIkEqZ6XYHr4WmnlO3RH8BeX6bk57sK1D2
G7Fs3k0z47TUdlZfhqDBkPl0m96kmgdYLSKQV8szkNbICaTwjOcIDF/Lu0oMDIqU
Z/wMNHq+cMznB9kUuJRs4Nn5VwOGgQQD8f3ZURBuKH2j8HtqxwRjGsN41hk=
-----END RSA PRIVATE KEY-----
+352
View File
@@ -0,0 +1,352 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 27/gen/2016
*/
class AnalyticsHelper {
private static $COOKIE_NAME = "FDN_STAT_NUM";
private static $COOKIE_TIME = "+1 year";
/**
* La funzione si occupa del salvataggio vero e proprio della impression della pagina.
* UTILIZZARE QUESTA FUNZIONE SOLO NELLA PAGINA DI BACKEND (stats/pageImpression.php). Nelle pagine base utilizzare invece la funzione di log
* @param string $ip
* @param string $content
* @param string $source
*/
public static function savePageImpression($ip, $content, $source){
$tmp = new stdClass();
$tmp->user = null;
if (isset($_COOKIE[self::$COOKIE_NAME])){
$id = $_COOKIE[self::$COOKIE_NAME];
$tmp->user = new stdClass();
$tmp->user->id = $id;
$tmp->user->isNew = false;
if (GlobalVariables::get("dao")->count("StatisticModel",array("user.id"=>$id))==0){
$tmp->user->isNew = true;
}
}
$tmp->content = $content;
$tmp->source = $source;
$tmp->ip = $ip;
$tmp->statType = StatisticModel::STAT_TYPE_PAGE;
$stat = new StatisticModel($tmp);
GlobalVariables::get("dao")->save($stat);
}
/**
* La funzione si occupa di aggiungere una visualizzazione alla pagina corrente
*/
public static function logPageImpression(){
if (!isset($_COOKIE[self::$COOKIE_NAME])){
self::prepareStatCookie();
}
$ip = $_SERVER['REMOTE_ADDR'];
$content = $_SERVER['PHP_SELF'];
$source = null;
if (array_key_exists("HTTP_REFERER",$_SERVER)){
$source = $_SERVER['HTTP_REFERER'];
}
$function = '$.ajax({url: "stats/pageImpression.php", method: "POST", data: { "ip": "'.$ip.'", "content": "'.$content.'", "source": "'.$source.'" }, dataType: "html" });';
GUIHandler::addOnLoadJsEvent($function);
}
private static function prepareStatCookie(){
setcookie(self::$COOKIE_NAME, uniqid("",true), strtotime(self::$COOKIE_TIME) );
}
/**
* La funzione si occupa del salvataggio vero e proprio della impression della notizia.
* UTILIZZARE QUESTA FUNZIONE SOLO NELLA PAGINA DI BACKEND (stats/notiziaImpression.php). Nelle pagine base utilizzare invece la funzione di log
* @param string $ip
* @param string $content
* @param string $source
*/
public static function saveNotiziaImpression($ip, $notiziaId, $source){
$tmp = new stdClass();
$tmp->user = null;
if (isset($_COOKIE[self::$COOKIE_NAME])){
$id = $_COOKIE[self::$COOKIE_NAME];
$tmp->user = new stdClass();
$tmp->user->id = $id;
$tmp->user->isNew = false;
if (GlobalVariables::get("dao")->count("StatisticModel",array("user.id"=>$id))==0){
$tmp->user->isNew = true;
}
}
$tmp->content = new stdClass();
$notizia = GlobalVariables::get("dao")->getFirst("NotiziaModel",array("id"=>$notiziaId));
if (!is_null($notizia)){
$tmp->content->notizia = $notiziaId;
$tmp->content->category = $notizia->category;
$tmp->source = $source;
$tmp->ip = $ip;
$tmp->statType = StatisticModel::STAT_TYPE_NOTIZIA;
$stat = new StatisticModel($tmp);
GlobalVariables::get("dao")->save($stat);
}
}
/**
* La funzione si occupa di aggiungere una visualizzazione alla notizia correlata a $id
* @param string $id
*/
public static function logNotiziaImpression($id){
if (!isset($_COOKIE[self::$COOKIE_NAME])){
self::prepareStatCookie();
}
$ip = $_SERVER['REMOTE_ADDR'];
$notizia = $id;
$source = null;
if (array_key_exists("HTTP_REFERER",$_SERVER)){
$source = $_SERVER['HTTP_REFERER'];
}
$function = '$.ajax({url: "stats/notiziaImpression.php", method: "POST", data: { "ip": "'.$ip.'", "notizia": "'.$id.'", "source": "'.$source.'" }, dataType: "html" });';
GUIHandler::addOnLoadJsEvent($function);
}
/**
* Restitusce il numero di impressions per una notizia
* @param string $id
*/
public static function countNotiziaImpressions($id, $start = null, $end = null){
$searchArray = array("statType"=>StatisticModel::STAT_TYPE_NOTIZIA,"content.notizia"=>$id);
if (!is_null($start)){
// $searchArray["date"]['$gte'] = new MongoDate($start);
$searchArray["date"]['$gte'] = new MongoDB\BSON\UTCDateTime( $start * 1000 );
}
if (!is_null($end)){
// $searchArray["date"]['$lte'] = new MongoDate($end);
$searchArray["date"]['$lte'] = new MongoDB\BSON\UTCDateTime( $end * 1000 );
}
return GlobalVariables::get("dao")->count("StatisticModel",$searchArray);
}
/**
* La funzione si occupa del salvataggio vero e proprio della impression del banner.
* UTILIZZARE QUESTA FUNZIONE SOLO NELLA PAGINA DI BACKEND (stats/bannerImpression.php). Nelle pagine base utilizzare invece la funzione di log
* @param string $ip
* @param string $content
* @param string $source
*/
public static function saveBannerImpression($ip, $bannerId, $source){
$tmp = new stdClass();
$tmp->user = null;
if (isset($_COOKIE[self::$COOKIE_NAME])){
$id = $_COOKIE[self::$COOKIE_NAME];
$tmp->user = new stdClass();
$tmp->user->id = $id;
$tmp->user->isNew = false;
if (GlobalVariables::get("dao")->count("StatisticModel",array("user.id"=>$id))==0){
$tmp->user->isNew = true;
}
}
$tmp->content = new stdClass();
$banner = GlobalVariables::get("dao")->getFirst("BannerModel",array("id"=>$bannerId));
if (!is_null($banner)){
$tmp->content->banner = $bannerId;
$tmp->content->position = $banner->position;
$tmp->source = $source;
$tmp->ip = $ip;
$tmp->statType = StatisticModel::STAT_TYPE_BANNER_IMPRESSION;
$stat = new StatisticModel($tmp);
GlobalVariables::get("dao")->save($stat);
}
}
/**
* La funzione si occupa di aggiungere una visualizzazione all banner $id
* @param string $id
*/
public static function logBannerImpression($id){
if (!isset($_COOKIE[self::$COOKIE_NAME])){
self::prepareStatCookie();
}
$ip = $_SERVER['REMOTE_ADDR'];
$source = null;
if (array_key_exists("HTTP_REFERER",$_SERVER)){
$source = $_SERVER['HTTP_REFERER'];
}
$function = '$.ajax({url: "stats/bannerImpression.php", method: "POST", data: { "ip": "'.$ip.'", "banner": "'.$id.'", "source": "'.$source.'" }, dataType: "html" });';
echo '<script type="text/javascript">'.$function.'</script>';
// OLD VERSION
// $function = '$.ajax({url: "stats/bannerImpression.php", method: "POST", data: { "ip": "'.$ip.'", "banner": "'.$id.'", "source": "'.$source.'" }, dataType: "html" });';
// GUIHandler::addOnLoadJsEvent($function);
}
/**
* Restitusce il numero di impressions per una notizia
* @param string $id
*/
public static function countBannerImpressions($id, $start = null, $end = null){
$searchArray = array("statType"=>StatisticModel::STAT_TYPE_BANNER_IMPRESSION,"content.banner"=>$id);
if (!is_null($start)){
// $searchArray["date"]['$gte'] = new MongoDate($start);
$searchArray["date"]['$gte'] = new MongoDB\BSON\UTCDateTime($start * 1000);
}
if (!is_null($end)){
// $searchArray["date"]['$lte'] = new MongoDate($end);
$searchArray["date"]['$lte'] = new MongoDB\BSON\UTCDateTime($end * 1000);
}
return GlobalVariables::get("dao")->count("StatisticModel",$searchArray);
}
/**
* La funzione si occupa del salvataggio vero e proprio della impression dell banner.
* UTILIZZARE QUESTA FUNZIONE SOLO NELLA PAGINA DI BACKEND (stats/bannerImpression.php). Nelle pagine base utilizzare invece la funzione di log
* @param string $ip
* @param string $content
* @param string $source
*/
public static function saveBannerClick($bannerId, $source){
$tmp = new stdClass();
$tmp->user = null;
if (isset($_COOKIE[self::$COOKIE_NAME])){
$id = $_COOKIE[self::$COOKIE_NAME];
$tmp->user = new stdClass();
$tmp->user->id = $id;
$tmp->user->isNew = false;
if (GlobalVariables::get("dao")->count("StatisticModel",array("user.id"=>$id))==0){
$tmp->user->isNew = true;
}
}
$tmp->content = new stdClass();
$banner = GlobalVariables::get("dao")->getFirst("BannerModel",array("id"=>$bannerId));
if (!is_null($banner)){
$tmp->content->banner = $bannerId;
$tmp->content->position = $banner->position;
$tmp->source = $source;
$tmp->ip = $_SERVER['REMOTE_ADDR'];
$tmp->statType = StatisticModel::STAT_TYPE_BANNER_CLICK;
$stat = new StatisticModel($tmp);
GlobalVariables::get("dao")->save($stat);
}
}
/**
* La funzione si occupa di aggiungere una visualizzazione all banner $id
* @param string $id
*/
public static function getBannerClickLink($banner){
if (!isset($_COOKIE[self::$COOKIE_NAME])){
self::prepareStatCookie();
}
return "bannerClick('".$banner->id."','".$banner->link."');";
}
/**
* Restitusce il numero di impressions per una notizia
* @param string $id
*/
public static function countBannerClicks($id, $start = null, $end = null){
$searchArray = array("statType"=>StatisticModel::STAT_TYPE_BANNER_CLICK,"content.banner"=>$id);
if (!is_null($start)){
// $searchArray["date"]['$gte'] = new MongoDate($start);
$searchArray["date"]['$gte'] = new MongoDB\BSON\UTCDateTime($start * 1000);
}
if (!is_null($end)){
// $searchArray["date"]['$lte'] = new MongoDate($end);
$searchArray["date"]['$lte'] = new MongoDB\BSON\UTCDateTime($end * 1000);
}
return GlobalVariables::get("dao")->count("StatisticModel",$searchArray);
}
/**
* Restituisce il banner da mostrare tenendo in considerazione quelli già visualizzati e le visualizzazioni totali
* @param int $position
* @param string $replaced id del banner rimpiazzato
*/
public static function getBannerToShow($position, $replaced = null, $category = BannerModel::GENERAL_CATEGORY){
// Rimuovi il replaced dalla lista
$shown = array();
$rval = null;
if (ASDSessionHandler::sessionValueExists("bannerActive")){
$shown = ASDSessionHandler::getSessionValue("bannerActive");
if (!is_null($replaced) && in_array($replaced, $shown)){
$key = array_search($replaced, $shown);
unset($shown[$key]);
ASDSessionHandler::setSessionValue("bannerActive",$shown);
}
}
// idlist contiene gli id dei banner in ordine di visualizzazione crescente (esclusi quelli non visualizzati)
$pipeline = PipelineHelper::getTodaysBannerVisualizationPipeline($position);
$stats = GlobalVariables::get("dao")->aggregate("StatisticModel",$pipeline);
// var_dump($stats);
$idList = array();
if (sizeof($stats)>0){
foreach ($stats as $stat){
$idList[] = $stat["_id"]["banner"];
}
}
// $baseSearchArray = array("position"=>$position,"end"=>array('$gte'=>new MongoDate(strtotime("tomorrow"))),"categories"=>$category);
$baseSearchArray = array("position"=>$position,"end"=>array('$gte'=>new MongoDB\BSON\UTCDateTime( strtotime("tomorrow") * 1000 ) ),"categories"=>$category);
// Prendi il primo dei "mai mostrati oggi" tra quelli non presenti nella pagina
$todayPlusShown = array_merge($idList,$shown);
if (sizeof($todayPlusShown)>0){
$tmp = array_map(function ($id) {return new MongoDB\BSON\ObjectID($id);}, $todayPlusShown);
$tmp = array('_id'=>array('$nin'=>$tmp));
$rval = GlobalVariables::get("dao")->getFirst("BannerModel", array_merge($baseSearchArray, $tmp) );
}
else {
$rval = GlobalVariables::get("dao")->getFirst("BannerModel", $baseSearchArray);
}
if (is_null($rval)){
$todayLessShown = array_values(array_diff($idList, $shown));
if (sizeof($todayLessShown)>0){
$i = 0;
while (is_null($rval) && $i<sizeof($todayLessShown)){
$condition = array_merge($baseSearchArray, array("id"=>$todayLessShown[$i]) );
$rval = GlobalVariables::get("dao")->getFirst("BannerModel", $condition );
$i++;
}
}
}
if (!is_null($rval)){
$shown[] = $rval->id;
ASDSessionHandler::setSessionValue("bannerActive",$shown);
}
return $rval;
}
}
?>
+27
View File
@@ -0,0 +1,27 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 11/mar/2016
*/
class BannerHelper{
private static $INTERNAL_COUNT = 1;
public static function printBanner($position = BannerModel::POSITION_HEAD, $category = null){
if (is_null($category)){
$category = BannerModel::GENERAL_CATEGORY;
}
$cur = self::getPlaceholderId();
?>
<div id="<?php echo $cur;?>"><script type="text/javascript">$(document).ready(function () {bannerRoll('<?php echo $cur;?>',<?php echo $position;?>,<?php echo $category;?>);});</script></div>
<?php
}
private static function getPlaceholderId(){
return 'banPlaceholder_'.(self::$INTERNAL_COUNT++);
}
}
?>
+27
View File
@@ -0,0 +1,27 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 12/gen/2016
*/
class CataloguedException extends CoreException {
protected $data;
public function __construct($msg,$exceptiondata = null) {
parent::__construct($msg);
if(!is_array($exceptiondata)) {
$this->data = array($exceptiondata);
}
else {
$this->data = $exceptiondata;
}
}
public function getData() {
return $this->data;
}
}
?>
+11
View File
@@ -0,0 +1,11 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 22/dic/2015
*/
class CoreException extends Exception {
}
?>
+124
View File
@@ -0,0 +1,124 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 26/gen/2016
*/
class FDN_MailHelper {
public static function generateMailFooter(){
$footer = '<div style="background-color:#14477c;height:177px;margin-top:10px;">'.
'<div style="text-align:center;color:#2e91d4;padding:10px;">'.
'<a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/index.php">Home</a> | <a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/categorySummary.php?category=1>">Politica</a> | <a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/categorySummary.php?category=2>">Cronaca</a> | <a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/categorySummary.php?category=3>">Sport</a> | <a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/categorySummary.php?category=4>">Cultura&Spettacolo</a> | <a style="color:#2e91d4;margin:10px;" href="http://www.ifattidinapoli.it/categorySummary.php?category=5>">Gossip</a>'.
'</div>'.
'<div style="text-align:center;color:white;margin-top:25px;">TESTATA REGISTRATA PRESSO IL TRIBUNALE DI NAPOLI AUT. NR. 8 DEL 27 GENNAIO 2006</div>'.
'<div style="text-align:center;color:white;margin-top:20px;">COPYRIGHT &copy 2016 <a href="http://www.ifattidinapoli.it" style="color:white;">www.ifattidinapoli.it</a> - Giornale della Terza Metropoli Italiana</div>'.
'<div style="text-align:center;color:white;margin-top:20px;"><a href="http://www.ifattidinapoli.it/redazione.php" style="color:white;">REDAZIONE</a> | <a href="http://www.ifattidinapoli.it/archivio.php" style="color:white;">ARCHIVIO STORICO</a></div>'.
'</div>';
return $footer;
}
public static function getAdminConfirmMail($admin){
$config = GlobalVariables::get("config");
$tmp = new stdClass();
$tmp->from = $config->emails->postmaster;
$tmp->fromName = "I Fatti di Napoli - Automailer";
$tmp->recipient = $admin->email;
$tmp->subject = "Attivazione account I Fatti di Napoli";
$confirmLink = GUIHandler::getBaseUrl()."admin/confirmAdmin.php?regcode=".$admin->id."&email=".$admin->email;
$mailHead = '<div style="width:1024px; margin:auto;"><div style="text-align:center;"><img src="http://www.ifattidinapoli.it/images/logo_uff.png" alt="" /><div><br/><br/>';
$tmp->body = $mailHead."Per attivare il tuo account clicka sul link riportato in seguito o copialo e incollalo nel tuo browser.<br/><br/>";
$tmp->body.='<a href="'.$confirmLink.'">'.$confirmLink.'</a><br/>'.self::generateMailFooter().'</div>';
return new MailModel($tmp);
}
public static function getAdminPasswordResetMail(PasswordRecoveryRequestModel $request){
$config = GlobalVariables::get("config");
$user = GlobalVariables::get("dao")->getFirst($request->target->class,array("id"=>$request->target->id));
$tmp = new stdClass();
$tmp->from = $config->emails->postmaster;
$tmp->fromName = "I Fatti di Napoli - Automailer";
$tmp->recipient = $user->email;
$tmp->subject = "I Fatti di Napoli - Recupero password";
$confirmLink = GUIHandler::getBaseUrl()."admin/passwordRecovery.php?req=".$request->id."&u=".$request->target->id;
$mailHead = '<div style="width:1024px; margin:auto;"><div style="text-align:center;"><img src="http://www.ifattidinapoli.it/images/logo_uff.png" alt="" /><div><br/><br/>';
$tmp->body = $mailHead."Hai ricevuto questo messaggio perchè hai effettuato una richiesta di recupero password dal nostro sito.<br/><br/>";
$tmp->body.= "Se non hai effettuato nessuna richiesta, semplicemente ignora questo messaggio.<br/><br/>";
$tmp->body.= "Clicka sul seguente link per generare una nuova password.<br/><br/>";
$tmp->body.='<a href="'.$confirmLink.'">'.$confirmLink.'</a><br/>'.self::generateMailFooter().'</div>';
return new MailModel($tmp);
}
public static function getUserConfirmMail($user){
$config = GlobalVariables::get("config");
$tmp = new stdClass();
$tmp->from = $config->emails->postmaster;
$tmp->fromName = "I Fatti di Napoli - Automailer";
$tmp->recipient = $user->email;
$tmp->subject = "Attivazione account I Fatti di Napoli";
$confirmLink = GUIHandler::getBaseUrl()."confirmUser.php?regcode=".$user->id."&email=".$user->email;
$mailHead = '<div style="width:1024px; margin:auto;"><div style="text-align:center;"><img src="http://www.ifattidinapoli.it/images/logo_uff.png" alt="" /><div><br/><br/>';
$tmp->body = $mailHead."Per attivare il tuo account clicka sul link riportato in seguito o copialo e incollalo nel tuo browser.<br/><br/>";
$tmp->body.='<a href="'.$confirmLink.'">'.$confirmLink.'</a><br/>'.self::generateMailFooter().'</div>';
return new MailModel($tmp);
}
public static function getUserPasswordResetMail(PasswordRecoveryRequestModel $request){
$config = GlobalVariables::get("config");
$user = GlobalVariables::get("dao")->getFirst($request->target->class,array("id"=>$request->target->id));
$tmp = new stdClass();
$tmp->from = $config->emails->postmaster;
$tmp->fromName = "I Fatti di Napoli - Automailer";
$tmp->recipient = $user->email;
$tmp->subject = "I Fatti di Napoli - Recupero password";
$confirmLink = GUIHandler::getBaseUrl()."passwordRecovery.php?req=".$request->id."&u=".$request->target->id;
$mailHead = '<div style="width:1024px; margin:auto;"><div style="text-align:center;"><img src="http://www.ifattidinapoli.it/images/logo_uff.png" alt="" /><div><br/><br/>';
$tmp->body = $mailHead."Hai ricevuto questo messaggio perchè hai effettuato una richiesta di recupero password dal nostro sito.<br/><br/>";
$tmp->body.= "Se non hai effettuato nessuna richiesta, semplicemente ignora questo messaggio.<br/><br/>";
$tmp->body.= "Clicka sul seguente link per generare una nuova password.<br/><br/>";
$tmp->body.='<a href="'.$confirmLink.'">'.$confirmLink.'</a><br/>'.self::generateMailFooter().'</div>';
return new MailModel($tmp);
}
public static function getNewCommentoMail(CommentoModel $commento, AdminModel $admin){
$config = GlobalVariables::get("config");
$tmp = new stdClass();
$tmp->from = $config->emails->postmaster;
$tmp->fromName = "I Fatti di Napoli - Automailer";
$tmp->recipient = $admin->email;
$tmp->subject = "I Fatti di Napoli - Nuovo commento";
$confirmLink = GUIHandler::getBaseUrl()."/admin/validateCommento.php?i=".$commento->id;
$mailHead = '<div style="width:1024px; margin:auto;"><div style="text-align:center;"><img src="http://www.ifattidinapoli.it/images/logo_uff.png" alt="" /><div><br/><br/>';
$tmp->body = $mailHead."Un nuovo commento è stato inserito su I Fatti di Napoli ed è in attesa di essere accettato.<br/><br/>";
$tmp->body.= "Verifica i contenuti del commento utilizzando il link di seguito.<br/><br/>";
$tmp->body.='<a href="'.$confirmLink.'">'.$confirmLink.'</a>'.self::generateMailFooter().'</div>';
return new MailModel($tmp);
}
}
?>
+20
View File
@@ -0,0 +1,20 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 12/gen/2016
*/
class GlobalVariables {
private static $variables = array();
public static function set($name, $value){
self::$variables[$name] = clone $value;
}
public static function get($name){
return self::$variables[$name];
}
}
?>
+29
View File
@@ -0,0 +1,29 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 26/gen/2016
*/
class MultimessageException extends CoreException {
protected $messageList;
public function __construct(array $arr){
$this->messageList = $arr;
$this->message = $this->getMessageMerged("\n");
}
public function addMessage($msg){
$this->messageList[]=$msg;
$this->message = $this->getMessageMerged("\n");
}
public function getMessageList(){
return $this->messageList;
}
public function getMessageMerged($glue){
return implode($glue,$this->getMessageList());
}
}
?>
+283
View File
@@ -0,0 +1,283 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 05/feb/2016
*/
class PipelineHelper {
public static function getDailyVisualizationPipeline($startDate){
$rval = array(
array(
'$match'=>array(
'statType'=>StatisticModel::STAT_TYPE_PAGE,
'date'=>array(
// '$gte'=>new MongoDate($startDate)
'$gte'=>new MongoDB\BSON\UTCDateTime($startDate * 1000)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>array(
"day"=>array('$dayOfMonth'=>'$date'),
"month"=>array('$month'=>'$date'),
"year"=>array('$year'=>'$date')
),
'user'=>'$user.id',
),
"visualizzazioni"=>array(
'$sum'=>1
),
"isNew"=>array(
'$sum'=>array(
'$cond'=>array(
array('$eq'=>array('$user.isNew',true)),
1,
0
)
)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>'$_id.date'
),
"visualizzazioni"=>array(
'$sum'=>'$visualizzazioni'
),
"unici"=>array(
'$sum'=>'$isNew'
),
"visitatori"=>array(
'$sum'=>1
)
)
),
array(
'$sort'=>array(
"_id.date.year"=>1,
"_id.date.month"=>1,
"_id.date.day"=>1
)
)
);
return $rval;
}
public static function getDailyVisualizationPipelineByStartAndEnd($startDate,$endDate){
$rval = array(
array(
'$project'=>array(
'tdate'=>array(
'$add'=>array(
'$date',60*60*1000
)
),
"statType"=>'$statType',
'user'=>'$user',
)
),
array(
'$match'=>array(
'statType'=>StatisticModel::STAT_TYPE_PAGE,
'tdate'=>array(
// '$gte'=>new MongoDate($startDate),
// '$lte'=>new MongoDate($endDate)
'$gte'=>new MongoDB\BSON\UTCDateTime($startDate * 1000),
'$lte'=>new MongoDB\BSON\UTCDateTime($endDate * 1000)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>array(
"day"=>array('$dayOfMonth'=>'$tdate'),
"month"=>array('$month'=>'$tdate'),
"year"=>array('$year'=>'$tdate')
),
'user'=>'$user.id',
),
"visualizzazioni"=>array(
'$sum'=>1
),
"isNew"=>array(
'$sum'=>array(
'$cond'=>array(
array('$eq'=>array('$user.isNew',true)),
1,
0
)
)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>'$_id.date'
),
"visualizzazioni"=>array(
'$sum'=>'$visualizzazioni'
),
"unici"=>array(
'$sum'=>'$isNew'
),
"visitatori"=>array(
'$sum'=>1
)
)
),
array(
'$sort'=>array(
"_id.date.year"=>1,
"_id.date.month"=>1,
"_id.date.day"=>1
)
)
);
return $rval;
}
public static function getMonthlyVisualizationPipeline($startDate){
$rval = array(
array(
'$match'=>array(
'statType'=>StatisticModel::STAT_TYPE_PAGE,
'date'=>array(
// '$gte'=>new MongoDate($startDate)
'$gte'=>new MongoDB\BSON\UTCDateTime($startDate * 1000)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>array(
"month"=>array('$month'=>'$date'),
"year"=>array('$year'=>'$date')
),
'user'=>'$user.id',
),
"visualizzazioni"=>array(
'$sum'=>1
),
"isNew"=>array(
'$sum'=>array(
'$cond'=>array(
array('$eq'=>array('$user.isNew',true)),
1,
0
)
)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'date'=>'$_id.date'
),
"visualizzazioni"=>array(
'$sum'=>'$visualizzazioni'
),
"unici"=>array(
'$sum'=>'$isNew'
),
"visitatori"=>array(
'$sum'=>1
)
)
),
array(
'$sort'=>array(
"_id.date.year"=>1,
"_id.date.month"=>1
)
)
);
return $rval;
}
/**
* Il risultato di questa pipeline restituisce un oggetto con _id.banner contenente l'id del banner e visualizzazioni contenente il numero
* di visualizzazioni per oggi ordinati in modo crescente per visualizzazioni
* @param unknown $position
* @return multitype:multitype:multitype:number multitype:multitype:unknown number multitype:MongoDate multitype:multitype:multitype:number multitype:multitype:string
*/
public static function getTodaysBannerVisualizationPipeline($position){
$rval = array(
array(
'$match'=>array(
'statType'=>StatisticModel::STAT_TYPE_BANNER_IMPRESSION,
'content.position'=>$position,
// 'date'=>array( '$gte'=>new MongoDate(strtotime("today")) )
'date'=>array( '$gte'=>new MongoDB\BSON\UTCDateTime(strtotime("today") * 1000) )
)
),
array(
'$group'=>array(
"_id"=>array(
'banner'=>'$content.banner',
),
"visualizzazioni"=>array(
'$sum'=>1
)
)
),
array(
'$sort'=>array(
"visualizzazioni"=>1
)
)
);
return $rval;
}
/**
* Il risultato di questa pipeline restituisce un oggetto con _id.banner contenente l'id del banner e visualizzazioni contenente il numero
* di visualizzazioni per oggi ordinati in modo crescente per visualizzazioni
* @param unknown $position
* @return multitype:multitype:multitype:number multitype:multitype:unknown number multitype:MongoDate multitype:multitype:multitype:number multitype:multitype:string
*/
public static function getMostViewedOfLastDays($startDate,$limit = 5){
$rval = array(
array(
'$match'=>array(
'statType'=>StatisticModel::STAT_TYPE_NOTIZIA,
'date'=>array(
// '$gte'=>new MongoDate($startDate)
'$gte'=>new MongoDB\BSON\UTCDateTime($startDate * 1000)
)
)
),
array(
'$group'=>array(
"_id"=>array(
'notizia'=>'$content.notizia',
),
"visualizzazioni"=>array(
'$sum'=>1
)
)
),
array(
'$sort'=>array(
"visualizzazioni"=>-1
)
),
array(
'$limit'=>$limit
)
);
return $rval;
}
}
?>
+71
View File
@@ -0,0 +1,71 @@
<?php
/*
* RSSHelper.php
* Author: Riccardo Di Dato
* Creation Date: 17 lug 2017
*/
class RSSHelper {
public static function generateByNotiziaList(array $notizie){
header('Content-Type: application/xml');
echo '<?xml version="1.0"?>',PHP_EOL;
echo '<rss version="2.0" encoding="UTF-8">',PHP_EOL;
echo '<channel>',PHP_EOL;
self::generateChannelInfo();
if (sizeof($notizie)>0){
foreach ($notizie as $notizia){
self::generateNotiziaInfo($notizia);
}
}
echo '</channel>',PHP_EOL;
echo '</rss>',PHP_EOL;
}
private static function generateChannelInfo(){
$conf = GlobalVariables::get("config");
echo '<title>'.$conf->info->projectName.'</title>',PHP_EOL;
echo '<link>'.GUIHandler::getBaseUrl().'</link>',PHP_EOL;
echo '<description>'.html_entity_decode($conf->info->projectDescription).'</description>',PHP_EOL; // Entity decode perchè in config contiene &agrave; e non ho intenzione di controllare tutta l'applicazione
echo '<language>it-IT</language>',PHP_EOL;
echo '<webMaster>webmaster@ifattidinapoli.it</webMaster>',PHP_EOL;
echo '<image>',PHP_EOL;
echo '<title>'.$conf->info->projectName.'</title>',PHP_EOL;
echo '<link>'.GUIHandler::getBaseUrl().'</link>',PHP_EOL;
echo '<url>'.GUIHandler::getBaseUrl().'/images/logo_uff.png</url>',PHP_EOL;
echo '<width>48</width>',PHP_EOL;
echo '<height>48</height>',PHP_EOL;
echo '</image>',PHP_EOL;
}
private static function generateNotiziaInfo(NotiziaModel $notizia){
$conf = GlobalVariables::get("config");
echo '<item>',PHP_EOL;
echo '<title>'.$notizia->titolo.'</title>',PHP_EOL;
echo '<description>'.htmlentities($notizia->testo).'</description>',PHP_EOL;
echo '<link>'.$notizia->getAbsoluteUrl().'</link>',PHP_EOL;
$mainMedia = DaoMediaHandler::getMainMediaFromModel($notizia);
if (!is_null($mainMedia) && $mainMedia->hasProperty("mediaType") && $mainMedia->mediaType == MediaModel::TYPE_IMAGE){
$renderer = $mainMedia->getRenderer();
if ($renderer instanceof MediaImage){
$link = $renderer->getImageLink(MediaRendererInterface::SIZE_MEDIUM);
echo '<enclosure url="'.htmlentities($renderer->getImageLink(MediaRendererInterface::SIZE_MEDIUM)).'" length="'.filesize($renderer->getPath()).'" type="image/png" />',PHP_EOL;
}
}
echo '<pubDate>'.date(DATE_RFC2822,$notizia->about->data->toDateTime()->getTimestamp()).'</pubDate>',PHP_EOL;
echo '<guid>'.GUIHandler::getBaseUrl().'articolo_'.$notizia->id.'</guid>',PHP_EOL;
echo '</item>',PHP_EOL;
}
}
?>
@@ -0,0 +1,112 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 19/feb/2016
*/
class FDN2CBS_DataStorage extends CBSClient_DataStorageBase{
/**
* Restituisce un mongoID (stringa)
* @see CBSClient_DataStorageBase::getNextOperationId()
*/
public function getNextOperationId(){
$rval = 1;
$conf = GlobalVariables::get("dao")->getFirst("ConfigModel",array("name"=>"cbsQueue"));
if (!is_null($conf)){
$rval = $conf->lastOperationId+1;
}
return $rval;
// $cur = GlobalVariables::get("dao")->getFirst("CBSQueueModel",array(),array("sort"=>"operationId"));
// if (is_null($cur)){
// return 1;
// }
// else {
// return $cur->operationId+1;
// }
}
/**
* (non-PHPdoc)
* @see CBSClient_DataStorageBase::setMaxOperationId()
*/
public function setMaxOperationId($id){
$conf = GlobalVariables::get("dao")->getFirst("ConfigModel",array("name"=>"cbsQueue"));
if (is_null($conf)){
$obj = new stdClass();
$obj->name="cbsQueue";
$conf = new ConfigModel($obj);
}
$conf->lastOperationId = $id;
GlobalVariables::get("dao")->save($conf);
}
/**
* @see CBSClient_DataStorageBase::queueUncompletedRequest()
*/
public function queueUncompletedRequest($id, RAPI_RequestDetails $req){
$queueFolder = GlobalVariables::get("config")->paths->cbsQueue;
$obj = new stdClass();
$obj->operationId = $id;
$obj->retry = 0;
$queueObj = new CBSQueueModel($obj);
GlobalVariables::get("dao")->save($queueObj);
if (!SFSManager::fileExists($queueFolder)){
SFSManager::createDirectory($queueFolder);
}
$path = $queueFolder."/".$queueObj->id;
SFSManager::writeFile(serialize($req), $path);
}
/**
* @see CBSClient_DataStorageBase::getUncompletedRequests()
*/
public function getUncompletedRequests($limit = null){
$rval = array();
$basePath = GlobalVariables::get("config")->paths->cbsQueue;
$opt = array("sort"=>array("retry"=>1));
if (!is_null($limit)){
$opt["limit"] = $limit;
}
$requests = GlobalVariables::get("dao")->query("CBSQueueModel", array(), $opt);
if (sizeof($requests)>0){
foreach ($requests as $request){
$path = $basePath."/".$queueObj->id;
$cont = implode("",SFSManager::readFile($path));
$rval[] = unserialize($cont);
}
}
return $rval;
}
/**
* @see CBSClient_DataStorageBase::onRequestCompletedFromQueue()
*/
public function onRequestCompletedFromQueue($id){
$queueObj = GlobalVariables::get("dao")->getFirst("CBSQueueModel", array("operationId"=>$id));
$path = GlobalVariables::get("config")->paths->cbsQueue."/".$queueObj->id;
SFSManager::deleteFile($path);
GlobalVariables::get("dao")->delete($queueObj);
}
/**
* @see CBSClient_DataStorageBase::onRequestFailedFromQueue()
*/
public function onRequestFailedFromQueue($id){
$queueObj = GlobalVariables::get("dao")->getFirst("CBSQueueModel", array("operationId"=>$id));
$queueObj->retry = $queueObj->retry+1;
GlobalVariables::get("dao")->save($queueObj);
}
// private function getOperationIdFile(){
// $config = GlobalVariables::get("config");
// return $config->paths->common."/RAPI_maxOperationId";
// }
}
?>
+55
View File
@@ -0,0 +1,55 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 19/feb/2016
*/
class FDN2CBS_Logger implements RAPI_Logger{
/**
* (non-PHPdoc)
* @see LoggingFacility::log()
*/
public function log($level, $message){
LoggingFacilityManager::getLogger("api")->log($this->convertToCbsLogLevel($level),$message);
}
/**
* (non-PHPdoc)
* @see RAPI_Logger::generateSecurityWarning()
*/
public function generateSecurityWarning($severity, $message, RAPI_Request $request){
LoggingFacilityManager::getLogger("api")->log(LoggingFacility::$LEVEL_WARNING,"CBS SECURITY WARNING - ".$message);
}
/**
* (non-PHPdoc)
* @see RAPI_Logger::generateSecurityOperationWarning()
*/
public function generateSecurityOperationWarning($severity, $message, RAPI_Request $request, RAPI_Operation $op){
}
private function convertToCbsLogLevel($level){
switch ($level){
case RAPI_Logger::LOG_LEVEL_DEBUG:
$rval = LoggingFacility::$LEVEL_DEBUG;
break;
case RAPI_Logger::LOG_LEVEL_INFO:
$rval = LoggingFacility::$LEVEL_INFO;
break;
case RAPI_Logger::LOG_LEVEL_WARNING:
$rval = LoggingFacility::$LEVEL_WARNING;
break;
case RAPI_Logger::LOG_LEVEL_ERROR:
$rval = LoggingFacility::$LEVEL_ERROR;
break;
}
return $rval;
}
}
?>
@@ -0,0 +1,29 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 18/feb/2016
*/
/**
* Classe semplificare l'implementazione del client
* @author Riccardo Di Dato
*/
class CBSClient extends RAPI_ClientHelper{
/**
* La classe si occupa già di costruire il RAPI_Client e di implementare i metodi dell'helper
* @param RAPI_Logger $logger
* @param RAPI_DataStorage $dataStorage
* @param string $receivedAttachmentPath
*/
public function __construct(RAPI_Logger $logger, CBSClient_DataStorageBase $dataStorage, $receivedAttachmentPath){
parent::__construct(new CBS_RAPIClientImplementation($logger, $dataStorage, $receivedAttachmentPath));
$this->defineRequest("getBackups", "RAPI_BackupListRequestDetails", new RAPI_SingleValueResponseFetcher("list"));
$this->defineRequest("sendBackup", "RAPI_CreateBackupRequestDetails", new RAPI_SingleValueResponseFetcher("id"));
// $this->defineRequest("getBackup", "RAPI_GetBackupRequestDetails", new RAPI_StandardResponseFetcher(function($d){$d->content = utf8_decode($d->content); return $d; }));
$this->defineRequest("getBackup", "RAPI_GetBackupRequestDetails", new RAPI_StandardResponseFetcher());
}
}
?>
@@ -0,0 +1,66 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 18/feb/2016
*/
abstract class CBSClient_DataStorageBase implements RAPI_DataStorage{
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::getRapiPassphrase()
*/
public function getRapiPassphrase(){
return GlobalVariables::get("config")->api->passphrase;
}
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::getRapiAccount()
*/
public function getRapiAccount(){
return GlobalVariables::get("config")->api->account;
}
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::getRapiUser()
*/
public function getRapiUser(){
return "1";
}
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::getNextOperationId()
*/
abstract public function getNextOperationId();
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::setMaxOperationId()
*/
abstract public function setMaxOperationId($id);
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::queueUncompletedRequest()
*/
abstract public function queueUncompletedRequest($id, RAPI_RequestDetails $req);
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::getUncompletedRequests()
*/
abstract public function getUncompletedRequests($limit = null);
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::onRequestCompletedFromQueue()
*/
abstract public function onRequestCompletedFromQueue($id);
/**
* (non-PHPdoc)
* @see RAPI_DataStorage::onRequestFailedFromQueue()
*/
abstract public function onRequestFailedFromQueue($id);
}
?>
@@ -0,0 +1,45 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/feb/2016
*/
class CBS_RAPIClientImplementation extends RAPI_Client {
private $fh;
private $attachmentPath;
public function __construct($logger, $dataStorage, $attachmentPath){
parent::__construct($logger, $dataStorage);
$this->attachmentPath = $attachmentPath;
}
protected function openConnection(){
$service_port = getservbyname('rapi', 'tcp');
$address = RAPI_Config::RAPI_SERVER_ADDRESS;
$this->fh = stream_socket_client("tcp://$address:$service_port", $errno, $errstr, 30);
}
protected function closeConnection(){
fclose($this->fh);
}
protected function sendMessage($msg){
fwrite($this->fh, $msg);
}
protected function getMessage($bufferSize = null){
if (is_null($bufferSize)){
return fgets($this->fh);
}
else {
return fgets($this->fh,$bufferSize);
}
}
protected function getReceivedAttachmentPath(){
return $this->attachmentPath;
}
}
?>
@@ -0,0 +1,28 @@
<?php
/*
* Per usare il client basta estendere le classi RAPI_Logger e CBSClient_DataStorageBase ed utilizzarle per implementare CBSClient
Author: Riccardo Di Dato
Creation Date: 18/feb/2016
*/
require_once(dirname(__FILE__)."/rapi/rapi_client/RAPI_Client.php");
// TEST IMPLEMENTATIONS
require_once(dirname(__FILE__)."/messages/request/RAPI_BackupListRequestDetails.php");
require_once(dirname(__FILE__)."/messages/request/RAPI_CreateBackupRequestDetails.php");
require_once(dirname(__FILE__)."/messages/request/RAPI_GetBackupRequestDetails.php");
require_once(dirname(__FILE__)."/messages/response/RAPI_BackupListResponseDetails.php");
require_once(dirname(__FILE__)."/messages/response/RAPI_CreateBackupResponseDetails.php");
require_once(dirname(__FILE__)."/messages/response/RAPI_GetBackupResponseDetails.php");
require_once(dirname(__FILE__)."/CBSClient_DataStorageBase.php");
require_once(dirname(__FILE__)."/CBS_RAPIClientImplementation.php");
require_once(dirname(__FILE__)."/CBSClient.php");
RAPI_BackupListRequestDetails::registerToFactory();
RAPI_CreateBackupRequestDetails::registerToFactory();
RAPI_GetBackupRequestDetails::registerToFactory();
?>
@@ -0,0 +1,51 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 20/gen/2016
*/
/**
* Parametri Nessuno
* Ritorna la lista Backup dell'account richiedente
*
* @author Riccardo Di Dato
*/
class RAPI_BackupListRequestDetails extends RAPI_RequestDetails {
/**
* Returns true if the operation requires an
* operationId (like for writes and deletion)
*/
public static function usesOperationId(){
return false;
}
/**
* Returns the name of the operation used by the request factory (NOT THE RAPI_Operation !!!!!)
* @return string
*/
public static function getOperationName(){
return "BackupList";
}
/**
* @see RAPI_RequestDetails::getResponseDetailsClass()
*/
public static function getResponseDetailsClass(){
return "RAPI_BackupListResponseDetails";
}
/**
* @see RAPI_RequestDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("options");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
@@ -0,0 +1,51 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 10/feb/2016
*/
/**
* Parametri {fileContent}.
* Salva {fileContent} come nuovo backup
*
* @author Riccardo Di Dato
*/
class RAPI_CreateBackupRequestDetails extends RAPI_RequestDetails {
/**
* Returns true if the operation requires an
* operationId (for writes and deletion)
*/
public static function usesOperationId(){
return true;
}
/**
* Returns the name of the operation used by the request factory (NOT THE RAPI_Operation !!!!!)
* @return string
*/
public static function getOperationName(){
return "CreateBackup";
}
/**
* @see RAPI_RequestDetails::getResponseDetailsClass()
*/
public static function getResponseDetailsClass(){
return "RAPI_CreateBackupResponseDetails";
}
/**
* @see RAPI_RequestDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("filename");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array("backup");
}
}
?>
@@ -0,0 +1,52 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 11/feb/2016
*/
/**
* Parametri ID
* Ritorna un backup con dati e contenuto file
*
* @author Riccardo Di Dato
*/
class RAPI_GetBackupRequestDetails extends RAPI_RequestDetails {
/**
* Returns true if the operation requires an
* operationId (like for writes and deletion)
*/
public static function usesOperationId(){
return false;
}
/**
* Returns the name of the operation used by the request factory (NOT THE RAPI_Operation !!!!!)
* @return string
*/
public static function getOperationName(){
return "GetBackup";
}
/**
* @see RAPI_RequestDetails::getResponseDetailsClass()
*/
public static function getResponseDetailsClass(){
return "RAPI_GetBackupResponseDetails";
}
/**
* @see RAPI_RequestDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("id");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,24 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 20/gen/2016
*/
class RAPI_BackupListResponseDetails extends RAPI_ResponseDetails {
/**
* @see RAPI_MessageDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("list");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,23 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 10/feb/2016
*/
class RAPI_CreateBackupResponseDetails extends RAPI_ResponseDetails {
/**
* @see RAPI_MessageDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("id");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,23 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 11/feb/2016
*/
class RAPI_GetBackupResponseDetails extends RAPI_ResponseDetails {
/**
* @see RAPI_MessageDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("info","content");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array("backup");
}
}
?>
@@ -0,0 +1,45 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 24/giu/2015
*/
class RAPI_Config {
/**
* Versione del protocollo
* @var string
*/
const RAPI_VERSION = "RAPI-1.2";
/**
* Tempo massimo valido tra l'invio della richiesta e la sua ricezione (in minuti)
* @var int
*/
// const REQUEST_TIMEOUT = 3;
const REQUEST_TIMEOUT = 100000;
/**
* Timeout della richiesta oltre il quale il sistema genera un warning di sicurezza (minuti)
* @var int
*/
const REQUEST_TIMEOUT_WARNING = 180;
/**
* Debug variables
* @var bool
*/
const DISABLE_DIGEST = false;
/*
* CLIENT ONLY
*/
/**
* L'ip del server con installato rapi server
* @var string
*/
const RAPI_SERVER_ADDRESS = "cbs.asdynamics.com";
}
?>
@@ -0,0 +1,48 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
class RAPI_CryptUtils{
/**
* Genera un digest
* @param string $user Identificativo dell'utente
* @param int $timestamp Timestamp in microsecondi
* @param string $details Corpo della richiesta in JSON
* @param string $passphrase Password per la cifratura
* @return string
*/
private static function getDigest($user, $timestamp, $details, $passphrase) {
return hash_hmac("sha256",$user.$timestamp.substr($details,0,1000),$passphrase);
}
/**
* Genera un digest a partire da un messaggio
* @param string $user Identificativo dell'utente
* @param int $timestamp Timestamp in microsecondi
* @param string $details Corpo della richiesta in JSON
* @param string $passphrase Password per la cifratura
* @return string
*/
public static function getDigestForMessage(RAPI_Message $msg, $passphrase){
$user = null;
if ($msg instanceof RAPI_Request){
$user = $msg->getUser();
}
else if ($msg instanceof RAPI_Response){
$user = $msg->getRelatedRequest()->getUser();
}
else {
throw new RAPI_Exception("Invalid usage of CryptUtils::getDigestForMessage(); Unimplemented message type ('".get_class($msg)."')");
}
$timestamp = $msg->getTime();
$details = $msg->getDetails(true);
return self::getDigest($user, $timestamp, $details, $passphrase);
}
}
?>
@@ -0,0 +1,44 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 24/giu/2015
*/
interface RAPI_Logger {
const LOG_LEVEL_DEBUG = 1;
const LOG_LEVEL_INFO = 2;
const LOG_LEVEL_WARNING = 3;
const LOG_LEVEL_ERROR = 4;
const WARNING_SEVERITY_LOW = 1;
const WARNING_SEVERITY_MEDIUM = 2;
const WARNING_SEVERITY_HIGH = 3;
const WARNING_SEVERITY_CRITICAL = 4;
/**
* Una riga di log
* @param int $level Livello del log
* @param string $message Messaggio da scrivere nel log
*/
public function log($level, $message);
/**
* Genera un warning di sicurezza.
* @param int $level Importanza del warning
* @param string $message Messaggio da scrivere nel log
* @param RAPI_Message $request RAPI_Message che ha generato il warning
*/
public function generateSecurityWarning($severity, $message, RAPI_Request $request);
/**
* Come il warning sulla richiesta, ma include i dettagli dell'operazione
* @param int $level Importanza del warning
* @param string $message Messaggio da scrivere nel log
* @param RAPI_Message $request RAPI_Message associato all'operazione
* @param RAPI_Operation $op Operazione che ha generato il warning
*/
public function generateSecurityOperationWarning($severity, $message, RAPI_Request $request, RAPI_Operation $op);
}
?>
@@ -0,0 +1,16 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 24/giu/2015
*/
/**
* Eccezione generica lanciata dal sistema RAPI
* @author Riccardo Di Dato
*/
class RAPI_Exception extends Exception{
}
?>
@@ -0,0 +1,40 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
/**
* Eccezione lanciata in caso di errore di validazione.
* Contiene la causa per cui la richiesta non è valida
* @author rik
*
*/
class RAPI_ValidationException extends RAPI_Exception{
/**
* Lo status code che ha causato l'eccezione
* @var int
*/
private $status;
/**
* Costruisce la validation exception con un messaggio di default e salvando al suo interno lo status code.
* @param int $status
*/
public function __construct($status){
$this->status = $status;
parent::__construct("RAPI_ValidationException 'Status $status'");
}
/**
* Restituisce lo status code che ha causato l'eccezione
* @return int
*/
public function getStatus (){
return $this->status;
}
}
?>
@@ -0,0 +1,30 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
require_once(dirname(__FILE__)."/exceptions/RAPI_Exception.php");
require_once(dirname(__FILE__)."/exceptions/RAPI_ValidationException.php");
require_once(dirname(__FILE__)."/RAPI_Config.php");
require_once(dirname(__FILE__)."/RAPI_CryptUtils.php");
require_once(dirname(__FILE__)."/RAPI_Logger.php");
require_once(dirname(__FILE__)."/messages/RAPI_Message.php");
require_once(dirname(__FILE__)."/messages/RAPI_MessageDetails.php");
require_once(dirname(__FILE__)."/messages/RAPI_Request.php");
require_once(dirname(__FILE__)."/messages/RAPI_RequestDetails.php");
require_once(dirname(__FILE__)."/messages/RAPI_Response.php");
require_once(dirname(__FILE__)."/messages/RAPI_ResponseDetails.php");
require_once(dirname(__FILE__)."/messages/request/RAPI_UnreadableRequestDetails.php");
require_once(dirname(__FILE__)."/messages/request/RAPI_UnreadableRequest.php");
require_once(dirname(__FILE__)."/messages/response/RAPI_EmptyResponseDetails.php");
require_once(dirname(__FILE__)."/messages/response/RAPI_SimpleMessageResponseDetails.php");
require_once(dirname(__FILE__)."/messages/RAPI_RequestDetailsFactory.php");
?>
@@ -0,0 +1,256 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 24/giu/2015
*/
/**
* Message example:
* {
* version: ${protocol_version},
* time: ${timestamp_microseconds},
* digest: ${digest},
* details: ${request}
* }
* @author Riccardo Di Dato
*
*/
abstract class RAPI_Message {
private $encryptedCache = null;
/*
* Attributi, setters e getters
*/
/**
* Versione del protocollo RAPI
* @var string
*/
private $protocolVersion;
public function getProtocolVersion(){
return $this->protocolVersion;
}
/**
* Timestamp in microsecondi
* @var int
*/
private $time;
public function getTime(){
return $this->time;
}
/**
* Digest per valutare l'autenticità
* @var string
*/
private $digest;
public function getDigest(){
return $this->digest;
}
/**
* Imposta il digest per il messaggio
* @param string $digest il digest da impostare
*/
public function setDigest($digest){
$this->digest = $digest;
}
/**
* Una classe contenente i dettagli per generare l'operazione
* @var RAPI_MessageDetails
*/
private $details;
/**
* @param string $encoded
* @return string|RAPI_MessageDetails
*/
public function getDetails($encoded = false){
if ($encoded){
return json_encode($this->details);
}
else {
return $this->details;
}
}
/**
* Metodo di utility che richiama il metodo omonimo del message details.
* @return stdClass
*/
public function getAttachmentData($name){
return $this->getDetails()->getAttachmentData($name);
}
/**
* Metodo di utility che richiama il metodo omonimo del message details per l'istanza utilizzata all'interno
* @return stdClass
*/
public function getAttachmentList(){
return $this->getDetails()->getAttachmentList();
}
/**
* Metodo di utility che richiama il metodo omonimo del message details per l'istanza utilizzata all'interno
*/
public function setAttachmentLocalFileReference($name, $path){
$this->getDetails()->setAttachmentLocalFileReference($name,$path);
}
/**
* Metodo di utility che richiama il metodo omonimo del message details per l'istanza utilizzata all'interno
*/
public function getAttachmentLocalFileReference($name){
return $this->details->getAttachmentLocalFileReference($name);
}
/*
* Costruttore
*/
/**
* @param string $protocolVersion La versione del protocollo RAPI
* @param RAPI_MessageDetails $details Il contenuto del messaggio
* @param int $time Timestamp in microsecondi
* @param string $digest Digest per valutare l'autenticità del messaggio
*/
public function __construct($protocolVersion, RAPI_MessageDetails $details, $time = null, $digest = null){
$this->protocolVersion = $protocolVersion;
$this->time = is_null($time)?array_sum( explode( ' ' , microtime() ) ):$time;
$this->details = $details;
$this->digest = $digest;
}
/*
* Metodi per la SERIALIZZAZIONE
*/
/**
* Genera un oggetto standard da utilizzare per
* la serializzazione.
* Questa versione genera solo gli attributi
* relativi a RAPI_Message
* @return stdClass
*/
protected function generateEncryptionBaseObject(){
$rval = new stdClass();
$rval->version = $this->protocolVersion;
$rval->time = $this->time;
$rval->digest = $this->digest;
$rval->details = $this->details->generateEncryptionObject();
return $rval;
}
/**
* Restituisce la serializzazione dell'oggetto
* @return string
*/
public function getEncryption(){
if (is_null($this->encryptedCache)){
$this->testEncryption();
}
return $this->encryptedCache;
}
public function testEncryption(){
$this->encryptedCache = null;
$enc = json_encode($this->generateEncryptionObject());
if ($enc === false){
throw new RAPI_Exception("JSON Encoding failed. Message '".json_last_error_msg()."'");
}
$this->encryptedCache = $enc;
}
/*
* Metodi di DE-SERIALIZZAZIONE
*/
/**
* Deserializza la stringa e ritorna un oggetto RAPI_Message
* valido.
* @param string $string
* @param array $additionalData Parametro opzionale per aggiungere attributi (già decodificati) all'oggetto dopo la decodifica
* @throws RAPI_Exception Se non riesce a parsare la stringa
* @return RAPI_Message
*/
public static function fromEncrypted($string, array $additionalData = array()){
$appoggio = json_decode(trim($string));
if (!is_null($appoggio)){
if (sizeof($additionalData)>0){
foreach ($additionalData as $key => $val){
$appoggio->$key = $val;
}
}
}
else {
$errMsg = "Invalid request format ";
switch (json_last_error()) {
case JSON_ERROR_NONE:
$errMsg.= ' (No JSON errors)';
break;
case JSON_ERROR_DEPTH:
$errMsg.= ' (JSON - Maximum stack depth exceeded)';
break;
case JSON_ERROR_STATE_MISMATCH:
$errMsg.= ' (JSON - Underflow or the modes mismatch)';
break;
case JSON_ERROR_CTRL_CHAR:
$errMsg.= ' (JSON - Unexpected control character found)';
break;
case JSON_ERROR_SYNTAX:
$errMsg.= ' (JSON - Syntax error, malformed JSON)';
break;
case JSON_ERROR_UTF8:
$errMsg.= ' (JSON - Malformed UTF-8 characters, possibly incorrectly encoded)';
break;
default:
$errMsg.= ' (JSON - Unknown error)';
break;
}
throw new RAPI_Exception($errMsg);
}
return static::createFromObject($appoggio);
}
/**
* Ritorna true se l'oggetto ha gli
* attributi per costruire un RAPI_Message.
* @param stdClass $obj
* @return bool
*/
protected static function isValidObjectForCreationBase($obj){
return property_exists($obj, "version") &&
property_exists($obj, "time") &&
property_exists($obj, "digest") &&
property_exists($obj, "details");
}
/*
* Abstract
*/
/**
* Genera un oggetto che contiene tutti
* i valori da encodare (con JSON).
* Utilizza generateEncryptionBaseObject e gli aggiunge
* tutti gli attributi da includere nel messaggio
* @return stdClass
*/
protected abstract function generateEncryptionObject();
/**
* Ritorna true se l'oggetto ha gli
* attributi per costruire un RAPI_Message.
* Utilizzare isValidObjectForCreationBase e dopo
* valutare gli attributi della sottoclasse
* @param stdClass $obj
* @return bool
*/
protected static abstract function isValidObjectForCreation($obj);
/**
* Costruisce un message a partire da una stdClass.
* @param stdClass $obj
* @return RAPI_Message
* @throws RAPI_Exception
*/
public static abstract function createFromObject($obj);
}
?>
@@ -0,0 +1,135 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 01/lug/2015
*/
abstract class RAPI_MessageDetails {
/**
* @var stdClass
*/
private $data;
/**
* @var stdClass
*/
private $attachments = array();
/**
* @return stdClass
*/
public function getData(){
return $this->data;
}
/**
* @return stdClass
*/
public function getAttachmentData($name){
if (!array_key_exists($name, $this->attachments)){
throw new RAPI_Exception("Invalid attachment name ($name) passed to '".get_called_class()."::getAttachmentData()'");
}
return $this->attachments[$name];
}
/**
* Imposta il file di appoggio LOCALE per un attachment
* @param string $name nome dell'attachment
* @param string $path il path del file
* @throws RAPI_Exception
*/
public function setAttachmentLocalFileReference($name, $path){
if (!array_key_exists($name, $this->attachments)){
throw new RAPI_Exception("Invalid attachment name ($name) passed to '".get_called_class()."::setAttachmentLocalFileReference()'");
}
$this->attachments[$name]->localReference = $path;
}
public function getAttachmentLocalFileReference($name){
if (!array_key_exists($name, $this->attachments)){
throw new RAPI_Exception("Invalid attachment name ($name) passed to '".get_called_class()."::getAttachmentLocalFileReference()'");
}
return $this->attachments[$name]->localReference;
}
/**
* Il parametro $data deve avere come attributi almeno quelli restituiti da getArgumentList()
* @param stdClass $data
* @throws RAPI_Exception
*/
public function __construct(stdClass $data, array $attachments = array()){
foreach (static::getArgumentList() as $arg){
if (!property_exists($data, $arg)){
throw new RAPI_Exception("Invalid data object passed to '".get_called_class()."'. Missing property '$arg'");
}
}
$requiredAttachments = static::getAttachmentList();
$requiredFields = array("md5","size","name");
if (sizeof($attachments)>0){
foreach ($attachments as $attachment){
foreach ($requiredFields as $field){
if (!property_exists($attachment, $field)){
throw new RAPI_Exception("Invalid attachment data object passed to '".get_called_class()."'. Missing property '$field' for attachment '$attachName'");
}
}
$this->attachments[$attachment->name] = $attachment;
if ( ($key = array_search($attachment->name, $requiredAttachments)) !== false ){
unset($requiredAttachments[$key]);
}
}
}
if (sizeof($requiredAttachments)>0){
throw new RAPI_Exception("Invalid attachment array passed to '".get_called_class()."'. Missing attachments '".implode(", ", $requiredAttachments)."'");
}
$this->data = $data;
}
/**
* Restituisce la codifica JSON del messaggio
* @return string
*/
public function __toString(){
return json_encode($this->generateEncryptionObject());
}
/**
* Restituisce una stdClass utilizzabile per rigenerare l'oggetto
* @return stdClass
*/
public function generateEncryptionObject(){
$tmp = new stdClass();
$tmp->data = new stdClass();
foreach (static::getArgumentList() as $argName){
$tmp->data->$argName = $this->data->$argName;
}
$tmp->attachments = array();
foreach (static::getAttachmentList() as $attachName){
$ele = new stdClass();
$ele->name = $attachName;
$ele->md5 = $this->attachments[$attachName]->md5;
$ele->size = $this->attachments[$attachName]->size;
$tmp->attachments[] = $ele;
}
return $tmp;
}
/*
* Abstract Methods
*/
/**
* Returns the list of arguments
* @return string[]
*/
public static abstract function getArgumentList();
/**
* Returns the list of attachments
* @var stdClass[]
*/
public static abstract function getAttachmentList();
}
?>
@@ -0,0 +1,143 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
/**
* Request example:
* {
* version: ${protocol_version},
* account: ${acc_id},
* user: ${user_id},
* time: ${timestamp_microseconds},
* msg_id: ${request_id},
* digest: ${digest},
* details: ${request}
* }
* @author Riccardo Di Dato
*
*/
class RAPI_Request extends RAPI_Message{
/*
* Attributi, setters e getters
*/
/**
* Account utilizzato per la richiesta
* @var string
*/
private $account;
public function getAccount(){
return $this->account;
}
/**
* Utente dell'account
* @var string
*/
private $user;
public function getUser(){
return $this->user;
}
/**
* Identificativo della richiesta (NULL in lettura)
* @var string
*/
private $operationId;
public function getOperationId(){
return $this->operationId;
}
/*
* Metodi propri della classe
*/
/**
* @param string $account Il token dell'account che fa la richiesta
* @param string $user L'identificativo dell'utente (collegato all'account) che fa la richiesta
* @param string $operationId Identificativo univoco del messaggio. UTILIZZARE SOLO IN SCRITTURA, IN LETTURA UTILIZZARE null
* @param string $protocolVersion La versione del protocollo RAPI
* @param RAPI_RequestDetails $details Il contenuto della richiesta
* @param int $time Timestamp in microsecondi
* @param string $digest Digest per valutare l'autenticità del messaggio
*/
public function __construct($account, $user, $operationId, $protocolVersion, RAPI_RequestDetails $details, $time = null, $digest = null){
parent::__construct($protocolVersion, $details, $time, $digest);
$this->account = $account;
$this->user = $user;
$this->operationId = $operationId;
}
/**
* Metodo di utility che richiama il metodo omonimo del request details.
* Se una delle request è un checksumFake confronta solo i due checksum.
* @param RAPI_Request $req
* @return boolean
*/
public function isEqual(RAPI_Request $req){
return strcmp($this->getProtocolVersion(),$req->getProtocolVersion())==0 &&
strcmp($this->account,$req->account)==0 &&
strcmp($this->user,$req->user)==0 &&
strcmp($this->operationId,$req->operationId)==0 &&
$this->getDetails()->isEqual($req->getDetails());
}
/**
* Metodo di utility che richiama il metodo omonimo del request details.
* @return bool
*/
public function isChecksumFake(){
return $this->getDetails()->isChecksumFake();
}
/**
* Genera la versione checksumFake della rapi request.
* @return RAPI_Request
*/
public function generateChecksumFake(){
$rval = new RAPI_Request($this->account, $this->user, $this->getOperationId(), $this->getProtocolVersion(), $this->getDetails()->generateChecksumFake(), $this->getTime(), $this->getDigest());
return $rval;
}
/*
* Abstract Implementations
*/
/**
* @see RAPI_Message::generateEncryptionObject()
*/
protected function generateEncryptionObject(){
$rval = $this->generateEncryptionBaseObject();
$rval->account = $this->account;
$rval->user = $this->user;
$rval->operationId = $this->operationId;
return $rval;
}
/**
* @see RAPI_Message::isValidObjectForCreation()
*/
protected static function isValidObjectForCreation($obj){
return self::isValidObjectForCreationBase($obj) &&
property_exists($obj, "account") &&
property_exists($obj, "user") &&
property_exists($obj, "operationId");
}
/**
* @see RAPI_Message::createFromObject()
*/
public static function createFromObject($obj){
if (self::isValidObjectForCreation($obj)){
$details = RAPI_RequestDetailsFactory::generateFromEncryptionObject($obj->details);
return new RAPI_Request($obj->account, $obj->user, $obj->operationId, $obj->version, $details, $obj->time, $obj->digest);
}
else {
throw new RAPI_Exception("Invalid request format");
}
}
}
?>
@@ -0,0 +1,137 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 01/lug/2015
*/
/**
*
* @author Riccardo Di Dato
*/
abstract class RAPI_RequestDetails extends RAPI_MessageDetails{
/**
* Stringa md5 usata come checksum.
* L'attributo è valorizzato solo per i checksumFake
* @var string
*/
private $md5 = null;
/*
* Checksum e checksumFake
*/
/**
* Restituisce il checksum (Indipendentemente che si tratti o meno di un checksumFake).
* @return string
*/
public function getChecksum(){
$rval = $this->md5;
if (is_null($rval)){
$rval = md5(strval($this));
}
return $rval;
}
/**
* Forza il valore della variabile interna contenente il checkusm.
* ATTENZIONE! I non checksumFake non dovrebbero avere questo attributo valorizzato
* @param string $md5
*/
public function forceChecksum($md5){
$this->md5 = $md5;
}
/**
* Genera la versione checksumFake di un rapi request details.
* @return RAPI_RequestDetails
*/
public function generateChecksumFake(){
$encObj = parent::generateEncryptionObject();
$tmp = new stdClass();
if (sizeof(static::getArgumentList())>0){
foreach (static::getArgumentList() as $arg){
$tmp->$arg = "";
}
}
$obj = new static($tmp,$encObj->attachments);
$obj->md5 = $this->getChecksum();
return $obj;
}
/**
* Restituisce true se si tratta di un checksum fake.
* @return boolean
*/
public function isChecksumFake(){
return !is_null($this->md5);
}
/*
* Metodi propri della classe
*/
/**
* Valuta l'uguaglianza delle request details
* NOTA: Funziona anche se un requestDetails è un checksumFake, ma in tal caso confronta solo i due checksum.
* @param RAPI_Request $req
* @return boolean
*/
public function isEqual(RAPI_RequestDetails $req){
$rval = ( strcmp($this->getChecksum(), $req->getChecksum())==0 ) ;
if (!$this->isChecksumFake() && !$req->isChecksumFake()){
$rval = strcmp($this, $req);
}
return $rval;
}
/**
* @see RAPI_MessageDetails::generateEncryptionObject()
*/
public function generateEncryptionObject(){
$tmp = parent::generateEncryptionObject();
$tmp->operation = static::getOperationName();
if ($this->isChecksumFake()){
$tmp->md5 = $this->getChecksum();
}
return $tmp;
}
/*
* Factory
*/
/**
* Registra il details alla factory
*/
public static function registerToFactory(){
RAPI_RequestDetailsFactory::addToRegister(static::getOperationName(), get_called_class());
}
/*
* Metodi astratti
*/
/**
* Returns true if the operation requires an
* operationId (like for writes and deletion)
* @return bool
*/
public static abstract function usesOperationId();
/**
* Returns the name of the operation used by the request factory (NOT THE RAPI_Operation !!!!!)
* @return string
*/
public static abstract function getOperationName();
/**
* Returns the class name of the response details to use
* @return string
*/
public static abstract function getResponseDetailsClass();
}
?>
@@ -0,0 +1,52 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 01/lug/2015
*/
class RAPI_RequestDetailsFactory{
private static $REGISTER = array();
public static function addToRegister($operationName,$requestDetails){
self::$REGISTER[$operationName] = $requestDetails;
}
public static function getRequestDetailsClassnameByOperationName($operationName){
if (array_key_exists($operationName, self::$REGISTER)){
return self::$REGISTER[$operationName];
}
else {
throw new RAPI_Exception("Invalid operation name passed to RAPI_RequestDetailsFactory::getRequestDetailsClassnameByOperationName '$operationName'");
}
}
/**
*
* @param stdClass $tmp
* @throws RAPI_Exception
* @return RAPI_RequestDetails
*/
public static function generateFromEncryptionObject(stdClass $tmp){
if (!property_exists($tmp, 'operation')) {
throw new RAPI_Exception("Invalid encryptionObject passed to RAPI_RequestDetailsFactory::generateFromEncryptionObject (operation field missing)");
}
else if (!property_exists($tmp, 'data')) {
throw new RAPI_Exception("Invalid encryptionObject passed to RAPI_RequestDetailsFactory::generateFromEncryptionObject (data field missing)");
}
else if (!property_exists($tmp, 'attachments')) {
throw new RAPI_Exception("Invalid encryptionObject passed to RAPI_RequestDetailsFactory::generateFromEncryptionObject (attachment field missing)");
}
else {
$classname = self::getRequestDetailsClassnameByOperationName($tmp->operation);
$rval = new $classname($tmp->data,$tmp->attachments);
if (property_exists($tmp, 'md5')){
$rval->forceChecksum($tmp->md5);
}
return $rval;
}
}
}
?>
@@ -0,0 +1,172 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
/**
* Response example:
* {
* version: ${protocol_version},
* time: ${timestamp_microseconds},
* status: ${response_status},
* digest: ${digest},
* details: ${request}
* }
* @author Riccardo Di Dato
*
*/
class RAPI_Response extends RAPI_Message{
/*
* Class Static
*/
const STATUS_OK = 0;
const STATUS_MALFORMED = 1;
const STATUS_UNAUTHORIZED = 2;
const STATUS_INVALID = 3;
const STATUS_EXPIRED = 4;
const STATUS_INTERNAL_SERVER_ERROR = 5;
private static $STATUS_DATA = array(
self::STATUS_MALFORMED => array("message"=>"MALFORMED"),
self::STATUS_UNAUTHORIZED => array("message"=>"UNAUTHORIZED"),
self::STATUS_INVALID => array("message"=>"INVALID"),
self::STATUS_EXPIRED => array("message"=>"EXPIRED"),
self::STATUS_INTERNAL_SERVER_ERROR => array("message"=>"INTERNAL_SERVER_ERROR")
);
public static function getStatusDataMessage($status){
$rval = "UNKNOWN";
if (array_key_exists($status, self::$STATUS_DATA)){
return self::$STATUS_DATA[$status]["message"];
}
}
/*
* Attribute, setters e getters
*/
/**
* La richiesta relativa a questa risposta
* @var RAPI_Request
*/
private $related_request;
/**
* Restituisce la richiesta associata alla risposta
* @return RAPI_Request
*/
public function getRelatedRequest(){
return $this->related_request;
}
/**
* Lo stato della richiesta.
* In caso di richiesta non valida digest e details saranno vuoti
* @var int
*/
private $status;
/**
* Restituisce lo stato della richiesta
* @return int
*/
public function getStatus(){
return $this->status;
}
/*
* Costruttore
*/
/**
* @param RAPI_Request $relatedRequest La richiesta relativa a questa risposta
* @param string $protocolVersion La versione del protocollo RAPI
* @param RAPI_ResponseDetails $details Il contenuto del messaggio
* @param int $time Timestamp in microsecondi
* @param string $digest Digest per valutare l'autenticità del messaggio
*/
public function __construct(RAPI_Request $relatedRequest, $status, $protocolVersion, RAPI_ResponseDetails $details = NULL, $time = null, $digest = null){
$this->related_request = $relatedRequest;
$this->status = $status;
if ($this->status > 0){
// $details = new stdClass();
// $details->message = self::$STATUS_DATA[$this->status]["message"];
$details = new RAPI_SimpleMessageResponseDetails(self::$STATUS_DATA[$this->status]["message"]);
// $details = "{'message':'".self::$STATUS_DATA[$this->status]["message"]."'}";
}
else if (is_null($details)){
throw new RAPI_Exception("Building a RAPI_Response without passing a valid details object");
}
parent::__construct($protocolVersion, $details, $time, $digest);
}
/*
* Metodi propri della classe
*/
/**
* Ritorna true se la request corrisponde
* alla request che ha generato questa response
* @param RAPI_Request $req
* @return boolean
*/
public function fromSameRequest(RAPI_Request $req){
return $this->related_request->isEqual($req);
}
/**
* La funzione esegue l'operazione solo se la response ha come related una
* request in versione checksum, se le request corrispondono aggiorna
* la versione locale con quella completa, altrimenti lancia eccezione.
* @param RAPI_Request $req
* @return boolean
* @throws RAPI_Exception
*/
public function updateRelatedRequestChecksum(RAPI_Request $req){
if ($this->fromSameRequest($req)){
$this->related_request = $req;
}
else {
throw new RAPI_Exception("Calling function RAPI_Response::updateRelatedRequestChecksum() on not corresponding requests");
}
}
/*
* Abstract
*/
/**
* @see RAPI_Message::generateEncryptionObject()
*/
protected function generateEncryptionObject(){
$rval = $this->generateEncryptionBaseObject();
$rval->status = $this->status;
return $rval;
}
/**
* NOTA: All'oggetto va aggiunta la relatedRequest !
* @see RAPI_Message::isValidObjectForCreation()
*/
protected static function isValidObjectForCreation($obj){
return self::isValidObjectForCreationBase($obj) &&
property_exists($obj, "status") &&
property_exists($obj, "relatedRequest") &&
($obj->relatedRequest instanceof RAPI_Request);
}
/**
* @see RAPI_Message::createFromObject()
*/
public static function createFromObject($obj){
if (self::isValidObjectForCreation($obj)){
$details = null;
if ($obj->status == RAPI_Response::STATUS_OK){
$requestClass = get_class($obj->relatedRequest->getDetails());
$responseClass = $requestClass::getResponseDetailsClass();
$details = new $responseClass($obj->details->data,$obj->details->attachments);
}
return new RAPI_Response($obj->relatedRequest, $obj->status, $obj->version, $details, $obj->time, $obj->digest);
}
else {
throw new RAPI_Exception("Invalid request format");
}
}
}
?>
@@ -0,0 +1,11 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 01/lug/2015
*/
abstract class RAPI_ResponseDetails extends RAPI_MessageDetails{
}
?>
@@ -0,0 +1,18 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 02/lug/2015
*/
/**
*
* @author Riccardo Di Dato
*/
class RAPI_UnreadableRequest extends RAPI_Request{
public function __construct(){
parent::__construct("NONE", "NONE", null, RAPI_Config::RAPI_VERSION, new RAPI_UnreadableRequestDetails());
}
}
?>
@@ -0,0 +1,51 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 02/lug/2015
*/
class RAPI_UnreadableRequestDetails extends RAPI_RequestDetails {
/**
* Returns true if the operation requires an
* operationId (like for writes and deletion)
*/
public static function usesOperationId(){
return false;
}
/**
* Returns the name of the operation used by the request factory (NOT THE RAPI_Operation !!!!!)
* @return string
*/
public static function getOperationName(){
return "UNREADABLE";
}
public function __construct(){
parent::__construct(new stdClass());
}
/**
* @see RAPI_RequestDetails::getArgumentList()
*/
public static function getArgumentList(){
return array();
}
/**
* @see RAPI_RequestDetails::getResponseDetailsClass()
*/
public static function getResponseDetailsClass(){
return "RAPI_EmptyResponseDetails";
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,24 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/lug/2015
*/
class RAPI_EmptyResponseDetails extends RAPI_ResponseDetails{
/**
* @see RAPI_ResponseDetails::getArgumentList()
*/
public static function getArgumentList(){
return array();
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,33 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/lug/2015
*/
class RAPI_SimpleMessageResponseDetails extends RAPI_ResponseDetails{
/**
* @param string $message
*/
public function __construct($message){
$obj = new stdClass();
$obj->message = $message;
parent::__construct($obj);
}
/**
* @see RAPI_ResponseDetails::getArgumentList()
*/
public static function getArgumentList(){
return array("message");
}
/**
* @see RAPI_MessageDetails::getAttachmentList()
*/
public static function getAttachmentList(){
return array();
}
}
?>
@@ -0,0 +1,383 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 29/giu/2015
*/
require_once(dirname(__FILE__)."/client_include.php");
abstract class RAPI_Client {
/**
* @var RAPI_DataStorage
*/
private $dataStorage;
/**
* @var RAPI_Logger
*/
private $logger;
public function __construct(RAPI_Logger $logger, RAPI_DataStorage $dataStorage){
$this->logger = $logger;
$this->dataStorage = $dataStorage;
}
/**
* Wrapper per la funzione del logger, metodo di utilità.
* @param int $level Livello di log
* @param string $message Messaggio da scrivere nel log
*/
private function log($level, $message){
$this->logger->log($level, $message);
}
/**
* Genera un warning di sicurezza.
* @param int $level Importanza del warning
* @param string $message Messaggio da scrivere nel log
* @param RAPI_Response $data RAPI_Response che ha generato il warning
*/
private function generateSecurityWarning($severity, $message, RAPI_Response $request){
$this->logger->generateSecurityWarning($severity, $message, $request);
}
/**
* Effettua la chiamata al server per la richiesta inserita.
* Se la richiesta fallisce lancia eccezione e mette la richiesta in coda (SOLO SE USA OPERATION_ID).
* @param RAPI_RequestDetails $det
* @throws RAPI_ClientException (ANY)
* @return RAPI_ResponseDetails
*/
public function request(RAPI_RequestDetails $details){
try {
$req = $this->getRequestFromRequestDetails($details);
$response = $this->executeRequest($req);
$responseDetails = $response->getDetails();
}
catch (Exception $ex){
if ($details->usesOperationId()){
$this->dataStorage->queueUncompletedRequest($req->getOperationId(),$details);
}
throw $ex;
}
return $responseDetails;
}
/**
* Esegue una richiesta (in caso di fallimento lancia eccezione)
* @param RAPI_Request $req
* @throws RAPI_ClientException
* @return RAPI_Response
*/
private function executeRequest(RAPI_Request $req){
$this->openConnection();
$this->sendMessage($req->getEncryption());
$this->sendMessage("\n");
$attachmentList = $req->getAttachmentList();
if (sizeof($attachmentList)>0){
foreach ($attachmentList as $attachment){
$msg = $this->getMessage(2048);
if (strcmp($msg, "<< ----- ACK / $attachment ----- >>\n")!=0){
$this->logger->log(RAPI_Logger::LOG_LEVEL_ERROR, "Invalid protocol use, client not sending ACK message for attachment '$attachment'. The request will be rejected");
throw new RAPI_ClientException(RAPI_ClientException::INVALID_UNPARSABLE);
}
$buffer = "";
$filePath = $req->getAttachmentLocalFileReference($attachment);
$fh = fopen($filePath, "rb");
do {
$buffer = fread($fh, 32768);
$this->sendMessage($buffer);
}
while(!feof($fh));
// while ( ($buffer = fread($fh, 2048)) !== false ) {
// $this->sendMessage($buffer);
// }
fclose($fh);
$this->sendMessage("\n");
}
}
$textResponse = $this->getMessage();
$response = RAPI_Response::fromEncrypted($textResponse,array("relatedRequest"=>$req));
$this->validateResponse($response);
$attachmentList = $response->getAttachmentList();
if ($response->getStatus() == RAPI_Response::STATUS_OK && sizeof($attachmentList)>0){
foreach ($attachmentList as $attachment){
$data = $response->getAttachmentData($attachment);
$buffer = "";
$this->sendMessage("<< ----- ACK / $attachment ----- >>");
$this->sendMessage("\n");
$filePath = $this->getReceivedAttachmentPath()."/".uniqid($attachment."_");
$fh = fopen($filePath, "wb");
$next = $this->getMessage(32768);
while ($next!==false) {
$current = $next;
$length = strlen($current);
$next = $this->getMessage(32768);
if ($next===false){
$length = $length-1;
}
fwrite($fh,$current,$length);
}
// while ( ($buffer = $this->getMessage(2048)) !== false ){
// fwrite($fh,$buffer);
// }
fclose($fh);
if (filesize($filePath)!=$data->size){
$this->logger->log(RAPI_Logger::LOG_LEVEL_ERROR, "The received file has invalid size for attachment '$attachment'. The request will be rejected");
throw new RAPI_ClientException(RAPI_ClientException::INVALID_UNPARSABLE);
}
if ( strcmp(md5_file($filePath),$data->md5)!=0 ){
$this->logger->log(RAPI_Logger::LOG_LEVEL_ERROR, "The received file has invalid MD5 for attachment '$attachment'. The request will be rejected");
throw new RAPI_ClientException(RAPI_ClientException::INVALID_UNPARSABLE);
}
$response->setAttachmentLocalFileReference($attachment,$filePath);
}
}
$this->closeConnection();
return $response;
}
// /**
// * Esegue una richiesta e restituisce la risposta
// * @param RAPI_Request $req
// * @param string $forceOperationId se null usa il prossimo libero, altrimenti usa quello ricevuto
// * @throws RAPI_ClientException
// * @return RAPI_Response
// */
// private function getResponse(RAPI_Request $req){
// $ans = $this->sendMessage($req->getEncryption());
// try {
// $response = RAPI_Response::fromEncrypted($ans,array("relatedRequest"=>$req));
// }
// catch (RAPI_Exception $rex){
// $this->log(RAPI_Logger::LOG_LEVEL_ERROR,"Impossible to parse response. Reason: '".$rex->getMessage()."'");
// throw new RAPI_ClientException(RAPI_ClientException::INVALID_UNPARSABLE);
// }
// $this->validateResponse($response);
// return $response;
// }
/**
* Riprova ad eseguire le operazioni in pending.
* Limit limita il numero di operazioni da riprovare ad eseguire.
* @param int $limit per limitare la quantità di operazioni
* @throws RAPI_ClientException
*/
public function executePendingRequests($limit = null){
$reqsDetails = $this->dataStorage->getUncompletedRequests($limit);
if (sizeof($reqsDetails)>0){
$excs = array();
foreach ($reqsDetails as $id=>$details){
try {
$req = $this->getRequestFromRequestDetails($details,$id);
$resp = $this->executeRequest($req);
$this->dataStorage->onRequestCompletedFromQueue($id);
}
catch (Exception $ex){
$excs[] = "(".$ex->getMessage().")";
$this->dataStorage->onRequestFailedFromQueue($id);
}
}
if (sizeof($excs)>0){
$this->log(RAPI_Logger::LOG_LEVEL_ERROR,"Errors while executing queue in ".sizeof($excs)." requests. Messages: ".implode(", ", $excs));
throw new RAPI_ClientException(RAPI_ClientException::INVALID_UNPARSABLE);
}
}
}
// /**
// * Restituisce la stringa col messaggio
// * @param string $msg
// * @returns string
// */
// private function sendMessage($msg){
// $service_port = getservbyname('rapi', 'tcp');
// $address = RAPI_Config::RAPI_SERVER_ADDRESS;
// $this->log(RAPI_Logger::LOG_LEVEL_INFO,"Connecting to '$address:$service_port'");
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"Creating TCP socket");
// $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// if ($socket === false) {
// $this->log(RAPI_Logger::LOG_LEVEL_ERROR,"Impossible to create TCP socket. Reason: '".socket_strerror(socket_last_error())."'");
// throw new RAPI_ClientException(RAPI_ClientException::CONNECTION_ERROR);
// }
// else {
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"TCP Socket created successfully");
// }
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"Connecting to '$address:$service_port'");
// $result = socket_connect($socket, $address, $service_port);
// if ($result === false) {
// $this->log(RAPI_Logger::LOG_LEVEL_ERROR,"Impossible to connect to '$address:$service_port'. Reason: '".socket_strerror(socket_last_error($socket))."'");
// throw new RAPI_ClientException(RAPI_ClientException::CONNECTION_ERROR);
// }
// else {
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"TCP Socket connection complete");
// }
// $this->log(RAPI_Logger::LOG_LEVEL_INFO,"Sending request to '$address:$service_port'");
// socket_write($socket, $msg, strlen($msg));
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"Reading response from '$address:$service_port'");
// $out = '';
// $acc = '';
// while ($out = socket_read($socket, 2048)) {
// $acc .= $out;
// }
// $this->log(RAPI_Logger::LOG_LEVEL_DEBUG,"Response from '$address:$service_port' complete");
// $this->log(RAPI_Logger::LOG_LEVEL_INFO,"Closing connection to '$address:$service_port'");
// socket_close($socket);
// return $acc;
// }
// /**
// * Genera una RAPI_Request a partire da una RAPI_RequestDetails.
// * @param RAPI_RequestDetails $details
// * @param string $forceOperationId se null usa il prossimo libero, altrimenti usa quello ricevuto
// * @return RAPI_Request
// */
// private function wrapRequest(RAPI_RequestDetails $details, $forceOperationId = null){
// $account = $this->dataStorage->getRapiAccount();
// $user = $this->dataStorage->getRapiUser();
// $operationId = $details::usesOperationId()?(is_null($forceOperationId)?$this->dataStorage->getNextOperationId():$forceOperationId):null;
// $protocolVersion = RAPI_Config::RAPI_VERSION;
// $req = new RAPI_Request($account, $user, $operationId, $protocolVersion, $details);
// $req->setDigest(RAPI_CryptUtils::getDigestForMessage($req, $this->dataStorage->getRapiPassphrase()));
// return $req;
// }
/**
* Genera una RAPI_Request a partire da una RAPI_RequestDetails.
* @param RAPI_RequestDetails $details
* @param string $forceOperationId se null usa il prossimo libero, altrimenti usa quello ricevuto
* @return RAPI_Request
*/
private function getRequestFromRequestDetails(RAPI_RequestDetails $details, $forceOperationId = null){
$account = $this->dataStorage->getRapiAccount();
$user = $this->dataStorage->getRapiUser();
$operationId = null;
if ($details::usesOperationId()){
if (is_null($forceOperationId)){
$operationId = $this->dataStorage->getNextOperationId();
$this->dataStorage->setMaxOperationId($operationId);
}
else {
$operationId = $forceOperationId;
}
}
$protocolVersion = RAPI_Config::RAPI_VERSION;
$req = new RAPI_Request($account, $user, $operationId, $protocolVersion, $details);
$req->setDigest(RAPI_CryptUtils::getDigestForMessage($req, $this->dataStorage->getRapiPassphrase()));
return $req;
}
/**
* Valuta che la versione del protocollo utilizzata nella risposta sia la stessa del client.
* Lancia eccezione in caso di richiesta non valida
* @param RAPI_Response $req La risposta
* @throws RAPI_ClientException (INVALID_PROTOCOL)
*/
private function validateProtocolVersion(RAPI_Response $resp){
if (RAPI_Config::RAPI_VERSION != $resp->getProtocolVersion()){
$this->log(RAPI_Logger::LOG_LEVEL_WARNING, "Invalid protocol version detected (".$resp->getProtocolVersion()."). The response will be rejected");
throw new RAPI_ClientException(RAPI_ClientException::INVALID_PROTOCOL);
}
}
/**
* Valuta che la risposta sia in status OK.
* Lancia eccezione in caso di status non valido
* @param RAPI_Response $req La risposta
* @throws RAPI_ClientException (INVALID_STATUS)
*/
private function validateStatus(RAPI_Response $resp){
if (RAPI_Response::STATUS_OK != $resp->getStatus()){
$this->log(RAPI_Logger::LOG_LEVEL_INFO, "Invalid status detected (".RAPI_Response::getStatusDataMessage($resp->getStatus())."). The response will be rejected");
throw new RAPI_ClientException(RAPI_ClientException::INVALID_STATUS);
}
}
/**
* Valuta che il digest della risposta sia valido.
* Lancia eccezione in caso di digest non valido
* @param RAPI_Response $req La risposta
* @throws RAPI_ClientException (INVALID_DIGEST)
*/
private function validateDigest(RAPI_Response $resp){
if ( strcmp("", $resp->getDigest())==0 ){
$this->log(RAPI_Logger::LOG_LEVEL_INFO, "Invalid digest detected. The incident will be reported");
$this->generateSecurityWarning(RAPI_Logger::WARNING_SEVERITY_HIGH, "Rejecting a connection because has no digest", $resp);
throw new RAPI_ClientException(RAPI_ClientException::INVALID_DIGEST);
}
else if ($resp->getDigest() != RAPI_CryptUtils::getDigestForMessage($resp, $this->dataStorage->getRapiPassphrase())){
$this->log(RAPI_Logger::LOG_LEVEL_INFO, "Invalid digest detected. The incident will be reported");
$this->generateSecurityWarning(RAPI_Logger::WARNING_SEVERITY_CRITICAL, "Rejecting a connection because has an invalid digest", $resp);
throw new RAPI_ClientException(RAPI_ClientException::INVALID_DIGEST);
}
}
/**
* Effettua i vari controlli sulla risposta.
* Lancia eccezione in caso di risposta non valida
* @param RAPI_Response $req La risposta
* @throws RAPI_ClientException (INVALID_DIGEST INVALID_STATUS INVALID_PROTOCOL)
*/
private function validateResponse(RAPI_Response $resp){
$this->validateProtocolVersion($resp);
$this->validateStatus($resp);
$this->validateDigest($resp);
}
/**
* Opens a connection (socket, file stream ecc)
*/
protected abstract function openConnection();
/**
* Closes a connection (socket, file stream ecc)
*/
protected abstract function closeConnection();
/**
* Sends a message
*/
protected abstract function sendMessage($msg);
/**
* Reads a message. BufferSize rappresenta la dimensione del buffer da utilizzare,
* la funzione ritorna false se non c'è niente da leggere
*/
protected abstract function getMessage($bufferSize = null);
/**
* Write attachment step
*/
protected abstract function getReceivedAttachmentPath();
}
?>
@@ -0,0 +1,34 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 01/lug/2015
*/
class RAPI_ClientException extends RAPI_Exception{
const CONNECTION_ERROR = 1;
const INVALID_PROTOCOL = 2;
const INVALID_STATUS = 3;
const INVALID_DIGEST = 4;
const INVALID_UNPARSABLE = 5;
private $status;
private static $ERROR_NAMES = array(
self::CONNECTION_ERROR => "CONNECTION_ERROR",
self::INVALID_PROTOCOL => "INVALID_PROTOCOL",
self::INVALID_STATUS => "INVALID_STATUS",
self::INVALID_DIGEST => "INVALID_DIGEST",
self::INVALID_UNPARSABLE => "INVALID_UNPARSABLE"
);
public function __construct($status){
$this->status = $status;
parent::__construct("RAPI_ClientException 'Status $status' - ".self::$ERROR_NAMES[$this->status]);
}
public function getStatus (){
return $this->status;
}
}
?>
@@ -0,0 +1,120 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 02/lug/2015
*/
/**
* Classe a cui è possibile aggiungere metodi a partire da RAPI_Request.
* Utilizzare defineRequest per aggiungere metodi.
*
* @author Riccardo Di Dato
*
*/
class RAPI_ClientHelper {
private $client;
private $requests = array();
public function __construct(RAPI_Client $client){
$this->client = $client;
}
/**
* Chiama il metodo richiesto e ne fetcha il risultato.
*
* @param string $name Nome del metodo
* @param mixed $values Argomenti da passare al metodo
* @throws RAPI_ClientException Rilancia le eccezioni del client
* @throws RAPI_Exception Se il metodo non esiste o gli argomenti non sono validi o se il fetcher lancia eccezione
* @return mixed In base al fetcher
*/
public function __call($name, array $values){
if (!array_key_exists($name, $this->requests)){
throw new RAPI_Exception("Call to undefined function RAPI_ClientHelper::$methodName");
}
$resp = $this->client->request($this->generateDetails($name, $values));
return $this->fetchResponse($name, $resp);
}
/**
* Aggiunge un metodo all'helper.
*
* @param string $name Il nome con cui si desidera chiamare il metodo
* @param string $className Nome della RAPI_RequestDetails associata alla request
* @param RAPI_ResponseFetcher $respFetcher Il metodo per fetchare la risposta
*/
public function defineRequest($name, $className, RAPI_ResponseFetcher $respFetcher){
if (class_exists($className) && (is_subclass_of($className, "RAPI_RequestDetails") ) ){
$this->requests[$name]['class'] = $className;
$this->requests[$name]['fetcher'] = $respFetcher;
}
else {
if (!class_exists($className)){
throw new RAPI_Exception("Invalid method definition. Undefined class '$className'");
}
else {
throw new RAPI_Exception("Invalid method definition. Class '$className' is not a RAPI_RequestDetails");
}
}
}
/**
* Genera una RAPI_RequestDetails a partire dal nome del metodo chiamato e dagli
* argomenti da passargli.
* Lancia eccezione se il numero di argomenti passati non corrisponde a quelli
* del metodo chiamato o se il metodo non esiste.
*
* @param string $methodName Nome del metodo chiamato
* @param array $args Gli argomenti da passare alla RAPI_RequestDetails
* @throws RAPI_Exception Se il metodo non esiste o se $args non è valido
* @return RAPI_RequestDetails I details da utilizzare per il metodo chiamato
*/
private function generateDetails($methodName, array $args){
$className = $this->requests[$methodName]['class'];
$argList = $className::getArgumentList();
$attList = $className::getAttachmentList();
if (sizeof($args) != (sizeof($argList) + sizeof($attList)) ){
$paramString = implode(", ",array_map(function($d){return "\$".$d."";}, array_merge($argList,$attList)));
throw new RAPI_Exception("Invalid arguments passed to function RAPI_ClientHelper::$methodName($paramString). (Received ".sizeof($args)." arguments)");
}
$constructObj = new stdClass();
$i = 0;
foreach ($argList as $argName){
$constructObj->$argName = $args[$i++];
}
$constructAtt = array();
foreach ($attList as $argName){
$localFile = $args[$i++];
$attData = new stdClass();
$attData->name = $argName;
$attData->size = filesize($localFile);
$attData->md5 = md5_file($localFile);
$attData->localReference = $localFile;
$constructAtt[] = $attData;
}
return new $className($constructObj,$constructAtt);
}
/**
* Chiama il fetcher del metodo passandogli la RAPI_ResponseDetails.
* Fetcha il risultato e lo restituisce.
*
* @param string $methodName Nome del metodo chiamato
* @param RAPI_ReponseDetails $response Risposta da fetchare
* @throws RAPI_Exception Se il metodo non esiste o se il fetcher lancia eccezione
* @return mixed In base a ciò che ritorna il fetch
*/
private function fetchResponse($methodName, RAPI_ResponseDetails $response){
// if (!array_key_exists($methodName, $this->requests)){
// throw new RAPI_Exception("Invalid call to RAPI_ClientHelper::fetchResponse for method '$methodName'. (The method is undefined)");
// }
return $this->requests[$methodName]['fetcher']($response);
}
}
?>
@@ -0,0 +1,70 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 29/giu/2015
*/
interface RAPI_DataStorage {
/**
* Returns the passphrase
* @return string
*/
public function getRapiPassphrase();
/**
* Returns the account
* @return string
*/
public function getRapiAccount();
/**
* Returns the user
* @return string
*/
public function getRapiUser();
/**
* Returns the next valid operationId
* @return id
*/
public function getNextOperationId();
/**
* Set max operationId
* @param int $id
*/
public function setMaxOperationId($id);
/**
* Queue uncompleted operations
* @param string $id operationID
* @param RAPI_RequestDetails $req
*/
public function queueUncompletedRequest($id, RAPI_RequestDetails $req);
/**
* Returns the list of uncompleted requests. The array keys are the operationIds.
*
* NOTE: This function doesn't remove items from the list, to delete
* elements from the list use RAPI_DataStorage::onRequestCompletedFromQueue()
* @param int $limit null for no limit
* @return RAPI_RequestDetails[]
*/
public function getUncompletedRequests($limit = null);
/**
* Operazione eseguita quando la richiesta viene completata con SUCCESSO dalla coda
* @param string $id operationID
*/
public function onRequestCompletedFromQueue($id);
/**
* Operazione eseguita quando la richiesta fallisce dalla coda
* @param string $id operationID
*/
public function onRequestFailedFromQueue($id);
}
?>
@@ -0,0 +1,20 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/giu/2015
*/
require_once(dirname(__FILE__)."/../include.php");
require_once(dirname(__FILE__)."/RAPI_ClientException.php");
require_once(dirname(__FILE__)."/RAPI_DataStorage.php");
require_once(dirname(__FILE__)."/RAPI_ClientHelper.php");
require_once(dirname(__FILE__)."/request_helper/RAPI_ResponseFetcher.php");
require_once(dirname(__FILE__)."/request_helper/RAPI_SingleValueResponseFetcher.php");
require_once(dirname(__FILE__)."/request_helper/RAPI_StandardResponseFetcher.php");
?>
@@ -0,0 +1,13 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 02/lug/2015
*/
interface RAPI_ResponseFetcher {
public function __invoke(RAPI_ResponseDetails $resp);
}
?>
@@ -0,0 +1,26 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 09/lug/2015
*/
class RAPI_SingleValueResponseFetcher implements RAPI_ResponseFetcher {
private $paramName;
private $callback;
public function __construct($paramName, callable $callback = null){
$this->paramName = $paramName;
$this->callback = $callback;
}
public function __invoke(RAPI_ResponseDetails $resp){
$rval = $resp->getData()->{$this->paramName};
if (!is_null($this->callback)){
$cb = $this->callback;
$rval = $cb($rval);
}
return $rval;
}
}
?>
@@ -0,0 +1,33 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 09/lug/2015
*/
class RAPI_StandardResponseFetcher implements RAPI_ResponseFetcher {
private $callback;
public function __construct(callable $callback = null){
$this->callback = $callback;
}
public function __invoke(RAPI_ResponseDetails $resp){
$rval = new stdClass();
$rval->data = $resp->getData();
$rval->attachments = array();
$attList = $resp->getAttachmentList();
if (sizeof($attList)>0){
foreach ($attList as $att){
$rval->attachments[$att] = $resp->getAttachmentLocalFileReference($att);
}
}
if (!is_null($this->callback)){
$cb = $this->callback;
$rval = $cb($rval);
}
return $rval;
}
}
?>
+18
View File
@@ -0,0 +1,18 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 23/feb/2016
*/
require_once(dirname(__FILE__)."/cbsClient/cbs.client.include.php");
require_once(dirname(__FILE__)."/FDN2CBS_Logger.php");
require_once(dirname(__FILE__)."/FDN2CBS_DataStorage.php");
$cbsLogger = new FDN2CBS_Logger();
$cbsDataStorage = new FDN2CBS_DataStorage();
$cbsClient = new CBSClient($cbsLogger, $cbsDataStorage,GlobalVariables::get("config")->paths->backupTmp);
GlobalVariables::set("backupClient",$cbsClient);
?>
+191
View File
@@ -0,0 +1,191 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
abstract class Constrained implements ConstrainedInterface{
public static $SET_BEHAVIOURS = array(
self::SET_BEHAVIOUR_NORMAL => array("label"=>"Normal"),
self::SET_BEHAVIOUR_IGNORE => array("label"=>"Ignore"),
self::SET_BEHAVIOUR_THROW => array("label"=>"Throw Exception")
);
public static $UNSET_BEHAVIOURS = array(
self::UNSET_BEHAVIOUR_NORMAL => array("label"=>"Normal"),
self::UNSET_BEHAVIOUR_IGNORE => array("label"=>"Ignore"),
self::UNSET_BEHAVIOUR_THROW => array("label"=>"Throw Exception")
);
public static $GET_BEHAVIOURS = array(
self::GET_BEHAVIOUR_NORMAL => array("label"=>"Normal"),
self::GET_BEHAVIOUR_EMPTY => array("label"=>"Empty"),
self::GET_BEHAVIOUR_THROW => array("label"=>"Throw Exception")
);
private $constraints = array();
public function __construct(){
$this->createSetBehaviour("*", self::SET_BEHAVIOUR_NORMAL);
$this->createGetBehaviour("*", self::GET_BEHAVIOUR_NORMAL);
$this->createUnsetBehaviour("*", self::UNSET_BEHAVIOUR_NORMAL);
}
public function createSetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null){
// if (strpos($key, ".")!== false){
// $matches = array();
// if (!preg_match("/^([^.]+)\.(.+)$/", $key, $matches)){
// throw new CoreException("Invalid key format passed to ".get_class($this)."::createSetBehaviour ($key)");
// }
// $myKey = $matches[1];
// $childKey = $matches[2];
// $child = $this->getInternal($myKey);
// if (is_null($child)){
// $this->setInternal($myKey, new ConstrainedMemoryObject());
// }
// if ($child instanceof Constrained){
// $child->createSetBehaviour($childKey, $behaviour, $callbackClass);
// }
// else {
// throw new CoreException("Invalid key passed to ".get_class($this)."::createSetBehaviour. Setting a child constraint on a non constrained element.");
// }
// }
// else {
if (!array_key_exists($behaviour, self::$SET_BEHAVIOURS)){
throw new CoreException("Invalid behaviour parameter passed to ".get_class($this)."::createSetBehaviour ($behaviour)");
}
if (!array_key_exists($key,$this->constraints)){
$this->constraints[$key] = new stdClass();
}
$this->constraints[$key]->set = new stdClass();
$this->constraints[$key]->set->behaviour = $behaviour;
$this->constraints[$key]->set->callbackClass = $callbackClass;
// }
}
public function createGetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null){
if (!array_key_exists($behaviour, self::$GET_BEHAVIOURS)){
throw new CoreException("Invalid behaviour parameter passed to ".get_class($this)."::createGetBehaviour ($behaviour)");
}
if (!array_key_exists($key,$this->constraints)){
$this->constraints[$key] = new stdClass();
}
$this->constraints[$key]->get = new stdClass();
$this->constraints[$key]->get->behaviour = $behaviour;
$this->constraints[$key]->get->callbackClass = $callbackClass;
}
public function createUnsetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null){
if (!array_key_exists($behaviour, self::$UNSET_BEHAVIOURS)){
throw new CoreException("Invalid behaviour parameter passed to ".get_class($this)."::createUnsetBehaviour ($behaviour)");
}
if (!array_key_exists($key,$this->constraints)){
$this->constraints[$key] = new stdClass();
}
$this->constraints[$key]->unset = new stdClass();
$this->constraints[$key]->unset->behaviour = $behaviour;
$this->constraints[$key]->unset->callbackClass = $callbackClass;
}
public function setConstrained($key, $value){
try {
$constraint = $this->constraints["*"]->set;
if (array_key_exists($key, $this->constraints) && property_exists($this->constraints[$key], "set")){
$constraint = $this->constraints[$key]->set;
}
$constraint = $this->constraints[$key]->set;
switch ($constraint->behaviour){
case self::SET_BEHAVIOUR_NORMAL:
$this->setInternal($key, $value);
break;
case self::SET_BEHAVIOUR_THROW:
throw new ConstraintException("set",$key,$value);
break;
case self::SET_BEHAVIOUR_IGNORE:
default:
break;
}
if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
$this->setBase($constraint->callbackClass->executeSetCallback($this->getBase(), $key, $value));
}
}
catch (ConstraintException $cex){
throw $this->addPathToChildException($cex);
}
}
public function getConstrained($key){
try {
$rval = null;
if (array_key_exists($key, $this->constraints) && property_exists($this->constraints[$key], "get")){
$constraint = $this->constraints[$key]->get;
switch ($constraint->behaviour){
case self::GET_BEHAVIOUR_THROW:
throw new ConstraintException("get",$key);
break;
case self::GET_BEHAVIOUR_NORMAL:
$rval = $this->getInternal($key);
break;
case self::GET_BEHAVIOUR_EMPTY:
default:
break;
}
if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
$rval = $constraint->callbackClass->executeGetCallback($this->getBase(), $key);
}
}
else {
$rval = $this->getInternal($key);
}
return $rval;
}
catch (ConstraintException $cex){
throw $this->addPathToChildException($cex);
}
}
public function unsetConstrained($key){
try {
if (array_key_exists($key, $this->constraints) && property_exists($this->constraints[$key], "unset")){
$constraint = $this->constraints[$key]->unset;
switch ($constraint->behaviour){
case self::UNSET_BEHAVIOUR_NORMAL:
$this->unsetInternal($key);
break;
case self::UNSET_BEHAVIOUR_THROW:
throw new ConstraintException("unset",$key);
break;
case self::UNSET_BEHAVIOUR_IGNORE:
default:
break;
}
if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
$this->setBase($constraint->callbackClass->executeUnsetCallback($this->getBase(), $key));
}
}
else {
$this->unsetInternal($key);
}
}
catch (ConstraintException $cex){
throw $this->addPathToChildException($cex);
}
}
protected function replicateConstraints(Constrained $oth){
$this->constraints = clone $oth->constraints;
}
protected abstract function addPathToChildException($myKey, ConstraintException $ex);
protected abstract function setInternal($key,$value);
protected abstract function getInternal($key);
protected abstract function unsetInternal($key);
protected abstract function setBase($base);
}
?>
@@ -0,0 +1,67 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
class ConstrainedArrayObject extends Constrained implements ArrayAccess {
private $base = array();
public function __construct(array $base){
parent::__construct();
$this->setBase($base);
}
protected function setBase($base){
foreach ($base as $key=>$value){
$this->base[$key] = ConstrainedFactory::build($value);
}
}
public function getBase(){
return $this->base;
}
protected function addPathToChildException($myKey, ConstraintException $ex){
$newKey = $myKey."[".$ex->getRelatedKey()."]";
return new ConstraintException($ex->getRelatedOperation(), $newKey, $ex->getRelatedValue());
}
protected function setInternal($key,$value){
if (is_null($key)) {
$this->base[] = $value;
}
else {
$this->base[$key] = $value;
}
}
protected function getInternal($key){
return $this->offsetExists($key) ? $this->base[$key] : null;
}
protected function unsetInternal($key){
unset($this->base[$key]);
}
// ArrayAccess methods
public function offsetExists($key) {
return array_key_exists($key, $this->base);
}
public function offsetSet($key, $value) {
$this->setConstrained($key, $value);
}
public function offsetUnset($key) {
$this->unsetConstrained($key);
}
public function offsetGet($key) {
$this->getConstrained($key);
}
}
?>
@@ -0,0 +1,41 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
interface ConstrainedBehaviour {
/**
* Esegue il callback per le funzioni di set, restituisce il valore finale di constrainedOriginal.
* ATTENZIONE!! LA funzione è in grado di modificare anche parametri diversi da
* quello chiamato con key. Questo comportamento è intenzionale in quanto
* in alcuni casi potrebbe essere voluto.
* @param stdClass $constrainedOriginal il modello su cui chiamare la set
* @param string $key la chiave da utilizzare per il set
* @param mixed $value il valore da settare
* @return stdClass il nuovo constrained original a fine operazione
*/
public function executeSetCallback($constrainedOriginal, $key, $value);
/**
* Esegue un callback per le funzioni di get, deve restituire il valore da ritornare con
* la funzione originale.
* @param stdClass $constrainedOriginal il modello su cui chiamare la get
* @param string $key la chiave da utilizzare per la get
* @return mixed il valore da ritornare
*/
public function executeGetCallback($constrainedOriginal, $key);
/**
* Esegue un callback per le funzioni di unset, restituisce il valore finale di constrainedOriginal.
* ATTENZIONE!! LA funzione è in grado di modificare anche parametri diversi da
* quello chiamato con key. Questo comportamento è intenzionale in quanto
* in alcuni casi potrebbe essere voluto.
* @param stdClass $constrainedOriginal il modello su cui chiamare la get
* @param string $key la chiave da utilizzare per la get
* @return mixed il valore da ritornare
*/
public function executeUnsetCallback($constrainedOriginal, $key);
}
?>
@@ -0,0 +1,37 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
class ConstrainedFactory {
public static function build($obj){
$rval = $obj;
if ($obj instanceof ConstrainedInterface){
$rval = clone $obj;
}
else if (is_object($obj)){
$rval = new ConstrainedObject($obj);
}
else if (is_array($obj)){
$rval = new ConstrainedArrayObject($obj);
}
return $rval;
}
public static function debuild($obj){
$rval = $obj;
if ($obj instanceof ConstrainedInterface){
$rval = new stdClass();
$tmp = $obj->getBase();
foreach ($tmp as $key=>$val){
$rval->$key = self::debuild($val);
}
}
return $rval;
}
}
?>
@@ -0,0 +1,32 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
interface ConstrainedInterface {
const SET_BEHAVIOUR_NORMAL = 1;
const SET_BEHAVIOUR_IGNORE = 2;
const SET_BEHAVIOUR_THROW = 3;
const UNSET_BEHAVIOUR_NORMAL = 1;
const UNSET_BEHAVIOUR_IGNORE = 2;
const UNSET_BEHAVIOUR_THROW = 3;
const GET_BEHAVIOUR_NORMAL = 1;
const GET_BEHAVIOUR_EMPTY = 2;
const GET_BEHAVIOUR_THROW = 3;
public function setConstrained($key, $value);
public function getConstrained($key);
public function unsetConstrained($key);
public function createSetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null);
public function createGetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null);
public function createUnsetBehaviour($key, $behaviour, ConstrainedBehaviour $callbackClass = null);
public function getBase();
}
?>
@@ -0,0 +1,11 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
class ConstrainedMemoryObject extends Constrained{
}
?>
@@ -0,0 +1,220 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
class ConstrainedObject extends Constrained {
private $base;
public function __construct($base){
parent::__construct();
$this->setBase($base);
}
protected function setBase($base){
$this->base = new stdClass();
foreach ($base as $key=>$value){
$this->base->$key = ConstrainedFactory::build($value);
}
}
public function getBase(){
return $this->base;
}
protected function addPathToChildException($myKey, ConstraintException $ex){
$newKey = $myKey."->".$ex->getRelatedKey();
return new ConstraintException($ex->getRelatedOperation(), $newKey, $ex->getRelatedValue());
}
protected function setInternal($key,$value){
return $this->base->$key = $value;
}
protected function getInternal($key){
return $this->base->$key;
}
protected function unsetInternal($key){
unset($this->base->$key);
}
public function __set($key,$value){
return $this->setConstrained($key, $value);
}
public function __get($key){
return $this->getConstrained($key);
}
public function __unset($key){
return $this->unsetConstrained($key);
}
}
// class ConstrainedObject {
// const SET_BEHAVIOUR_NORMAL = 1;
// const SET_BEHAVIOUR_IGNORE = 2;
// const SET_BEHAVIOUR_THROW = 100;
// const UNSET_BEHAVIOUR_NORMAL = 1;
// const UNSET_BEHAVIOUR_IGNORE = 2;
// const UNSET_BEHAVIOUR_THROW = 100;
// const GET_BEHAVIOUR_NORMAL = 1;
// const GET_BEHAVIOUR_EMPTY = 2;
// const GET_BEHAVIOUR_THROW = 100;
// private $original;
// private $constraints = array();
// public function __construct($original){
// $this->original = $original;
// }
// public function __set($key, $value){
// if ($value instanceof ArrayObject){
// $value = $value->getArrayCopy();
// }
// if (array_key_exists($key, $this->constraints)){
// $constraint = $this->constraints[$key]->set;
// switch ($constraint->behaviour){
// case self::SET_BEHAVIOUR_NORMAL:
// $this->original->$key = $value;
// break;
// case self::SET_BEHAVIOUR_THROW:
// throw new ConstraintException("Constraint violation: impossible to set field '$key'");
// break;
// case self::SET_BEHAVIOUR_IGNORE:
// default:
// break;
// }
// if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
// $this->original = $constraint->callbackClass->executeSetCallback($this->original, $key, $value);
// }
// }
// else {
// $this->original->$key = $value;
// }
// }
// public function __get($key){
// $rval = null;
// if (array_key_exists($key, $this->constraints)){
// $constraint = $this->constraints[$key]->get;
// switch ($constraint->behaviour){
// case self::GET_BEHAVIOUR_THROW:
// throw new ConstraintException("Constraint violation: impossible to get field '$key'");
// break;
// case self::GET_BEHAVIOUR_NORMAL:
// $rval = $this->original->$key;
// break;
// case self::GET_BEHAVIOUR_EMPTY:
// default:
// break;
// }
// if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
// $rval = $constraint->callbackClass->executeGetCallback($this->original, $key);
// }
// }
// else {
// $rval = $this->original->$key;
// }
// if (is_array($rval)){
// $rval = new ArrayObject($rval);
// }
// return $rval;
// }
// public function __unset($key){
// if (array_key_exists($key, $this->constraints)){
// $constraint = $this->constraints[$key]->unset;
// switch ($constraint->behaviour){
// case self::UNSET_BEHAVIOUR_NORMAL:
// unset($this->original->$key);
// break;
// case self::UNSET_BEHAVIOUR_THROW:
// throw new ConstraintException("Constraint violation: impossible to unset field '$key'");
// break;
// case self::UNSET_BEHAVIOUR_IGNORE:
// default:
// break;
// }
// if (property_exists($constraint, "callbackClass") && !is_null($constraint->callbackClass)){
// $this->original = $constraint->callbackClass->executeUnsetCallback($this->original, $key);
// }
// }
// else {
// unset($this->original->$key);
// }
// }
// public function createSetBehaviour($key, $behaviour, ConstraintObjectBehaviourCallable $callbackClass = null){
// if (!array_key_exists($key,$this->constraints)){
// $this->constraints[$key] = new stdClass();
// }
// $this->constraints[$key]->set = new stdClass();
// if ($behaviour < self::SET_BEHAVIOUR_NORMAL){
// $behaviour = self::SET_BEHAVIOUR_NORMAL;
// }
// else if ($behaviour > self::SET_BEHAVIOUR_THROW){
// $behaviour = self::SET_BEHAVIOUR_THROW;
// }
// $this->constraints[$key]->set->behaviour = $behaviour;
// $this->constraints[$key]->set->callbackClass = $callbackClass;
// }
// public function createGetBehaviour($key, $behaviour, ConstraintObjectBehaviourCallable $callbackClass = null){
// if (!array_key_exists($key,$this->constraints)){
// $this->constraints[$key] = new stdClass();
// }
// $this->constraints[$key]->get = new stdClass();
// if ($behaviour < self::GET_BEHAVIOUR_NORMAL){
// $behaviour = self::GET_BEHAVIOUR_NORMAL;
// }
// else if ($behaviour > self::GET_BEHAVIOUR_THROW){
// $behaviour = self::GET_BEHAVIOUR_THROW;
// }
// $this->constraints[$key]->get->behaviour = $behaviour;
// $this->constraints[$key]->get->callbackClass = $callbackClass;
// }
// public function createUnsetBehaviour($key, $behaviour, ConstraintObjectBehaviourCallable $callbackClass = null){
// if (!array_key_exists($key,$this->constraints)){
// $this->constraints[$key] = new stdClass();
// }
// $this->constraints[$key]->unset = new stdClass();
// if ($behaviour < self::UNSET_BEHAVIOUR_NORMAL){
// $behaviour = self::UNSET_BEHAVIOUR_NORMAL;
// }
// else if ($behaviour > self::UNSET_BEHAVIOUR_THROW){
// $behaviour = self::UNSET_BEHAVIOUR_THROW;
// }
// $this->constraints[$key]->unset->behaviour = $behaviour;
// $this->constraints[$key]->unset->callbackClass = $callbackClass;
// }
// public function get(){
// return $this->original;
// }
// public function debugInfo(){
// $rval = array();
// foreach ($this->original as $key=>$val){
// $rval[$key] = $this->$key;
// }
// foreach ($this->constraints as $key=>$constr){
// if (property_exists($constr, "get")){
// if ($constr->get->behaviour != self::GET_BEHAVIOUR_THROW){
// $rval[$key] = $this->$key;
// }
// }
// }
// return $rval;
// }
// }
?>
@@ -0,0 +1,32 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
class ConstraintException extends CoreException{
private $operation;
private $key;
private $value;
public function __construct($operation,$key,$value = null){
$this->operation = $operation;
$this->key = $key;
$this->value = $value;
parent::__construct("Impossible to execute operation '$operation' on attribute '$key'".(!is_null($value)?" with value '$value'":""));
}
public function getRelatedOperation(){
return $this->operation;
}
public function getRelatedKey(){
return $this->key;
}
public function getRelatedValue(){
return $this->value;
}
}
?>
@@ -0,0 +1,18 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 08/gen/2016
*/
require_once(dirname(__FILE__)."/ConstraintException.php");
require_once(dirname(__FILE__)."/ConstrainedInterface.php");
require_once(dirname(__FILE__)."/ConstrainedFactory.php");
require_once(dirname(__FILE__)."/Constrained.php");
require_once(dirname(__FILE__)."/ConstrainedBehaviour.php");
require_once(dirname(__FILE__)."/ConstrainedObject.php");
require_once(dirname(__FILE__)."/ConstrainedArrayObject.php");
?>
@@ -0,0 +1,182 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 23/dic/2015
*/
abstract class DaoSaveableDefaultImplementation implements DaoSaveable, Serializable {
protected $saveableObject;
public function __construct($saveableObject = null){
if (is_null($saveableObject)){
$saveableObject = new stdClass();
}
$this->updateFromSaveableObj($saveableObject);
}
public function __set($attr,$value){
if (strcmp($attr,"id")==0 || strcmp($attr,"_id")==0){
if (strcmp($attr,"id")==0){
$attr = "_id";
}
if (!($value instanceof MongoDB\BSON\ObjectID)){
$value = new MongoDB\BSON\ObjectID($value);
}
}
$this->saveableObject->$attr = $value;
}
public function &__get($attr){
$rval = null;
if (strcmp($attr,"id")==0){
$attr = '_id';
}
if ($this->hasProperty($attr)){
$rval = &$this->saveableObject->$attr;
}
if (strcmp($attr,"_id")==0){
$rval = strval($rval);
}
return $rval;
}
public function __unset($attr){
unset($this->saveableObject->$attr);
}
public function hasProperty($attr){
if (strcmp($attr,"id")==0){
$attr = "_id";
}
return property_exists($this->saveableObject, $attr);
}
/**
* (non-PHPdoc)
* @see DaoSaveable::getSaveableObj()
*/
public function getSaveableObj(){
// return $this->saveableObject;
return $this->toArray($this->saveableObject);
}
private function toArray($input){
$rval = $input;
if (is_object($rval) ){
// if (!($rval instanceof MongoId) && !($rval instanceof MongoDate) ){
if (!($rval instanceof MongoDB\BSON\ObjectID) && !($rval instanceof MongoDB\BSON\UTCDateTime) ){
$rval = (array)$input;
}
// $rval = (array)$input;
}
if (is_array($rval)) {
foreach ( $rval as $key=>$val){
$rval[$key] = $this->toArray($val);
}
}
return $rval;
}
/**
* (non-PHPdoc)
* @see DaoSaveable::buildFromSaveableObj()
*/
public static function buildFromSaveableObj($saveableObject){
return new static($saveableObject);
}
/**
* (non-PHPdoc)
* @see DaoSaveable::updateFromSaveableObj()
*/
public function updateFromSaveableObj($saveableObject){
$this->saveableObject = $this->toObject($saveableObject);
if (!property_exists($this->saveableObject, "deleted")){
$this->saveableObject->deleted = false;
}
// $this->saveableObject = $saveableObject;
}
private function toObject($input){
$rval = $input;
if (is_array($input) && sizeof(array_diff_key($input,array_keys($input)))>0 ){
$rval = (object)$input;
}
if (is_array($rval)){
foreach ( $rval as $key=>$val){
$rval[$key] = $this->toObject($val);
}
}
else if (is_object($rval)) {
// if (!($rval instanceof MongoId) && !($rval instanceof MongoDate)){
if (!($rval instanceof MongoDB\BSON\ObjectID) && !($rval instanceof MongoDB\BSON\UTCDateTime) ){
foreach ( $rval as $key=>$val){
$rval->$key = $this->toObject($val);
}
}
}
return $rval;
}
private function toArrayAndScalars($obj){
$rval = $obj;
if ( ( $rval instanceof MongoDB\BSON\ObjectID ) || ( $rval instanceof MongoDB\BSON\UTCDateTime ) ){
$rval = [
'__fetch' => get_class($rval),
'value' => strval($rval)
];
}
else if ( is_object( $rval ) ){
$rval = (array)($rval);
}
if ( is_array($rval) ) {
foreach ( $rval as $key=>$val ) {
if (!is_scalar($val)){
$rval[$key] = $this->toArrayAndScalars($val);
}
}
}
return $rval;
}
private function fromArrayAndScalars($obj){
$rval = $obj;
if (is_array($obj)){
if (array_key_exists("__fetch", $rval) && array_key_exists("value", $rval) ){
$class = $rval["__fetch"];
$val = $rval["value"];
$rval = new $class($val);
}
else {
foreach ($rval as $key=>$value){
$rval[$key] = $this->fromArrayAndScalars($value);
}
}
}
return $rval;
}
public function serialize(){
return json_encode( $this->toArrayAndScalars( $this->saveableObject ) );
}
public function unserialize($serialized){
$this->updateFromSaveableObj( $this->fromArrayAndScalars( json_decode( $serialized, true ) ) );
}
}
?>
@@ -0,0 +1,33 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 23/dic/2015
*/
interface DaoSaveable {
/**
* @return stdClass L'oggetto da passare alla set di mongo
*/
public function getSaveableObj();
/**
* @return string La collection name dove salvare il model
*/
public static function getCollectionName();
/**
* Costruisce l'oggetto a partire dai dati raw di mongo
* @param stdClass $obj dati raw di mongo
*/
public static function buildFromSaveableObj($obj);
/**
* Aggiorna i dati dell'oggetto partendo da un saveable object
* @param stdClass $obj dati raw di mongo
*/
public function updateFromSaveableObj($obj);
}
?>
+12
View File
@@ -0,0 +1,12 @@
<?php
/*
* DaoSearchable.php
* Author: Riccardo Di Dato
* Creation Date: 02 nov 2018
*/
interface DaoSearchable {
public static function getSearchableFields(): array;
}
?>
+464
View File
@@ -0,0 +1,464 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 22/dic/2015
*/
class GenericDao{
/**
* Nome del database
* @var string
*/
private $dbName;
/**
* Contiene il controller del driver mongo
* @var MongoDB\Driver\Manager
*/
private $client;
/**
* La connection string viene passata interamente a MongoClient, richiede formato 'mongo://server:port'.
* host1 e database sono obbligatori
*
* @param string $connectionString
*/
public function __construct($dbName, $connectionString = null){
if (is_null($connectionString)){
$this->client = new MongoDB\Driver\Manager();
}
else {
$this->client = new MongoDB\Driver\Manager($connectionString);
}
$this->dbName = $dbName;
}
/**
* Restituisce il nome del database attualmente in uso
* @return string
*/
public function getDbName(){
return $this->dbName;
}
/**
* Ritorna un array di model
* @param string $modelClass classe da ritornare (DaoSaveable)
* @param array $filter array associativo della select formato mongo
* @param array $options (al momento supporta limit e sort)
* @param string $customReturnClass
* @throws CoreException se la CustomReturnClass non è valida
* @return DaoSaveable[]
*/
public function query($modelClass, array $filter = array(), array $options = array()){
$modelClass = trim($modelClass);
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::query ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$useFilter = $filter;
if (!array_key_exists("deleted",$useFilter)){
$useFilter["deleted"] = false;
}
if (array_key_exists("id",$useFilter)){
$useFilter["_id"] = $useFilter["id"];
unset($useFilter["id"]);
}
if (array_key_exists("_id",$useFilter) && is_string($useFilter["_id"])){
$useFilter["_id"] = new MongoDB\BSON\ObjectID($useFilter["_id"]);
}
if (array_key_exists("sort",$options)){
if (array_key_exists("creationDate",$options["sort"]) && !array_key_exists("_id",$options["sort"])){
$options["sort"]["_id"] = $options["sort"]["creationDate"];
}
}
if (array_key_exists("limit",$options)){
$options["limit"] = intval($options["limit"]);
}
if (array_key_exists("skip",$options)){
$options["skip"] = intval($options["skip"]);
}
$query = new MongoDB\Driver\Query($useFilter, $options);
$cursor = $this->client->executeQuery($this->dbName.".$collectionName",$query);
$rval = array();
foreach ($cursor as $element){
$rval[] = $modelClass::buildFromSaveableObj($element);
}
return $rval;
}
public function count($modelClass, array $filter = array(), array $options = array()){
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::query ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$useFilter = $filter;
if (!array_key_exists("deleted",$useFilter)){
$useFilter["deleted"] = false;
}
if (array_key_exists("id",$useFilter)){
$useFilter["_id"] = $useFilter["id"];
unset($useFilter["id"]);
}
if (array_key_exists("_id",$useFilter) && is_string($useFilter["_id"])){
$useFilter["_id"] = new MongoDB\BSON\ObjectID($useFilter["_id"]);
}
$command = new \MongoDB\Driver\Command( [ 'count' => $collectionName, 'query' => $useFilter ] );
$cursor = $this->client->executeCommand( $this->dbName, $command );
foreach ($cursor as $ele){
return $ele->n;
}
}
/**
* Come query ma ritorna il primo o null se non ci sono risultati
* @param string $modelClass
* @param array $filter
* @param array $options
* @return DaoSaveable
*/
public function getFirst($modelClass, array $filter = array(), array $options = array()){
$options["limit"] = 1;
$rval = null;
$list = $this->query($modelClass, $filter, $options);
if (sizeof($list)>0){
$rval = reset($list);
}
return $rval;
}
/**
* Salva...
* @param DaoSaveable $model
*/
public function save(DaoSaveable $model){
$collectionName = $model->getCollectionName();
$saveObj = $model->getSaveableObj();
$bulk = new MongoDB\Driver\BulkWrite();
if ( array_key_exists("_id", $saveObj) && !is_null($saveObj["_id"]) ){
if (is_string( $saveObj["_id"]) ){
$saveObj["_id"] = new MongoDB\BSON\ObjectID($saveObj["_id"]);
}
$bulk->update(array("_id"=>$saveObj["_id"] ),$saveObj);
}
else {
$saveObj["_id"] = new MongoDB\BSON\ObjectID();
$bulk->insert($saveObj);
$model->updateFromSaveableObj($saveObj);
}
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $this->client->executeBulkWrite($this->dbName.".$collectionName", $bulk, $writeConcern);
//TODO: (Rik) Controllo sul write concern
}
/**
* Cancella... la cancellazione non è reale, viene solo settato il campo deleted a true.
* @param DaoSaveable $model
*/
public function delete(DaoSaveable $model){
$model->deleted = true;
$this->save($model);
}
/**
* Ritorna un array di model
* @param string $modelClass classe da ritornare (DaoSaveable)
* @param array $filter array associativo della select formato mongo
* @param array $options (al momento supporta limit e sort)
* @param string $customReturnClass
* @throws CoreException se la CustomReturnClass non è valida
* @return DaoSaveable[]
*/
public function aggregate($modelClass, array $pipeline = array(), array $options = array()){
$modelClass = trim($modelClass);
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::aggregate ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$addDeleteMatch = true;
if (sizeof($pipeline)>0){
foreach ($pipeline as $ele){
if (is_array($ele)){
// Check se esistono match su deleted
if (array_key_exists('$match', $ele) && array_key_exists("deleted", $ele['$match'])){
$addDeleteMatch = false;
}
if (array_key_exists('$groupBy', $ele)){
// Sostituzione di id con _id
foreach ($ele as $key=>$val){
if (array_key_exists("id",$val)){
$val["_id"] = $val["id"];
unset($val["id"]);
}
}
// Sostituzione di _id stringa con MongoId
if (array_key_exists("_id",$val) && is_string($val["_id"])){
$val["_id"] = new MongoDB\BSON\ObjectID( $val["_id"] );
}
}
}
}
}
if ($addDeleteMatch){
if (array_key_exists('$match', $pipeline[0])){
$pipeline[0]['$match']["deleted"] = false;
// array_unshift($pipeline[0]['$match'], array("deleted"=>false));
}
else {
array_unshift($pipeline, array('$match'=>array("deleted"=>false)));
}
}
$command = new \MongoDB\Driver\Command( [ 'aggregate' => $collectionName, 'pipeline' => $pipeline ] );
$cursor = $this->client->executeCommand( $this->dbName, $command );
$rval = [];
foreach ($cursor as $ele){ // inganniamo il cursore, in realtà il risultato è uno
//TODO CHECK
if (!is_null($ele->result)){
$rval = $ele->result;
$rval = json_decode( json_encode($rval) ,true );
}
}
return $rval;
}
/**
* Ritorna la lista dei notizia model ordinati per pertinenza
* @param string $modelClass
* @param string $searchWord
* @param array $filter
* @param array $options
* @throws CoreException
* @return DaoSaveable[]
*/
public function search($modelClass, $search, array $filter = array(), array $options = array()){
if ( is_a($modelClass, DaoSearchable::class, true ) ) {
return $this->query($modelClass, self::getSearchFilter( $modelClass, $search, $filter, $options, $modelClass::getSearchableFields() ), $options);
}
else {
return $this->searchUseIndex($modelClass, $search, $filter, $options);
}
}
public function searchCount($modelClass, $search, array $filter = array(), array $options = array()){
if ( is_a($modelClass, DaoSearchable::class, true ) ) {
return $this->count($modelClass, self::getSearchFilter( $modelClass, $search, $filter, $options, $modelClass::getSearchableFields() ), $options);
}
else {
return $this->searchUseIndexCount($modelClass, $search, $filter, $options);
}
}
/**
* Versione MODDATA di quello in PHPFramework (usa solo SEARCH_MODE_DAO in modalità regex)
* @param string $modelClass
* @param string $search
* @param array $filter
* @param array $options
* @param array $recursiveIgnore
* @throws CoreException
* @return array|string[]
*/
private function getSearchFilter($modelClass, $search, array $filter = array(), array $options = array(), array $searchFields){
$search = trim($search);
if ( strcmp($search, "")!=0 ){
$searchArr = preg_split("/\s+/", $search);
if (sizeof($searchFields)>0) {
$internalAnd = [ '$and' => [] ];
foreach ($searchArr as $ele){
$internalOr = [ '$or' => [] ];
foreach ($searchFields as $field){
$internalOr['$or'][] = [
$field => new MongoDB\BSON\Regex($ele,'i')
];
}
$internalAnd['$and'][] = $internalOr;
}
if (sizeof($filter)>0){
$andFilter = array();
$andFilter['$and'] = array();
$andFilter['$and'][] = $filter;
$andFilter['$and'][] = $internalAnd;
$filter = $andFilter;
}
else {
$filter = $internalAnd;
}
}
}
return $filter;
}
/**
* Ritorna la lista dei notizia model ordinati per pertinenza
* @param string $modelClass
* @param string $searchWord
* @param array $filter
* @param array $options
* @throws CoreException
* @return DaoSaveable[]
*/
public function searchUseIndex($modelClass, $search, array $filter = array(), array $options = array()){
$filter['$text'] = array('$search'=> trim($search) );
return $this->query($modelClass, $filter, $options);
}
public function searchUseIndexCount($modelClass, $search, array $filter = array(), array $options = array()){
$filter['$text'] = array('$search'=> trim($search) );
return $this->count($modelClass, $filter, $options);
}
/**
* Ritorna la lista dei notizia model ordinati per pertinenza
* @param string $modelClass
* @param string $searchWord
* @param array $filter
* @param array $options
* @throws CoreException
* @return DaoSaveable[]
*/
public function searchOld($modelClass, $searchWord, array $filter = array(), array $options = array()){
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::query ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$collection = $this->database->$collectionName;
$useFilter = $filter;
$useFilter['$text'] = array('$search'=>$searchWord);
if (!array_key_exists("deleted",$useFilter)){
$useFilter["deleted"] = false;
}
if (array_key_exists("id",$useFilter)){
$useFilter["_id"] = $useFilter["id"];
unset($useFilter["id"]);
}
if (array_key_exists("_id",$useFilter) && is_string($useFilter["_id"])){
$useFilter["_id"] = new MongoId($useFilter["_id"]);
}
$cursor = $collection->find($useFilter,array('score' => array('$meta' => 'textScore')));
$sortArray = array();
if (array_key_exists("sort",$options)){
$sortArray = $options["sort"];
}
$sortArray = array_merge($sortArray,array('score' => array('$meta' => 'textScore')) );
$cursor->sort($sortArray);
if (array_key_exists("skip",$options)){
$cursor->skip($options["skip"]);
}
if (array_key_exists("limit",$options)){
$cursor->limit($options["limit"]);
}
$rval = array();
foreach ($cursor as $element){
unset($element->score);
$rval[] = $modelClass::buildFromSaveableObj($element);
}
return $rval;
}
public function searchCountOld($modelClass, $searchWord, array $filter = array(), array $options = array()){
if (!is_null($modelClass)){
if (!is_subclass_of($modelClass, "DaoSaveable", true)){
throw new CoreException("Invalid return class passed to GenericDao::query ($modelClass)");
}
}
$collectionName = $modelClass::getCollectionName();
$collection = $this->database->$collectionName;
$useFilter = $filter;
$useFilter['$text'] = array('$search'=>$searchWord);
if (!array_key_exists("deleted",$useFilter)){
$useFilter["deleted"] = false;
}
if (array_key_exists("id",$useFilter)){
$useFilter["_id"] = $useFilter["id"];
unset($useFilter["id"]);
}
if (array_key_exists("_id",$useFilter) && is_string($useFilter["_id"])){
$useFilter["_id"] = new MongoId($useFilter["_id"]);
}
$cursor = $collection->find($useFilter,array('score' => array('$meta' => 'textScore')));
return $cursor->count(true);
}
}
?>
+11
View File
@@ -0,0 +1,11 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 22/dic/2015
*/
abstract class Model extends DaoSaveableDefaultImplementation{
}
?>
+47
View File
@@ -0,0 +1,47 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
// Inclue Saam
require_once(dirname(__FILE__)."/DaoSaveableInterface.php");
require_once(dirname(__FILE__)."/DaoSearchable.php");
require_once(dirname(__FILE__)."/DaoSaveableDefaultImplementation.php");
require_once(dirname(__FILE__)."/GenericDao.php");
require_once(dirname(__FILE__)."/Model.php");
require_once(dirname(__FILE__)."/mediaModels/MediaModel.php");
require_once(dirname(__FILE__)."/mediaModels/HasMediaModel.php");
require_once(dirname(__FILE__)."/mediaModels/DaoMediaHandler.php");
require_once(dirname(__FILE__)."/models/ConfigModel.php");
require_once(dirname(__FILE__)."/models/TaskModel.php");
require_once(dirname(__FILE__)."/models/NotiziaModel.php");
require_once(dirname(__FILE__)."/models/AdminModel.php");
require_once(dirname(__FILE__)."/models/UserModel.php");
require_once(dirname(__FILE__)."/models/CommentoModel.php");
require_once(dirname(__FILE__)."/models/MailModel.php");
require_once(dirname(__FILE__)."/models/MailTemplateModel.php");
require_once(dirname(__FILE__)."/models/AccessModel.php");
require_once(dirname(__FILE__)."/models/LogModel.php");
require_once(dirname(__FILE__)."/models/StatisticModel.php");
require_once(dirname(__FILE__)."/models/BannerModel.php");
require_once(dirname(__FILE__)."/models/CBSQueueModel.php");
require_once(dirname(__FILE__)."/models/PasswordRecoveryRequestModel.php");
$dao = new GenericDao($database->dbName,$database->connectionString);
GlobalVariables::set("dao", $dao);
?>
@@ -0,0 +1,226 @@
<?php
class DaoMediaHandler implements MediaHandlerInterface{
/**
*
* @param HasMediaInterface $news
* @return MediaInterface[] $media
* Ritorna un array con i media model della news
*/
public static function getMedias(HasMediaInterface $model){
$newsReference = $model->getMediaReferences();
$referenceIds = array();
if (sizeof($newsReference)>0){
foreach ($newsReference as $ref){
$referenceIds[] = new MongoDB\BSON\ObjectID($ref);
}
}
$rval = array();
// var_dump($newsReference);
$rval = GlobalVariables::get("dao")->query("MediaModel",array('id'=>array('$in'=>$referenceIds)));
// var_dump($rval);
return $rval;
}
/**
* Aggiunge il media al model e controlla se il model ha un main media e se non lo ha glielo assegna (salva sia il media che la news).
* @param HasMediaInterface $model
* @param MediaInterface $media
* @throws MediaException
*/
public static function addMedia(HasMediaInterface $model, MediaInterface $media){
if(!$model->hasProperty("id")){
throw new MediaException("Invalid HasMediaInterface passed to DaoMediaHandler::addMedia (no property ID)");
}
if(!$media->hasProperty("id")){
throw new MediaException("Invalid MediaInterface passed to DaoMediaHandler::addMedia (no property ID)");
}
try{
$mediaArr = array();
$mediaArr = $model->getMediaReferences();
if(!in_array($media->getReference(), $mediaArr)){
$mediaArr[] = $media->getReference();
$model->setMediaReferences($mediaArr);
if(!DaoMediaHandler::hasMainMedia($model)){
$model->setMainMedia($media);
}
GlobalVariables::get("dao")->save($model);
self::setOwnerToMedia($model, $media);
// $media->setOwnerReference($model);
GlobalVariables::get("dao")->save($media);
}
}catch(CoreException $ex){
throw new MediaException("Error while saving in DaoMediaHandler::addMedia (".$ex->getMessage().")");
}
}
/**
* Elimina l'id del media dal model e deleta il media. Se il media è il main media della news lo unsetta
*
* @param HasMediaInterface $model
* @param MediaInterface $media
* @throws MediaException
*/
public static function deleteMedia(HasMediaInterface $model, MediaInterface $media){
try{
$mediaArr = array();
$mediaArr = $model->getMediaReferences();
$mediaId = $media->getReference();
// var_dump($mediaArr);
if(sizeof($mediaArr)>0){
$key = array_search($mediaId, $mediaArr);
if($key !== false){
unset($mediaArr[$key]);
$model->setMediaReferences($mediaArr);
if($model->getMainMediaReference() == $mediaId){
$medias = self::getMedias($model);
if (sizeof($medias)>0){
if ($media->getReference() == $medias[0]->getReference()){
$model->setMainMedia($medias[1]);
}
else {
$model->setMainMedia($medias[0]);
}
}
else {
$model->setMainMedia(null);
}
// echo "UGUALE!";
}
GlobalVariables::get("dao")->save($model);
GlobalVariables::get("dao")->delete($media);
}
else{
throw new MediaException("Trying to delete invalid media from a model in DaoMediaHandler::deleteMedia");
}
}
else{
throw new MediaException("This HasMediaInterface has no media in it '".$model->id."' sizeof on mediaReference failed in DaoMediaHandler::deleteMedia");
}
}catch(CoreException $ex){
throw new MediaException("Error while deleting in DaoMediaHandler::deleteMedia (".$ex->getMessage().")");
}
}
/**
* Elimina tutti i media associati al contenuto
* @param HasMediaInterface $model
*/
public static function deleteAllMedias(HasMediaInterface $model){
$medias = self::getMedias($model);
if (sizeof($medias)>0){
foreach ($medias as $media){
self::deleteMedia($model, $media);
}
}
}
/**
* Setta l'owner al MediaModel
* @param HasMediaInterface $model
* @param MediaModel $media
*/
public static function setOwnerToMedia(HasMediaInterface $model, MediaModel $media){
$media->setOwnerReference($model);
}
/**
*
* @param MediaInterface $media
* @throws MediaException
* @return DaoSaveable
*/
public static function getMediaOwnerFromMedia(MediaInterface $media){
$ownerRef = $media->getOwnerReference();
try{
$owner = GlobalVariables::get("dao")->getFirst($ownerRef->class,array("id"=>$ownerRef->id));
return $owner;
}catch(CoreException $ex){
throw new MediaException("Invalid Media Reference trying get Media Owner in DaoMediaHandler::getMEdiaOwner");
}
}
/**
*
* @param HasMediaInterface $model
* @param MediaInterface $media
* @throws MediaException
*/
public static function setMainMediaToModel(HasMediaInterface $model, MediaInterface $media){
try{
self::addMedia($model, $media);
$model->setMainMedia($media);
GlobalVariables::get("dao")->save($model);
}catch(CoreException $ex){
throw new MediaException("Error while trying to save an HasMediaInterface in ModelHandler::setMainMedia");
}
}
/**
* Prende in ingresso un HasMediaInterface ritorna un MediaModel o null;
*
* @param HasMediaInterface $model
* @return MediaModel
*/
public static function getMainMediaFromModel(HasMediaInterface $model){
$mainMedia = $model->getMainMediaReference();
$tmp = null;
if(!is_null($mainMedia)){
$mainMediaId = new MongoDB\BSON\ObjectID($mainMedia);
$tmp = GlobalVariables::get("dao")->getFirst("MediaModel",array("id"=>$mainMediaId));
}
// var_dump($tmp);
return $tmp;
}
/**
* Richiede un saveable object con almeno la proprietà mediaType e il path del file
*
* @param stdClass $saveableObj
* @param string $filePath
* @return MediaModel
*/
public static function createNewFileBasedMedia($saveableObj, $filePath,$extension){
$basepath = GlobalVariables::get("config")->paths->media;
$media = new MediaModel($saveableObj);
$media->extension = $extension;
GlobalVariables::get("dao")->save($media);
SFSManager::copyFile($filePath, $basepath."/".$media->id.".".$media->extension);
return $media;
}
/**
* Richiede un saveable object con la proprietà mediaType settata
*
* @param stdClass $saveable
* @return MediaModel
*/
public static function createNewTextBasedMedia($saveable){
$media = new MediaModel($saveable);
GlobalVariables::get("dao")->save($media);
return $media;
}
public static function hasMainMedia(HasMediaInterface $model){
$hasMainMedia = false;
if(!is_null($model->getMainMediaReference())){
$hasMainMedia = true;
}
return $hasMainMedia;
}
}
?>
@@ -0,0 +1,77 @@
<?php
abstract class HasMediaModel extends Model implements HasMediaInterface{
/**
* (non-PHPdoc)
* @see HasMediaInterface::getReference()
*/
public function getReference(){
$rval = new stdClass();
$rval->class = get_class($this);
$rval->id = $this->id;
return $rval;
}
/**
* (non-PHPdoc)
* @see HasMediaInterface::setMediaReferences()
*/
public function setMedias(array $medias){
$this->mediaReferences = array();
if(sizeof($medias)>0){
foreach ($medias as $media){
if ($media instanceof MediaInterface){
$this->mediaReferences[] = $media->getReference();
}
}
}
}
public function setMediaReferences(array $references){
$this->mediaReferences = array();
if(sizeof($references)>0){
foreach ($references as $reference){
$this->mediaReferences[] = $reference;
}
}
}
/**
* (non-PHPdoc)
* @see HasMediaInterface::getMediaReferences()
*/
public function getMediaReferences(){
if(!$this->hasProperty("mediaReferences")){
$this->mediaReferences = array();
}
return $this->mediaReferences;
}
/**
* (non-PHPdoc)
* @see HasMediaInterface::setMainMedia()
*/
public function setMainMedia(MediaInterface $media = null){
if(!is_null($media)){
$this->mainMedia = $media->getReference();
}
else{
$this->mainMedia=null;
}
}
/**
* (non-PHPdoc)
* @see HasMediaInterface::getMainMediaReference()
*/
public function getMainMediaReference(){
if(!$this->hasProperty("mainMedia")){
$this->mainMedia = null;
}
return $this->mainMedia;
}
}
?>
@@ -0,0 +1,111 @@
<?php
class MediaModel extends Model implements MediaInterface{
const TYPE_YOUTUBE = 1;
const TYPE_IMAGE = 2;
const TYPE_HTML5 = 3;
const TYPE_PDF = 4;
const TYPE_LOCALVIDEO = 5;
public static $MEDIA_TYPES = array(
self::TYPE_YOUTUBE=>array("label"=>"Youtube"),
self::TYPE_IMAGE=>array("label"=>"Immagine"),
self::TYPE_HTML5=>array("label"=>"Html5"),
self::TYPE_PDF=>array("label"=>"Pdf"),
self::TYPE_LOCALVIDEO=>array("label"=>"Video")
);
private $mediaRenderer;
public function getRenderer(){
return $this->mediaRenderer;
}
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
$this->setMediaRenderer();
if (!$this->hasProperty("owner")){
$this->owner = new stdClass();
}
}
public function __set($attr,$value){
if (strcmp("mediaType", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public function setMediaRenderer(){
if($this->hasProperty("mediaType")){
if ($this->mediaType == self::TYPE_HTML5){
if ($this->hasProperty("code")){
$this->mediaRenderer = new MediaHtml5($this->code);
}
else {
throw new MediaException("Media of type 'HTML5' has no code field");
}
}
if ($this->mediaType == self::TYPE_LOCALVIDEO){
$this->mediaRenderer = new MediaLocalVideo($this);
}
if ($this->mediaType == self::TYPE_IMAGE){
$this->mediaRenderer = new MediaImage($this->id, $this->extension);
}
if ($this->mediaType == self::TYPE_PDF){
$this->mediaRenderer = new MediaPdf($this);
}
if ($this->mediaType == self::TYPE_YOUTUBE){
$this->mediaRenderer = new MediaYoutube($this);
}
}
else{
throw new MediaException("Missing mediatype for Media in MediaModel construct");
}
}
public function asText(array $opts = array()){
return $this->mediaRenderer->asText($opts);
}
public function renderMedia(array $opts = array()){
// var_dump($this->mediaRenderer);
$this->mediaRenderer->render($opts);
}
public function getType(){
return $this->mediaType;
}
public static function getCollectionName(){
return "media";
}
public function setOwnerReference(HasMediaInterface $model){
$this->owner = $model->getReference();
}
public function getOwnerReference(){
return $this->owner;
}
public function getReference(){
return $this->id;
}
public function updateFromSaveableObj($saveableObject){
parent::updateFromSaveableObj($saveableObject);
$this->setMediaRenderer();
}
public function getPath(){
if(($this->mediaType == self::TYPE_IMAGE) || ($this->mediaType == self::TYPE_PDF) || ($this->mediaType == self::TYPE_LOCALVIDEO)){
return $this->mediaRenderer->getPath();
}
else{
return "questo media non è presente all'interno dell'applicativo";
}
}
}
?>
@@ -0,0 +1,33 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 26/gen/2016
*/
class AccessModel extends Model {
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
$requiredProps = array("related");
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
foreach ($requiredProps as $prop){
if (!$this->hasProperty($prop)){
throw new CoreException("Missing parameter '$prop' while calling AdminAccessModel::__construct()");
}
}
}
public static function getCollectionName(){
return "accessLog";
}
}
?>
+80
View File
@@ -0,0 +1,80 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 13/gen/2016
*/
class AdminModel extends Model{
/*
SuperAdmin (FLAG_HIDDEN Profilo per esecuzione manuale di task, attivazione/disattivazione task, aggiunge flag NON_HIDDEN agli utenti, ripristina backup)
Admin (Amministratore di sistema, può aggiungere FLAG_BASE agli altri amministratori)
Editore (FLAG_BASE Inserimento notizie)
Editore_supervisor (Validazione notizie)
Banner (Inserimento banner)
Banner_supervisor (Visualizza statistiche banner)
Commenti_supervisor (Valida i commenti e modifica quelli in stato di pending)
Statistiche_supervisor (Visualizza statistiche relative agli accessi sull'applicazione)
Newsletter (Crea newsletter)
Sondaggi (Crea sondaggi)
*/
const TYPE_FLAG_NONE = 0;
const TYPE_FLAG_HIDDEN = 1;
const TYPE_FLAG_BASE = 2;
const ADMIN_TYPE_SUPERADMIN = 1;
const ADMIN_TYPE_NORMALADMIN = 2;
const ADMIN_TYPE_EDITORE = 4;
const ADMIN_TYPE_EDITORE_SUPERVISOR = 8;
const ADMIN_TYPE_BANNER = 16;
const ADMIN_TYPE_BANNER_SUPERVISOR = 32;
const ADMIN_TYPE_COMMENTI_SUPERVISOR = 64;
const ADMIN_TYPE_STATISTICHE_SUPERVISOR = 128;
const ADMIN_TYPE_NEWSLETTER = 256;
const ADMIN_TYPE_SONDAGGI = 512;
public static $ADMIN_TYPES = array(
self::ADMIN_TYPE_SUPERADMIN => array("label"=>"Superadmin","typeFlags"=>self::TYPE_FLAG_HIDDEN),
self::ADMIN_TYPE_NORMALADMIN => array("label"=>"Role Admin","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_EDITORE => array("label"=>"Editore","typeFlags"=>self::TYPE_FLAG_BASE),
self::ADMIN_TYPE_EDITORE_SUPERVISOR => array("label"=>"Editore Supervisor","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_BANNER => array("label"=>"Banner","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_BANNER_SUPERVISOR => array("label"=>"Banner Supervisor","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_COMMENTI_SUPERVISOR => array("label"=>"Commenti Supervisor","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_STATISTICHE_SUPERVISOR => array("label"=>"Statistiche Supervisor","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_NEWSLETTER => array("label"=>"Newsletter","typeFlags"=>self::TYPE_FLAG_NONE),
self::ADMIN_TYPE_SONDAGGI => array("label"=>"Sondaggi","typeFlags"=>self::TYPE_FLAG_NONE)
);
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("roles")){
$this->roles = 0;
}
}
public static function getCollectionName(){
return "administrators";
}
public function hasRole($role){
return ($role & $this->roles) == $role;
}
public function addRole($role){
$this->roles = $this->roles | $role;
}
public function removeRole($role){
$this->roles = $this->roles & ~$role;
}
public function setRole($role){
$this->roles = $role;
}
}
?>
@@ -0,0 +1,47 @@
<?php
class BannerModel extends HasMediaModel{
// const TYPE_IMAGE = 1;
// const TYPE_HTML = 2;
// public static $BANNER_TYPES = array(
// self::TYPE_IMAGE=>array("label"=>"Image"),
// self::TYPE_HTML=>array("label"=>"Html")
// );
const POSITION_HEAD = 1;
const POSITION_BODY = 2;
const POSITION_LONG = 3;
const GENERAL_CATEGORY = 0;
public static $BANNER_POSITIONS = array(
self::POSITION_HEAD=>array("label"=>"Testata"),
self::POSITION_BODY=>array("label"=>"Corpo"),
self::POSITION_LONG=>array("label"=>"Corpo Lungo")
);
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("categories")){
$this->categories = array(self::GENERAL_CATEGORY);
}
}
public function __set($attr,$value){
if (strcmp("type", $attr)==0 || strcmp("position", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public static function getCollectionName(){
return "banner";
}
}
?>
@@ -0,0 +1,23 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 22/feb/2016
*/
class CBSQueueModel extends Model{
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("retry")){
$this->retry = 0;
}
}
public static function getCollectionName(){
return "CBS_queue";
}
}
?>
@@ -0,0 +1,59 @@
<?php
class CommentoModel extends Model{
const STATUS_PENDING = 1;
const STATUS_ACCEPTED = 2;
const STATUS_REJECTED = 3;
public static $COMMENTO_STATUS = array(
self::STATUS_PENDING=>array("label"=>"Valutazione"),
self::STATUS_ACCEPTED=>array("label"=>"Accettata"),
self::STATUS_REJECTED=>array("label"=>"Respinta")
);
/**
* saveableObject deve avere alemeno il campo notizia = notiziaId e il campo user = userId;
* @param stdClass $saveableObject
* @throws CoreException
*/
public function __construct($saveableObject){
parent::__construct($saveableObject);
if (!$this->hasProperty("notizia") || strcmp($this->notizia,"")==0){
throw new CoreException("Impossible to build CommentoModel without field notizia");
}
if (!$this->hasProperty("user") || strcmp($this->user,"")==0){
throw new CoreException("Impossible to build CommentoModel without field user");
}
if (!$this->hasProperty("status") || strcmp($this->status,"")==0){
$this->status = self::STATUS_PENDING;
}
if (!$this->hasProperty("mailSent")){
$this->mailSent = false;
}
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
}
public function __set($attr,$value){
if (strcmp("status", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public static function getCollectionName(){
return "commenti";
}
}
?>
@@ -0,0 +1,17 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 13/gen/2016
*/
class ConfigModel extends Model{
public static function getCollectionName(){
return "genconfig";
}
}
?>
+37
View File
@@ -0,0 +1,37 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 27/gen/2016
*/
class LogModel extends Model {
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
}
public function getCode(){
return $this->id;
}
public static function getCollectionName(){
return "guiLog";
}
public static function fromException(Exception $ex){
$tmp = new stdClass();
$tmp->message = $ex->getMessage();
$tmp->trace = strval($ex);
return new self($tmp);
}
}
?>
+82
View File
@@ -0,0 +1,82 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/gen/2016
*/
class MailModel extends Model implements FDN_MailInterface{
const STATUS_PENDING = 0;
const STATUS_SENT = 1;
const STATUS_PAUSED = 2;
const PRIORITY_HIGH = 100;
const PRIORITY_NORMAL = 50;
const PRIORITY_LOW = 10;
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
$requiredProps = array("from","subject","body","recipient");
if (!$this->hasProperty("status")){
$this->status = self::STATUS_PENDING;
}
if (!$this->hasProperty("priority")){
$this->priority = self::PRIORITY_NORMAL;
}
foreach ($requiredProps as $prop){
if (!$this->hasProperty($prop)){
throw new CoreException("Missing parameter '$prop' while calling MailModel::__construct()");
}
}
}
public function __set($attr,$value){
if (strcmp("status", $attr)==0 || strcmp("priority", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public function getMailObject(){
$email = new PHPMailer();
$email->CharSet = "UTF-8";
$email->isMail();
$email->From = $this->from;
if ($this->hasProperty("fromName")){
$email->FromName = $this->fromName;
}
$email->Subject = $this->subject;
$email->IsHTML(true);
$email->Body = $this->body;
if ($this->hasProperty("altBody")){
$email->AltBody = $this->altBody;
}
else {
$email->AltBody = strip_tags($this->body);
}
$email->AddAddress($this->recipient);
if ($this->hasProperty("attachment")){
$email->AddAttachment( $this->attachment , basename($this->attachment) );
}
return $email;
}
public static function getCollectionName(){
return "mail";
}
}
?>
@@ -0,0 +1,49 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 25/gen/2016
*/
class MailTemplateModel extends Model{
const STATUS_NEW = 0;
const STATUS_READY = 1;
const STATUS_COMPLETE = 2;
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
$requiredProps = array("from","subject","body");
if (!$this->hasProperty("status")){
$this->status = self::STATUS_NEW;
}
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
foreach ($requiredProps as $prop){
if (!$this->hasProperty($prop)){
throw new CoreException("Missing parameter '$prop' while calling MailTemplateModel::__construct()");
}
}
}
public function __set($attr,$value){
if (strcmp("status", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public static function getCollectionName(){
return "mailTemplate";
}
}
?>
+143
View File
@@ -0,0 +1,143 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 07/gen/2016
*/
/**
* Campi:
* titolo
* sottotitolo
* testo
* about {
* author
* data
* }
* @author rik
*
*/
class NotiziaModel extends HasMediaModel implements DaoSearchable{
const STATUS_PENDING = 1;
const STATUS_ACCEPTED = 2;
const STATUS_REJECTED = 3;
public static $NOTIZIA_STATUS = array(
self::STATUS_PENDING=>array("label"=>"Valutazione"),
self::STATUS_ACCEPTED=>array("label"=>"Accettata"),
self::STATUS_REJECTED=>array("label"=>"Respinta")
);
const CATEGORY_POLITICA = 1;
const CATEGORY_CRONACA = 2;
const CATEGORY_SPORT = 3;
const CATEGORY_CULTURA = 4;
const CATEGORY_GOSSIP = 5;
const CATEGORY_ANIMALI = 6;
const CATEGORY_VIAGGI = 7;
const CATEGORY_RISTORANTI = 8;
const CATEGORY_MESTIERI = 9;
const CATEGORY_CASA = 10;
const CATEGORY_SALUTE = 11;
const CATEGORY_ANNUNCI = 12;
const CATEGORY_FISCOELAVORO = 13;
const CATEGORY_RUBRICHE = 14;
const CATEGORY_SPECIALE_ELEZIONI = 15;
const CATEGORY_SMARRITI = 16;
const CATEGORY_RITROVATI = 17;
const CATEGORY_CONSIGLI_ESPERTI = 18;
const CATEGORY_MONDO_SPOSI = 19;
public static $NOTIZIE_CATEGORY = array(
self::CATEGORY_POLITICA=>array("label"=>"Politica","mainMenu"=>true,"hidden"=>false,"pages"=>array("list"=>"politica.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_CRONACA=>array("label"=>"Cronaca","mainMenu"=>true, "hidden"=>false,"pages"=>array("list"=>"cronaca.php"),"color"=>"red","isSubmenu"=>null),
self::CATEGORY_SPORT=>array("label"=>"Sport","mainMenu"=>true, "hidden"=>false,"pages"=>array("list"=>"sport.php"),"color"=>"#4f8f2f","isSubmenu"=>null),
self::CATEGORY_CULTURA=>array("label"=>"Cultura&Spettacolo","mainMenu"=>true, "hidden"=>false,"pages"=>array("list"=>"cultura.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_GOSSIP=>array("label"=>"Gossip","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"gossip.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_ANIMALI=>array("label"=>"Mondo Animale","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"animali.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_VIAGGI=>array("label"=>"Viaggi","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"viaggi.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_RISTORANTI=>array("label"=>"Food&Drink","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"ristoranti.php"),"color"=>"#502f8f","isSubmenu"=>null),
self::CATEGORY_MESTIERI=>array("label"=>"Professioni e Mestieri","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"mestieri.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_CASA=>array("label"=>"Casa","mainMenu"=>false, "hidden"=>true,"pages"=>array("list"=>"casa.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_SALUTE=>array("label"=>"Salute","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"salute.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_ANNUNCI=>array("label"=>"Annunci","mainMenu"=>false, "hidden"=>true,"pages"=>array("list"=>"annunci.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_FISCOELAVORO=>array("label"=>"Fisco e Lavoro","mainMenu"=>false, "hidden"=>true,"pages"=>array("list"=>"fiscoelavoro.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_RUBRICHE=>array("label"=>"Rubriche","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"rubriche.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_SPECIALE_ELEZIONI=>array("label"=>"Speciale Elezioni","mainMenu"=>false, "hidden"=>true,"pages"=>array("list"=>"specialeElezioni.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_SMARRITI=>array("label"=>"Smarriti","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"animaliSmarriti.php"),"color"=>"#3e3e3e","isSubmenu"=>self::CATEGORY_ANIMALI),
self::CATEGORY_RITROVATI=>array("label"=>"Ritrovati","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"animaliRitrovati.php"),"color"=>"#3e3e3e","isSubmenu"=>self::CATEGORY_ANIMALI),
self::CATEGORY_CONSIGLI_ESPERTI=>array("label"=>"I consigli degli esperti","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"consigliEsperti.php"),"color"=>"#3e3e3e","isSubmenu"=>null),
self::CATEGORY_MONDO_SPOSI=>array("label"=>"Mondo Sposi","mainMenu"=>false, "hidden"=>false,"pages"=>array("list"=>"mondoSposi.php"),"color"=>"#dd603a","isSubmenu"=>null),
);
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("about")){
$this->about = new stdClass();
}
if (!property_exists($this->about, "data") || !($this->about->data instanceof MongoDB\BSON\UTCDateTime) ){
$this->about->data = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
}
public static function getCollectionName(){
return "notizia";
}
public function __set($attr,$value){
if (strcmp("category", $attr)==0 || strcmp("status", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public function buildAutoShortenedUrl(){
$shortened = strtolower($this->titolo);
$shortened = preg_replace("/[^a-z0-9-_]/", " ", $shortened);
$shortened = preg_replace("/\s+/", " ", trim($shortened) );
$eles = explode(" ", $shortened);
$eles = array_slice($eles, 0, 15);
$this->shortenedUrl = implode("_", $eles);
}
public function getAbsoluteUrl(){
$link = "articolo_".strval($this->id);
if ($this->hasProperty("shortenedUrl")){
$link = "art_".$this->shortenedUrl.".html";
}
return GUIHandler::getBaseUrl().$link;
}
public function getAbsoluteMobileUrl(){
$link = "articolo_".strval($this->id);
if ($this->hasProperty("shortenedUrl")){
$link = "art_".$this->shortenedUrl.".html";
}
return GUIHandlerMobile::getBaseUrl().$link;
}
public function cutTextHtmlSafe($attrName, $size){
$rval = strval( $this->$attrName );
if (strlen($rval) > ($size + 3) ){
$rval = html_entity_decode( $rval , ENT_QUOTES | ENT_HTML5, 'UTF-8' );
$rval = mb_substr($rval, 0, $size, 'UTF-8');
$rval.= "...";
}
return $rval;
}
public static function getSearchableFields(): array {
return [
"about.author",
"sottotitolo",
"testo",
"titolo"
];
}
}
?>
@@ -0,0 +1,53 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 17/mar/2016
*/
class PasswordRecoveryRequestModel extends Model{
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("target")){
throw new CoreException("Missing parameter 'target' while calling PasswordRecoveryRequestModel::__construct()");
}
if (!array_key_exists("class", $this->target)){
throw new CoreException("Missing parameter 'target.class' while calling PasswordRecoveryRequestModel::__construct()");
}
if (!array_key_exists("id", $this->target)){
throw new CoreException("Missing parameter 'target.id' while calling PasswordRecoveryRequestModel::__construct()");
}
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
if (!$this->hasProperty("sent")){
$this->sent = false;
}
}
public static function fromModel(Model $model){
$buildObj = new stdClass();
if ($model instanceof UserModel || $model instanceof AdminModel ){
$buildObj->target = array();
$buildObj->target["class"] = get_class($model);
$buildObj->target["id"] = $model->id;
return new self($buildObj);
}
else {
throw new CoreException("Impossible to build a PasswordRecoveryRequestModel from a model of class '".get_class($model)."' in PasswordRecoveryRequestModel::fromModel()");
}
}
public static function getCollectionName(){
return "passwordRecovery";
}
}
?>
@@ -0,0 +1,59 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 27/gen/2016
*/
/**
* {user:{id, isNew}, ip, content, source, data}
* @author Riccardo Di Dato
*/
class StatisticModel extends Model {
const STAT_TYPE_PAGE = 1;
const STAT_TYPE_NOTIZIA = 2;
const STAT_TYPE_BANNER_IMPRESSION = 3;
const STAT_TYPE_BANNER_CLICK = 4;
public static $STAT_TYPES = array(
self::STAT_TYPE_PAGE=>array("label"=>"Statistiche pagina"),
self::STAT_TYPE_NOTIZIA=>array("label"=>"Statistiche notizia"),
self::STAT_TYPE_BANNER_IMPRESSION=>array("label"=>"Statistiche pagina"),
self::STAT_TYPE_BANNER_CLICK=>array("label"=>"Statistiche pagina")
);
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
$requiredProps = array("user","content","source", "ip", "statType");
if (!$this->hasProperty("date")){
// $this->date = new MongoDate();
$this->date = new MongoDB\BSON\UTCDateTime( time() * 1000 );
}
foreach ($requiredProps as $prop){
if (!$this->hasProperty($prop)){
throw new CoreException("Missing parameter '$prop' while calling ".get_called_class()."::__construct()");
}
}
if (!array_key_exists($this->statType, self::$STAT_TYPES)){
throw new CoreException("Invalid statistic type '".$this->statType."' while calling ".get_called_class()."::__construct()");
}
}
public function __set($attr,$value){
if (strcmp("statType", $attr)==0){
$value = intval($value);
}
return parent::__set($attr, $value);
}
public static function getCollectionName(){
return "statistics";
}
}
?>
+22
View File
@@ -0,0 +1,22 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 13/gen/2016
*/
class TaskModel extends Model{
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("isActive")){
$this->isActive = false;
}
}
public static function getCollectionName(){
return "task";
}
}
?>
+44
View File
@@ -0,0 +1,44 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 13/gen/2016
*/
class UserModel extends Model{
public function __construct($saveableObject = null){
parent::__construct($saveableObject);
if (!$this->hasProperty("newsletter")){
$this->newsletter = true;
}
if (!$this->hasProperty("email")){
throw new CoreException("Impossible to create a user without a mail address");
}
if (!$this->hasProperty("username")){
throw new CoreException("Impossible to create a user without a username");
}
if(!$this->hasProperty("password")){
new CoreException("Impossible to create a user without a password");
}
if(!$this->hasProperty("active")){
$this->active = false;
}
if(!$this->hasProperty("activationSent")){
$this->activationSent = false;
}
}
public static function getCollectionName(){
return "users";
}
}
?>
+53
View File
@@ -0,0 +1,53 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 13/gen/2016
*/
class ASDSessionHandler {
private static $isSessionStarted;
private static $sessId;
public static function getSessionId(){
self::prepareToOperate();
return self::$sessId;
}
private static function prepareToOperate(){
if (!isset(self::$isSessionStarted) || !self::$isSessionStarted){
self::$isSessionStarted = session_start();
}
if (!isset(self::$sessId) || is_null(self::$sessId)){
self::$sessId = session_id();
}
}
public static function sessionValueExists($val){
self::prepareToOperate();
return array_key_exists($val,$_SESSION);
}
public static function getSessionValue($val){
self::prepareToOperate();
return (self::sessionValueExists($val)?$_SESSION[$val]:null);
}
public static function setSessionValue($key,$val){
self::prepareToOperate();
$_SESSION[$key] = $val;
}
public static function unsetSessionValue($key){
self::prepareToOperate();
if (array_key_exists($key,$_SESSION)){
unset($_SESSION[$key]);
}
}
public static function flush(){
self::prepareToOperate();
session_unset();
}
}
?>
+55
View File
@@ -0,0 +1,55 @@
<?php
abstract class CatalogManager {
public static $MAX_SUBSTITUTIONS = 9;
abstract protected function retrieveCatalog($index);
public function getCatalog($index,&$data=null) {
// if (is_array($index))var_dump($index);
$reval = "";
if(!is_null($data) && !is_array($data)) $data = array($data);
if($index != null && trim($index) != "") {
$reval = "" . $this->retrieveCatalog($index);
if($reval != null) {
if ($data!=null) $this->tokenize($reval,$data);
}
else $reval = $index;
}
return $reval;
}
/**
* Tokenizza la stringa di catalog
*/
protected function tokenize(&$catalog,&$data) {
$matches = array();
//implementation 3
if(preg_match_all("/\{([0-9]|c[0-9])\}/",$catalog,$matches)) {
$regas = $matches[1];
if(!is_array($regas)) $regas = array($regas);
// var_dump($regas);
foreach( $regas as $idx) {
if(preg_match("/^c[0-9]$/",$idx)) {
$useidx = (int) substr($idx,1);
$useidx--;
// echo "useidx: $useidx $idx\n";
$catalog = str_replace('{'. $idx . '}',$this->getCatalog((array_key_exists($useidx,$data)?$data[$useidx]:"")),$catalog);
}
else {
$useidx = (int) $idx;
$useidx--;
// echo "useidx: $useidx $idx\n";
$catalog = str_replace('{'. $idx . '}',(array_key_exists($useidx,$data)?$data[$useidx]:""),$catalog);
}
}
}
}
}
?>
+214
View File
@@ -0,0 +1,214 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 14/gen/2016
*/
class DatatablesHelper {
private static $instCount = 0;
public static function getResult($useModel, $permissionFlagRequired, array $exposedModel, array $dataFilter = array()){
$ret = new stdClass();
$ret->draw = $_POST["draw"];
$ret->recordsTotal = 0;
$ret->recordsFiltered = 0;
$ret->data = array();
if (AdminLoginManager::isLogged()){
$admin = AdminLoginManager::getLogged();
if ($admin->hasRole($permissionFlagRequired)){
$dao = GlobalVariables::get("dao");
$filter = $dataFilter;
$options = array('limit'=>$_POST["length"], 'skip'=>$_POST["start"]);
if (sizeof($_POST["order"])>0){
foreach ($_POST["order"] as $details){
$key = $_POST["columns"][$details["column"]]["data"];
$options["sort"][$key] = strcasecmp($details["dir"], "asc")==0?1:-1;
}
}
$models = array();
if (array_key_exists("search", $_POST) && array_key_exists("value", $_POST["search"]) && strcmp(trim($_POST["search"]["value"]),"")!=0 ){
unset($options["sort"]);
$models = $dao->search($useModel, trim($_POST["search"]["value"]), $filter, $options);
$ret->recordsTotal = $dao->searchCount($useModel, trim($_POST["search"]["value"]));
$ret->recordsFiltered = $dao->searchCount($useModel, trim($_POST["search"]["value"]), $filter);
}
else {
$models = $dao->query($useModel, $filter, $options);
$ret->recordsTotal = $dao->count($useModel);
$ret->recordsFiltered = $dao->count($useModel,$filter);
}
if (sizeof($models)>0){
foreach ($models as $model){
$result = self::getObjectFromFieldsArray($model, $exposedModel);
$ret->data[] = $result;
}
}
}
}
return $ret;
}
private static function getObjectFromFieldsArray($obj,array $fieldArr){
$rval = new stdClass();
if (sizeof($fieldArr)>0){
foreach ($fieldArr as $key=>$val){
if (is_array($val)){
$rval->$key = self::getObjectFromFieldsArray($obj->$key, $val);
}
else {
if ($obj->$key instanceof MongoDB\BSON\UTCDateTime){
// $rval->$key = date("d-m-Y H:i",$obj->$key->sec);
$rval->$key = date("d-m-Y H:i", $obj->$key->toDateTime()->getTimestamp() );
}
else {
$rval->$key = $obj->$key;
}
if (is_callable($val)){
$rval->$key = $val($rval->$key,$obj);
}
}
}
}
return $rval;
}
public static function generateTable($backendPage, array $columns, array $htmlOpts = array()){
$tabId = "datatable_".self::$instCount;
$toolbarClass = "toolbar_".self::$instCount++;
$buttonDiv = "";
$buttonJs = "";
$useButtons = false;
if (array_key_exists("buttons",$htmlOpts) && is_array($htmlOpts["buttons"]) && sizeof($htmlOpts["buttons"])>0){
$useButtons = true;
$i = 0;
foreach ($htmlOpts["buttons"] as $buttonData){
$buttonDiv.='<span id="'.$tabId."btn".$i.'" class="'.$buttonData["icon"].'" >&nbsp;</span>';
$buttonJs.='$("#'.$tabId."btn".$i.'").click(function(){'.
'if ($("tr.selected").length>0){'.
'var useForm = $("div.' . $toolbarClass . ' form");'.
'useForm.attr("action","'.$buttonData["page"].'").find("input").val($("tr.selected td:last-child").html());'.
'useForm.submit();'.
'}'.
'});';
$i++;
}
$buttonDiv.='<form action="" method="POST" style="display:none;"><input type="hidden" name="id" value=""/></form>';
}
$additionalControlbarHtml = null;
if (array_key_exists("additionalControlbarHtml",$htmlOpts)){
$additionalControlbarHtml = $htmlOpts["additionalControlbarHtml"];
}
$additionalPostFunction = null;
if (array_key_exists("additionalPostFunction",$htmlOpts)){
$additionalPostFunction = $htmlOpts["additionalPostFunction"];
}
$initCompleteFunction = null;
if (array_key_exists("initCompleteFunction",$htmlOpts)){
$initCompleteFunction = $htmlOpts["initCompleteFunction"];
}
$columns[] = array("label"=>"id","data"=>"id");
$colLabels = "<tr>";
$jsCols = array();
$i=0;
foreach ($columns as $col){
$colLabels.= '<th>'.$col["label"].'</th>';
$jsCols[]= '{"data":"'.$col["data"].'"}';
if (array_key_exists("sort",$col)){
$defaultOrder[]= '['.$i.',"'.$col["sort"].'"]';
}
$i++;
}
$colLabels.= '</tr>';
echo '<table id="'.$tabId.'"><thead>'.$colLabels.'</thead><tfoot>'.$colLabels.'</tfoot><tbody></tbody></table>';
?>
<script type="text/javascript">
$(document).ready(function(){
var dTab = $("#<?php echo $tabId;?>").DataTable({
<?php echo '"dom":"<\'toolbar '.$toolbarClass.'\' f>rtip",'."\n";?>
"language": {"url": "<?php echo GUIHandler::getJavascriptsUrl();?>datatables.ita.lang"},
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo GUIHandler::getBaseUrl();?>admin/tablesBackends/<?php echo $backendPage; ?>",
<?php
if (!is_null($additionalPostFunction)){
echo '"data":'.$additionalPostFunction.",";
}
?>
"type": "POST"
},
"columns": [ <?php echo implode(",", $jsCols);?> ],
<?php
if (sizeof($defaultOrder)>0){
echo '"order": ['. implode(",", $defaultOrder) . '],';
}
?>
"initComplete": function () {
<?php
if(!is_null($additionalControlbarHtml)){
echo '$("div.'.$toolbarClass.'").prepend(\''.$additionalControlbarHtml.'\');';
}
?>
$("div.<?php echo $toolbarClass;?>").prepend('<?php echo $buttonDiv;?>');
<?php echo $buttonJs;?>
<?php
if(!is_null($initCompleteFunction)){
echo $initCompleteFunction;
}
?>
},
"columnDefs": [
{"className":"lastVisible","targets":[<?php echo sizeof($columns)-2;?>]},
{"className":"hidden","targets":[<?php echo sizeof($columns)-1;?>]}
],
"searchDelay":600,
});
$('#<?php echo $tabId;?> tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
dTab.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
});
</script>
<?php
$details = array();
$details["toolbarClass"] = $toolbarClass;
$details["tableId"] = $tabId;
return $details;
}
}
?>
+83
View File
@@ -0,0 +1,83 @@
<?php
/*
Author: Riccardo Di Dato
Creation Date: 29/feb/2016
*/
class NotiziaBlock {
private $notizia;
public function __construct(NotiziaModel $notizia){
$this->notizia = $notizia;
}
public function __toString(){
$mainMedia = DaoMediaHandler::getMainMediaFromModel($this->notizia);
$mediaText = "";
if (!is_null($mainMedia)){
$mediaText = $mainMedia->asText(array("size"=>MediaRenderer::SIZE_MEDIUM,"clickable"=>true));
}
$rval = '<div class="notiziaBlock">';
$rval.= '<div class="notiziaMainMedia">'.$mediaText.'</div>';
$rval.= '<div class="notiziaTitle">'.$this->notizia->titolo.'</div>';
$rval.= '<div class="notiziaSubtitle">'.$this->notizia->sottotitolo.'</div>';
$rval.= '<div class="notiziaTesto">'.$this->notizia->testo.'</div>';
$rval.= "</div>";
return $rval;
}
}
class NotiziaCommentiList {
private $notizia;
public function __construct(NotiziaModel $notizia){
$this->notizia = $notizia;
}
public function __toString(){
$rval = '<div class="commentiBlock">';
$commenti = GlobalVariables::get("dao")->query("CommentoModel",array("notizia"=>$this->notizia->id));
if (sizeof($commenti)>0){
$rval.= "<ul>";
foreach ($commenti as $commento){
$commentoBlock = new CommentoBlock($commento);
$rval.= "<li>".$commentoBlock."</li>";
}
$rval.= "</ul>";
}
$rval.= "</div>";
return $rval;
}
}
class CommentoBlock {
private $commento;
public function __construct(CommentoModel $commento){
$this->commento = $commento;
}
public function __toString(){
$userModel = GlobalVariables::get("dao")->getFirst("UserModel",array("id"=>$this->commento->user));
$userString = "Utente cancellato";
if (!is_null($userModel)){
$userString = $userModel->nome." ".$userModel->cognome;
}
$rval = '<div class="commentoBlock">';
$rval.= '<div class="commentoTitolo">'.$this->commento->titolo.'</div>';
$rval.= '<div class="commentoTesto">'.$this->commento->testo.'</div>';
$rval.= '<div class="commentoUser">'.$userString.'</div>';
$rval.= '<div class="commentoDate">'.date("d-m-Y H:i",$this->commento->date->toDateTime()->getTimestamp()).'</div>';
$rval.= "</div>";
return $rval;
}
}
?>
+10
View File
@@ -0,0 +1,10 @@
<?php
class GUIException extends MultimessageException{
public function __construct($mixed){
if (!is_array($mixed)){
$mixed = array($mixed);
}
parent::__construct($mixed);
}
}

Some files were not shown because too many files have changed in this diff Show More