/**
  * Convenience method for parsing the result of an api request that
  * contains a json response body.
  *
  * @param RestfulResponse $result        result to parse
  * @param array           $successCodes  array of http status codes to
  *                                       treat as successful; an exception
  *                                       will be thrown if the http status
  *                                       code in the <var>$result<var>
  *                                       object does not match one of the
  *                                       success codes
  *
  * @see RestfulRequest::sendRequest
  * @return array api response as an array of key-value pairs.
  * @throws ServiceException if api request was not successful
  */
 public static function parseJson($result, $successCodes = array(200, 201))
 {
     $responseBody = $result->getResponseBody();
     $responseCode = $result->getResponseCode();
     foreach ($successCodes as $successCode) {
         if ($responseCode == $successCode) {
             return json_decode($responseBody, true);
         }
     }
     throw new ServiceException($responseCode, $responseBody);
 }
예제 #2
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di registrare un nuovo utente
    method: POST
    params: 
      hash: username e password oscurati (vedi /js/site.js Login.encrypt) 
    returns:
      success: false => errore, true => OK
      error: messaggio di errore se success e' false
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$av = new AutoValidator("frm-register", $_POST);
if ($av->validate()) {
    if (isset($_POST['question']) && $_POST['question'] == "10") {
        $email = db_escape(purify(trim(Charset::Utf8ToDB($_POST['email']))));
        $creds = LoginUtils::HashToCredentials(db_escape($_POST['hash']));
        $username = db_escape(purify(trim(Charset::Utf8ToDB($creds['username']))));
        $password = db_escape(purify(trim(Charset::Utf8ToDB($creds['password']))));
        // Username libero?
        if (!DB::FindOne("SELECT 1 FROM users WHERE user = \"{$username}\"")) {
            // Legacy: Un timestamp sarebbe stato meglio, ma non dobbiamo fare nulla con questo dato, quindi va bene cosi'
            $data = date("d/m/Y G:i");
            $description = "Normal User";
            $md5 = LoginUtils::Md5FromCredentials($username, $password);
            // Tutto a posto
            exequery(sprintf('INSERT INTO users (user, mail, ip, os_browser, date, description, permission, verified, md5, last_login_timestamp, last_login_ip, newsletter)
                  VALUES ("%s", "%s", "%s", "%s", "%s", "%s", %s, %s, "%s", %s, "%s", %s)', $username, $email, get_ip(), db_escape(purify($_SERVER["HTTP_USER_AGENT"])), $data, $description, User::PERMISSION_USER, 1, $md5, time(), get_ip(), 1));
예제 #3
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di spostare un messaggio dal cestino alla posta in arrivo
    method: GET
    params:
      id : id del messaggio da spostare
      dataType : formato della risposta (vedere Restful::PrintResponse)
    returns:
      success: false => errore, true => OK
  */
require_once "__inc__.php";
$response = new RestfulResponse(isset($_POST['dataType']) ? $_POST['dataType'] : 'html');
validate_num($_POST['id']);
$ms = new MessageService($currentUser['id']);
$ms->restoreFromTrash($_POST['id']);
$response->setSuccess(true);
$response->send();
예제 #4
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Permette di cercare il nome di un utente da una parte del nome
    method: POST
    params:
      name : parte del nome da cercare
      num_records : numero massimo di nomi che deve ritornare (limite di 50 per evitare di dare troppe informazioni)
    returns:
      results : array con nomi degli utenti
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
if (isset($_POST['term'])) {
    $term = Charset::Utf8ToDB($_POST['term']);
    $num_records = @$_POST['num_records'];
    // Validazione
    if (!isset($num_records)) {
        $num_records = 20;
    }
    if ($num_records > 50) {
        $num_records = 50;
    }
    $results = UserSearch::Find($term, $num_records);
    $response->set('results', $results);
    $response->setSuccess(true);
} else {
    $response->setError("Missing term param");
}
예제 #5
0
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di spostare un messaggio dal cestino alla posta in arrivo
    method: POST
    params:
      to : nome dell'utente a cui inviare i messaggi
      subject : oggetto del messaggio
      message : testo del messaggio
      important : flag se il messaggio è importante o no
      multiple : flag se il messaggio è multiplo o no
    returns:
      success: false => errore, true => OK
  */
require_once "__inc__.php";
$response = new RestfulResponse();
//Salvo i parametri
$to = Charset::Utf8ToDB($_POST['to']);
$subject = Charset::Utf8ToDB($_POST['subject']);
$message = Charset::Utf8ToDB($_POST['message']);
$important = isset($_POST['important']) ? $_POST['important'] : false;
//boolean
$multiple = isset($_POST['multiple']) ? $_POST['multiple'] : false;
//boolean
$av = new AutoValidator("message-write", $_POST);
if ($av->validate()) {
    //Controllo solo multiple, to e important (gli altri due vengono controllati in MessageService)
    $important = $currentUser->isAdmin() && $important ? 1 : 0;
    $multiple = $multiple == "true";
    if ($multiple != 1) {
        $to = db_escape($to);
예제 #6
0
    method: POST
    params:
      id : id del messaggio da visualizzare
    returns:
      subject : oggetto del messaggio
      from_or_to : stringa 'A' o 'Da'
      date : data dell'invio del messaggio (formattata in maniera leggibile)
      discursive_date: data dell'invio del messaggio (gg/mm/yy HH:mm)
      important : true o false se il messaggio è importante o no
      message_html : testo del messaggio (formattato in HTML)
      message_plain : testo del messaggio (non formattato)
      reply : true o false se bisonga mostrare il bottone rispondi o no
      from_to_user : nome dell'utente che ha inviato o ricevuto il messaggio
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$r = '';
$id = $_POST['id'];
validate_num($id);
$ms = new MessageService($currentUser['id']);
$m = $ms->getMessage($id);
if ($m['to_id'] == $currentUser['id']) {
    $ms->viewed($id);
}
$from_to = 'A';
$user = '******';
$write = "";
if ($m['to_id'] == $currentUser['id']) {
    $from_to = 'Da';
    $user = '******';
}
예제 #7
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di aggiungere un voto ad un sondaggio
    method: POST
    params: 
      topic_id: id del topic (base) su cui votare
      vote: id della scelta del sondaggio da votare
    returns:
      success: false => errore, true => OK
      results_html: html contenente i risultati del sondaggio
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
if ($currentUser->isLogged()) {
    // Valida i campi di input
    validate_num($_POST['topic_id']);
    validate_num($_POST['vote']);
    $topic = new Topic($_POST['topic_id']);
    if ($topic->isPoll() && $topic->isViewableBy($currentUser)) {
        $poll_data = $topic->getPollData();
        if (!$poll_data['user_has_voted']) {
            // Voto valido?
            $valid_vote = false;
            foreach ($poll_data['choices'] as $choice) {
                if ($choice['id'] == $_POST['vote']) {
                    $valid_vote = true;
                    break;
                }
예제 #8
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di aggiungere una risposta ad un topic
    method: POST
    params: 
      topic_id: id del topic (base) su cui aggiungere una risposta
      message: messaggio
    returns:
      success: false => errore, true => OK
      post_html: html contenente il post appena inserito
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$av = new AutoValidator("frm-forum-reply", $_POST);
if ($av->validate()) {
    if ($currentUser->isLogged()) {
        // Valida i campi di input
        validate_num($_POST['topic_id']);
        $topic = new Topic($_POST['topic_id']);
        $message = db_escape(Charset::Utf8ToDB($_POST['message']));
        if (!Forum::IsUserFlooding($currentUser)) {
            if (!$topic['locked']) {
                // Trova il forum_id
                $values = DB::FindOne("SELECT argument FROM forum_posts WHERE id = {$_POST['topic_id']}");
                $forum_id = $values['argument'];
                exequery(sprintf("INSERT INTO forum_posts (user_id, root_topic, argument, message, type, post_date, last_post_date, ip) \n                          VALUES(%d, %d, %d, '%s', %d, %d, %d, '%s')", $currentUser['id'], $_POST['topic_id'], $forum_id, $message, Forum::TYPE_POST, time(), time(), get_ip()));
                $id = DB::LastId();
                $post = new ForumPost($id);
예제 #9
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Ricava il contenuto raw di un post (o topic) del forum
      La richiesta dev'essere effettuata da un utente che ha i permessi per editare il post/topic
    method: GET
    params: 
      id: id del post/topic
    returns:
      informazioni del post/topic, inclusi:
      - messaggio, username del postatore
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
validate_num($_GET['id']);
if ($currentUser->isLogged()) {
    $post = new ForumPost($_GET['id']);
    if ($post->isViewableBy($currentUser)) {
        $response->set('message', $post['message']);
        $response->set('username', $post['user']);
    } else {
        $response->setError("Non hai i permessi per leggere queste informazioni.");
    }
} else {
    $response->setError("Non loggato");
}
echo $response->send();
예제 #10
0
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di inserire un nuovo topic nel forum
    method: POST
    params: 
      forum_id: id del forum in cui inserire il topic
      subject: oggetto del topic
      message: messaggio
      poll (facoltativo): lista di opzioni da inserire in un sondaggio (implica che il post e' un sondaggio)
    returns:
      success: false => errore, true => OK
      topic_url: url (relativo) del topic appena inserito
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$av = new AutoValidator("frm-forum-post", $_POST);
if ($av->validate()) {
    if ($currentUser->isLogged()) {
        // Valida i campi di input
        validate_num($_POST['forum_id']);
        $subject = db_escape(Charset::Utf8ToDB($_POST['subject']));
        $message = db_escape(Charset::Utf8ToDB($_POST['message']));
        $is_poll = isset($_POST['poll']);
        // Le domande del sondaggio vengono memorizzate nel campo
        // "poll" come array serializzato. Se "poll" e' null, allora
        // vuol dire che il topic non e' un sondaggio
        if ($is_poll) {
            $poll_questions = explode("\n", trim(purify(Charset::Utf8ToDB($_POST['poll']))));
            if (count($poll_questions) >= 2) {
                $poll_data = db_escape(serialize($poll_questions));
예제 #11
0
<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di far visualizzare una tabella con i messaggi presenti in una cartella
    method: POST
    params:
      folder : cartella di cui si vogliono vedere i messaggi
      order : tipo di ordinamento
      p : pagina da visualizzare
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
//Salvo i parametri
$folder = isset($_POST['folder']) ? $_POST['folder'] : '';
$order = isset($_POST['order']) ? $_POST['order'] : '';
$page = isset($_POST['p']) ? (int) $_POST['p'] : 1;
//Controllo di folder
$to_field_name = '';
switch ($folder) {
    case 'inbox':
        $response->set('to_field_name', 'Da');
        $to_field = 'from_id';
        $folder = MessageService::INBOX;
        break;
    case 'sent':
        $response->set('to_field_name', 'A');
        $to_field = 'to_id';
        $folder = MessageService::SENT;
        break;
예제 #12
0
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Ricava il contenuto raw di un post (o topic) del forum
      La richiesta dev'essere effettuata da un utente che ha i permessi per editare il post/topic
    method: GET e POST combinato
    params: 
      id (GET): id del post/topic
      value (POST): nuovo contenuto
    returns:
      success => true|false
      value => HTML contenente il nuovo post
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
validate_num($_GET['id']);
if ($currentUser->isLogged()) {
    $q = exequery("SELECT argument, user_id FROM forum_posts WHERE id = {$_GET['id']}");
    $values = mysqli_fetch_array($q);
    // Puo' editare?
    if ($currentUser->isModOfForum($values['argument']) || $currentUser["id"] == $values['user_id']) {
        $message = db_escape(Charset::Utf8ToDB($_POST['value']));
        exequery("UPDATE forum_posts SET message = '{$message}', edit_date = " . time() . ", edit_by = {$currentUser['id']}\n              WHERE id = {$_GET['id']}");
        $post = new ForumPost($_GET['id']);
        $response->set("value", $post->getParsedMessage());
        $response->setSuccess(true);
    } else {
        $response->setError("Non hai i permessi per modificare questo post");
    }
} else {
예제 #13
0
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/** Si occupa di autenticare l'utente 
    method: POST
    params: 
      hash: username e password oscurati (see /js/site.js Login.encrypt) 
      usecookie: false => non impostare cookie, true => imposta cookie
    returns:
      success: false => errore, true => OK
      banned_message (optional): un messaggio di ban se l'utente e' bannato

  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$hash = $_POST['hash'];
if (isset($hash)) {
    $currentUser = UserFactory::CreateFromLoginHash($hash);
    if ($currentUser->isLogged()) {
        $response->setSuccess(true);
        // Aggiorna ip, data ultimo login
        exequery(sprintf("UPDATE users SET previous_login_timestamp = '%d', \n                                 last_login_timestamp = '%d', \n                                 last_login_ip = '%s' \n                        WHERE id = %d", $currentUser['last_login_timestamp'], time(), get_ip(), $currentUser['id']));
        // Logga
        Log::Info(sprintf("%s effettua il login", $currentUser['username']));
        $_SESSION['login_hash'] = $currentUser['md5'];
        if ($_POST['usecookie']) {
            setcookie('login_hash', $currentUser['md5'], time() + 60 * 60 * 24 * 7, '/');
        }
    } else {
        if ($currentUser->isBanned()) {
예제 #14
0
<?php

/** Si occupa di recuperare la password dell'utente
    method: POST
    params: 
      hash: obscured username and password (see /js/site.js Login.encrypt) 
      usecookie: "0" => do not set cookie, "1" => set cookie
    returns:
      success: "0" => error happened, "1" => OK
      banned_message (optional): a ban message if the user is currently banned
      
  */
require_once "__inc__.php";
$response = new RestfulResponse("json");
$username = db_escape(Charset::Utf8ToDB($_POST['user']));
$userObj = new User("user = \"{$username}\"");
if ($userObj->isValid()) {
    $ip = get_ip();
    $url = $site_url . "/p/login/resetPassword.php?token={$userObj['md5']}&uid={$userObj['id']}";
    $message = $userObj['username'] . ",<br/>\nè stata inoltrata una richiesta da [{$ip}] per resettare la tua password su <a href=\"{$site_url}\">www.pierotofy.it</a>.<br/>\n<br/>\nPer continuare la procedura visita il link qui sotto riportato:<br/><br/>\n\n<a href=\"{$url}\">{$url}</a>\n";
    try {
        if (Mailer::SendEmail("*****@*****.**", "*****@*****.**", "Recupero password", $message)) {
            $response->setSuccess(true);
        } else {
            $response->setError("E' successo un errore durante l'invio dell'e-mail.");
        }
    } catch (Exception $e) {
        $response->setError("Eccezione: " . $e->getMessage());
    }
} else {
    $response->setError("L'utente non e' valido.");