Fix php style

This commit is contained in:
osaajani 2020-01-17 18:19:25 +01:00
parent 461bd9c98d
commit b8bd067dc7
59 changed files with 2307 additions and 1868 deletions

View File

@ -1,4 +1,14 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace adapters; namespace adapters;
/** /**
@ -11,13 +21,21 @@
interface AdapterInterface interface AdapterInterface
{ {
/** /**
* Classname of the adapter * Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct(string $number, string $datas);
/**
* Classname of the adapter.
*/ */
public static function meta_classname(): string; public static function meta_classname(): string;
/** /**
* Name of the adapter. * Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.) * It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
*/ */
public static function meta_name(): string; public static function meta_name(): string;
@ -28,62 +46,56 @@
public static function meta_description(): string; public static function meta_description(): string;
/** /**
* Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value) * Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value).
*/ */
public static function meta_datas_help(): string; public static function meta_datas_help(): string;
/** /**
* List of entries we want in datas for the adapter * List of entries we want in datas for the adapter.
*
* @return array : Eachline line is a field as an array with keys : name, title, description, required * @return array : Eachline line is a field as an array with keys : name, title, description, required
*/ */
public static function meta_datas_fields(): array; public static function meta_datas_fields(): array;
/** /**
* Does the implemented service support flash smss * Does the implemented service support flash smss.
*/ */
public static function meta_support_flash(): bool; public static function meta_support_flash(): bool;
/** /**
* Does the implemented service support status change * Does the implemented service support status change.
*/ */
public static function meta_support_status_change(): bool; public static function meta_support_status_change(): bool;
/** /**
* Adapter constructor, called when instanciated by RaspiSMS * Method called to send a SMS to a number.
* @param string $number : Phone number the adapter is used for *
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct (string $number, string $datas);
/**
* Method called to send a SMS to a number
* @param string $destination : Phone number to send the sms to * @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send * @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS * @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed Uid of the sended message if send, False else * @return mixed Uid of the sended message if send, False else
*/ */
public function send(string $destination, string $text, bool $flash = false); public function send(string $destination, string $text, bool $flash = false);
/** /**
* Method called to read unread SMSs of the number * Method called to read unread SMSs of the number.
*
* @return array : Array of the sms reads * @return array : Array of the sms reads
*/ */
public function read(): array; public function read(): array;
/** /**
* Method called to verify if the adapter is working correctly * Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid * should be use for exemple to verify that credentials and number are both valid.
* @return boolean : False on error, true else *
* @return bool : False on error, true else
*/ */
public function test(): bool; public function test(): bool;
/** /**
* Method called on reception of a status update notification for a SMS * Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')] * @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
*/ */
public static function status_change_callback(); public static function status_change_callback();

View File

@ -1,4 +1,14 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace adapters; namespace adapters;
/** /**
@ -11,29 +21,64 @@
class GammuAdapter implements AdapterInterface class GammuAdapter implements AdapterInterface
{ {
/** /**
* Classname of the adapter * Phone number using the adapter.
*/ */
public static function meta_classname() : string { return __CLASS__; } private $number;
/**
* Datas used to configure interaction with the implemented service. (e.g : Api credentials, ports numbers, etc.).
*/
private $datas;
/**
* Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct(string $number, string $datas)
{
$this->number = $number;
$this->datas = json_decode($datas, true);
}
/**
* Classname of the adapter.
*/
public static function meta_classname(): string
{
return __CLASS__;
}
/** /**
* Name of the adapter. * Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.) * It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
*/ */
public static function meta_name() : string { return 'Gammu'; } public static function meta_name(): string
{
return 'Gammu';
}
/** /**
* Description of the adapter. * Description of the adapter.
* A short description of the service the adapter implements. * A short description of the service the adapter implements.
*/ */
public static function meta_description() : string { return 'Utilisation du logiciel Gammu qui doit être installé sur le serveur et configuré. Voir https://wammu.eu.'; } public static function meta_description(): string
{
return 'Utilisation du logiciel Gammu qui doit être installé sur le serveur et configuré. Voir https://wammu.eu.';
}
/** /**
* Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value) * Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value).
*/ */
public static function meta_datas_help() : string { return 'Fichier de configuration à fournir à Gammu pour utiliser ce modem.'; } public static function meta_datas_help(): string
{
return 'Fichier de configuration à fournir à Gammu pour utiliser ce modem.';
}
/** /**
* List of entries we want in datas for the adapter * List of entries we want in datas for the adapter.
*
* @return array : Every line is a field as an array with keys : name, title, description, required * @return array : Every line is a field as an array with keys : name, title, description, required
*/ */
public static function meta_datas_fields(): array public static function meta_datas_fields(): array
@ -55,44 +100,28 @@
} }
/** /**
* Does the implemented service support flash smss * Does the implemented service support flash smss.
*/ */
public static function meta_support_flash() : bool { return false ; } public static function meta_support_flash(): bool
/**
* Does the implemented service support status change
*/
public static function meta_support_status_change() : bool { return false; }
/**
* Phone number using the adapter
*/
private $number;
/**
* Datas used to configure interaction with the implemented service. (e.g : Api credentials, ports numbers, etc.).
*/
private $datas;
/**
* Adapter constructor, called when instanciated by RaspiSMS
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct (string $number, string $datas)
{ {
$this->number = $number; return false;
$this->datas = json_decode($datas, true);
} }
/**
* Does the implemented service support status change.
*/
public static function meta_support_status_change(): bool
{
return false;
}
/** /**
* Method called to send a SMS to a number * Method called to send a SMS to a number.
*
* @param string $destination : Phone number to send the sms to * @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send * @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS * @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed : Uid of the sended message if send, False else * @return mixed : Uid of the sended message if send, False else
*/ */
public function send(string $destination, string $text, bool $flash = false) public function send(string $destination, string $text, bool $flash = false)
@ -123,7 +152,7 @@
} }
$result = $this->exec_command($command_parts); $result = $this->exec_command($command_parts);
if ($result['return'] != 0) if (0 !== $result['return'])
{ {
return false; return false;
} }
@ -143,11 +172,12 @@
if ($matches[1] ?? false) if ($matches[1] ?? false)
{ {
$uid = $matches[1]; $uid = $matches[1];
break; break;
} }
} }
if ($uid === false) if (false === $uid)
{ {
return false; return false;
} }
@ -155,9 +185,9 @@
return $uid; return $uid;
} }
/** /**
* Method called to read SMSs of the number * Method called to read SMSs of the number.
*
* @return array : Array of the sms reads * @return array : Array of the sms reads
*/ */
public function read(): array public function read(): array
@ -173,7 +203,7 @@
]; ];
$return = $this->exec_command($command_parts); $return = $this->exec_command($command_parts);
if ($return['return'] != 0) if (0 !== $return['return'])
{ {
return []; return [];
} }
@ -182,7 +212,7 @@
foreach ($return['output'] as $line) foreach ($return['output'] as $line)
{ {
$decode = json_decode($line, true); $decode = json_decode($line, true);
if ($decode === null) if (null === $decode)
{ {
continue; continue;
} }
@ -198,11 +228,11 @@
return $smss; return $smss;
} }
/** /**
* Method called to verify if the adapter is working correctly * Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid * should be use for exemple to verify that credentials and number are both valid.
* @return boolean : False on error, true else *
* @return bool : False on error, true else
*/ */
public function test(): bool public function test(): bool
{ {
@ -210,9 +240,9 @@
return true; return true;
} }
/** /**
* Method called on reception of a status update notification for a SMS * Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')] * @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
*/ */
public static function status_change_callback() public static function status_change_callback()
@ -220,9 +250,9 @@
return false; return false;
} }
/** /**
* Function to unlock pin * Function to unlock pin.
*
* @return bool : False on error, true else * @return bool : False on error, true else
*/ */
private function unlock_sim(): bool private function unlock_sim(): bool
@ -243,7 +273,6 @@
$result = $this->exec_command($command_parts); $result = $this->exec_command($command_parts);
//Check security status //Check security status
$command_parts = [ $command_parts = [
'gammu', 'gammu',
@ -254,7 +283,7 @@
$result = $this->exec_command($command_parts); $result = $this->exec_command($command_parts);
if ($result['return'] != 0) if (0 !== $result['return'])
{ {
return false; return false;
} }
@ -262,10 +291,11 @@
return $this->search_for_string($result['output'], 'nothing'); return $this->search_for_string($result['output'], 'nothing');
} }
/** /**
* Function to execute a command and transmit it to Gammu * Function to execute a command and transmit it to Gammu.
*
* @param array $command_parts : Commands parts to be join with a space * @param array $command_parts : Commands parts to be join with a space
*
* @return array : ['return' => int:return code of command, 'output' => array:each raw is a line of the output] * @return array : ['return' => int:return code of command, 'output' => array:each raw is a line of the output]
*/ */
private function exec_command(array $command_parts): array private function exec_command(array $command_parts): array
@ -273,7 +303,6 @@
//Add redirect of error to stdout //Add redirect of error to stdout
$command_parts[] = '2>&1'; $command_parts[] = '2>&1';
$command = implode(' ', $command_parts); $command = implode(' ', $command_parts);
$output = []; $output = [];
@ -283,11 +312,12 @@
return ['return' => (int) $return_var, 'output' => $output]; return ['return' => (int) $return_var, 'output' => $output];
} }
/** /**
* Function to search a string in the output of an executer command * Function to search a string in the output of an executer command.
*
* @param array $output : Text to search in where each raw is a line * @param array $output : Text to search in where each raw is a line
* @param string $search : Text to search for * @param string $search : Text to search for
*
* @return bool : True if found, false else * @return bool : True if found, false else
*/ */
private function search_for_string(array $output, string $search): bool private function search_for_string(array $output, string $search): bool
@ -296,7 +326,7 @@
foreach ($output as $line) foreach ($output as $line)
{ {
$find = mb_stristr($line, $search); $find = mb_stristr($line, $search);
if ($find !== false) if (false !== $find)
{ {
break; break;
} }
@ -304,6 +334,4 @@
return (bool) $find; return (bool) $find;
} }
} }

View File

@ -1,6 +1,17 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace adapters; namespace adapters;
use \Ovh\Api;
use Ovh\Api;
/** /**
* Interface for phones adapters * Interface for phones adapters
@ -12,29 +23,82 @@
class OvhSmsAdapter implements AdapterInterface class OvhSmsAdapter implements AdapterInterface
{ {
/** /**
* Classname of the adapter * Phone number using the adapter.
*/ */
public static function meta_classname() : string { return __CLASS__; } private $number;
/**
* Datas used to configure interaction with the implemented service. (e.g : Api credentials, ports numbers, etc.).
*/
private $datas;
/**
* OVH Api instance.
*/
private $api;
/**
* Number formated to be compatible with http query according to the ovh way.
*/
private $formatted_number;
/**
* Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct(string $number, string $datas)
{
$this->number = $number;
$this->formatted_number = str_replace('+', '00', $number);
$this->datas = json_decode($datas, true);
$this->api = new Api(
$this->datas['app_key'],
$this->datas['app_secret'],
$this->datas['endpoint'],
$this->datas['consumer_key']
);
}
/**
* Classname of the adapter.
*/
public static function meta_classname(): string
{
return __CLASS__;
}
/** /**
* Name of the adapter. * Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.) * It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
*/ */
public static function meta_name() : string { return 'OVH SMS'; } public static function meta_name(): string
{
return 'OVH SMS';
}
/** /**
* Description of the adapter. * Description of the adapter.
* A short description of the service the adapter implements. * A short description of the service the adapter implements.
*/ */
public static function meta_description() : string { return 'Solution de SMS proposé par le groupe OVH, https://www.ovhtelecom.fr/sms/.'; } public static function meta_description(): string
{
return 'Solution de SMS proposé par le groupe OVH, https://www.ovhtelecom.fr/sms/.';
}
/** /**
* Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value) * Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value).
*/ */
public static function meta_datas_help() : string { return 'Clefs API OVH, https://api.ovh.com/createToken/index.cgi.'; } public static function meta_datas_help(): string
{
return 'Clefs API OVH, https://api.ovh.com/createToken/index.cgi.';
}
/** /**
* List of entries we want in datas for the adapter * List of entries we want in datas for the adapter.
*
* @return array : Every line is a field as an array with keys : name, title, description, required * @return array : Every line is a field as an array with keys : name, title, description, required
*/ */
public static function meta_datas_fields(): array public static function meta_datas_fields(): array
@ -74,61 +138,28 @@
} }
/** /**
* Does the implemented service support flash smss * Does the implemented service support flash smss.
*/ */
public static function meta_support_flash() : bool { return false ; } public static function meta_support_flash(): bool
/**
* Does the implemented service support status change
*/
public static function meta_support_status_change() : bool { return true; }
/**
* Phone number using the adapter
*/
private $number;
/**
* Datas used to configure interaction with the implemented service. (e.g : Api credentials, ports numbers, etc.).
*/
private $datas;
/**
* OVH Api instance
*/
private $api;
/**
* Number formated to be compatible with http query according to the ovh way
*/
private $formatted_number;
/**
* Adapter constructor, called when instanciated by RaspiSMS
* @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/
public function __construct (string $number, string $datas)
{ {
$this->number = $number; return false;
$this->formatted_number = str_replace('+', '00', $number);
$this->datas = json_decode($datas, true);
$this->api = new Api(
$this->datas['app_key'],
$this->datas['app_secret'],
$this->datas['endpoint'],
$this->datas['consumer_key']
);
} }
/**
* Does the implemented service support status change.
*/
public static function meta_support_status_change(): bool
{
return true;
}
/** /**
* Method called to send a SMS to a number * Method called to send a SMS to a number.
*
* @param string $destination : Phone number to send the sms to * @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send * @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS * @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed Uid of the sended message if send, False else * @return mixed Uid of the sended message if send, False else
*/ */
public function send(string $destination, string $text, bool $flash = false) public function send(string $destination, string $text, bool $flash = false)
@ -145,14 +176,15 @@
$response = $this->api->post($endpoint, $params); $response = $this->api->post($endpoint, $params);
$nb_invalid_receivers = count(($response['invalidReceivers'] ?? [])); $nb_invalid_receivers = \count(($response['invalidReceivers'] ?? []));
if ($nb_invalid_receivers > 0) if ($nb_invalid_receivers > 0)
{ {
return false; return false;
} }
$uids = $response['ids'] ?? []; $uids = $response['ids'] ?? [];
return ($uids[0] ?? false);
return $uids[0] ?? false;
} }
catch (\Exception $e) catch (\Exception $e)
{ {
@ -160,9 +192,9 @@
} }
} }
/** /**
* Method called to read SMSs of the number * Method called to read SMSs of the number.
*
* @return array : Array of the sms reads * @return array : Array of the sms reads
*/ */
public function read(): array public function read(): array
@ -174,7 +206,7 @@
$endpoint = '/sms/'.$this->datas['service_name'].'/virtualNumbers/'.$this->formatted_number.'/incoming'; $endpoint = '/sms/'.$this->datas['service_name'].'/virtualNumbers/'.$this->formatted_number.'/incoming';
$uids = $this->api->get($endpoint); $uids = $this->api->get($endpoint);
if (!is_array($uids) || !$uids) if (!\is_array($uids) || !$uids)
{ {
return []; return [];
} }
@ -210,11 +242,11 @@
} }
} }
/** /**
* Method called to verify if the adapter is working correctly * Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid * should be use for exemple to verify that credentials and number are both valid.
* @return boolean : False on error, true else *
* @return bool : False on error, true else
*/ */
public function test(): bool public function test(): bool
{ {
@ -230,9 +262,8 @@
//Check virtualnumber //Check virtualnumber
$endpoint = '/sms/virtualNumbers/'.$this->formatted_number; $endpoint = '/sms/virtualNumbers/'.$this->formatted_number;
$response = $this->api->get($endpoint); $response = $this->api->get($endpoint);
$success = $success && (bool) $response;
return $success; return $success && (bool) $response;
} }
catch (\Exception $e) catch (\Exception $e)
{ {
@ -240,9 +271,9 @@
} }
} }
/** /**
* Method called on reception of a status update notification for a SMS * Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')] * @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
*/ */
public static function status_change_callback() public static function status_change_callback()
@ -250,7 +281,7 @@
$uid = $_GET['id'] ?? false; $uid = $_GET['id'] ?? false;
$dlr = $_GET['dlr'] ?? false; $dlr = $_GET['dlr'] ?? false;
if ($uid === false || $dlr === false) if (false === $uid || false === $dlr)
{ {
return false; return false;
} }
@ -259,15 +290,16 @@
{ {
case 1: case 1:
$status = 'delivered'; $status = 'delivered';
break;
break;
case 2: case 2:
case 16: case 16:
$status = 'failed'; $status = 'failed';
break;
break;
default: default:
$status = 'unknown'; $status = 'unknown';
break; break;
} }

View File

@ -1,4 +1,14 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace adapters; namespace adapters;
/** /**
@ -11,46 +21,7 @@
class TestAdapter implements AdapterInterface class TestAdapter implements AdapterInterface
{ {
/** /**
* Classname of the adapter * Phone number using the adapter.
*/
public static function meta_classname() : string { return __CLASS__; }
/**
* Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.)
*/
public static function meta_name() : string { return 'Test'; }
/**
* Description of the adapter.
* A short description of the service the adapter implements.
*/
public static function meta_description() : string { return 'A test adaptater that do not actually send or receive any message.'; }
/**
* Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value)
*/
public static function meta_datas_help() : string { return 'No datas.'; }
/**
* List of entries we want in datas for the adapter
* @return array : Eachline line is a field as an array with keys : name, title, description, required
*/
public static function meta_datas_fields() : array { return []; }
/**
* Does the implemented service support flash smss
*/
public static function meta_support_flash() : bool { return true ; }
/**
* Does the implemented service support status change
*/
public static function meta_support_status_change() : bool { return true; }
/**
* Phone number using the adapter
*/ */
private $number; private $number;
@ -59,20 +30,19 @@
*/ */
private $datas; private $datas;
/** /**
* Path for the file to read sms as a json from * Path for the file to read sms as a json from.
*/ */
private $test_file_read = PWD_DATAS.'/test_read_sms.json'; private $test_file_read = PWD_DATAS.'/test_read_sms.json';
/** /**
* Path for the file to write sms as a json in * Path for the file to write sms as a json in.
*/ */
private $test_file_write = PWD_DATAS.'/test_write_sms.json'; private $test_file_write = PWD_DATAS.'/test_write_sms.json';
/** /**
* Adapter constructor, called when instanciated by RaspiSMS * Adapter constructor, called when instanciated by RaspiSMS.
*
* @param string $number : Phone number the adapter is used for * @param string $number : Phone number the adapter is used for
* @param json string $datas : JSON string of the datas to configure interaction with the implemented service * @param json string $datas : JSON string of the datas to configure interaction with the implemented service
*/ */
@ -82,12 +52,73 @@
$this->datas = $datas; $this->datas = $datas;
} }
/**
* Classname of the adapter.
*/
public static function meta_classname(): string
{
return __CLASS__;
}
/** /**
* Method called to send a SMS to a number * Name of the adapter.
* It should probably be the name of the service it adapt (e.g : Gammu SMSD, OVH SMS, SIM800L, etc.).
*/
public static function meta_name(): string
{
return 'Test';
}
/**
* Description of the adapter.
* A short description of the service the adapter implements.
*/
public static function meta_description(): string
{
return 'A test adaptater that do not actually send or receive any message.';
}
/**
* Description of the datas expected by the adapter to help the user. (e.g : A list of expecteds Api credentials fields, with name and value).
*/
public static function meta_datas_help(): string
{
return 'No datas.';
}
/**
* List of entries we want in datas for the adapter.
*
* @return array : Eachline line is a field as an array with keys : name, title, description, required
*/
public static function meta_datas_fields(): array
{
return [];
}
/**
* Does the implemented service support flash smss.
*/
public static function meta_support_flash(): bool
{
return true;
}
/**
* Does the implemented service support status change.
*/
public static function meta_support_status_change(): bool
{
return true;
}
/**
* Method called to send a SMS to a number.
*
* @param string $destination : Phone number to send the sms to * @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send * @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS * @param bool $flash : Is the SMS a Flash SMS
*
* @return mixed Uid of the sended message if send, False else * @return mixed Uid of the sended message if send, False else
*/ */
public function send(string $destination, string $text, bool $flash = false) public function send(string $destination, string $text, bool $flash = false)
@ -100,9 +131,9 @@
return uniqid(); return uniqid();
} }
/** /**
* Method called to read SMSs of the number * Method called to read SMSs of the number.
*
* @return array : Array of the sms reads * @return array : Array of the sms reads
*/ */
public function read(): array public function read(): array
@ -119,7 +150,7 @@
foreach ($smss as $key => $sms) foreach ($smss as $key => $sms)
{ {
$decode_sms = json_decode($sms, true); $decode_sms = json_decode($sms, true);
if (NULL === $decode_sms) if (null === $decode_sms)
{ {
continue; continue;
} }
@ -130,20 +161,20 @@
return $return; return $return;
} }
/** /**
* Method called to verify if the adapter is working correctly * Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid * should be use for exemple to verify that credentials and number are both valid.
* @return boolean : False on error, true else *
* @return bool : False on error, true else
*/ */
public function test(): bool public function test(): bool
{ {
return true; return true;
} }
/** /**
* Method called on reception of a status update notification for a SMS * Method called on reception of a status update notification for a SMS.
*
* @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')] * @return mixed : False on error, else array ['uid' => uid of the sms, 'status' => New status of the sms ('unknown', 'delivered', 'failed')]
*/ */
public static function status_change_callback() public static function status_change_callback()
@ -165,14 +196,15 @@
{ {
case 'delivered': case 'delivered':
$return['status'] = 'delivered'; $return['status'] = 'delivered';
break;
break;
case 'failed': case 'failed':
$return['status'] = 'failed'; $return['status'] = 'failed';
break;
break;
default: default:
$return['status'] = 'unknown'; $return['status'] = 'unknown';
break; break;
} }

View File

@ -12,7 +12,7 @@
namespace controllers\internals; namespace controllers\internals;
/** /**
* Class to interact with adapters * Class to interact with adapters.
*/ */
class Adapter extends \descartes\InternalController class Adapter extends \descartes\InternalController
{ {
@ -20,7 +20,8 @@ namespace controllers\internals;
private const ADAPTERS_META_START = 'meta_'; private const ADAPTERS_META_START = 'meta_';
/** /**
* List adapters using internal metas * List adapters using internal metas.
*
* @return array * @return array
*/ */
public function list_adapters() public function list_adapters()
@ -47,9 +48,9 @@ namespace controllers\internals;
return $adapters; return $adapters;
} }
/** /**
* List Adapters files * List Adapters files.
*
* @return mixed (false|array) : array of adapters files path * @return mixed (false|array) : array of adapters files path
*/ */
public function list_files() public function list_files()
@ -66,7 +67,7 @@ namespace controllers\internals;
{ {
$len = mb_strlen(self::ADAPTERS_FILES_END); $len = mb_strlen(self::ADAPTERS_FILES_END);
$end = mb_substr($filename, -$len); $end = mb_substr($filename, -$len);
if ($end !== self::ADAPTERS_FILES_END) if (self::ADAPTERS_FILES_END !== $end)
{ {
continue; continue;
} }
@ -78,7 +79,10 @@ namespace controllers\internals;
} }
/** /**
* Read constants of an adapter * Read constants of an adapter.
*
* @param mixed $adapter_file
*
* @return mixed(array|bool) : False on error, array of constants name => value * @return mixed(array|bool) : False on error, array of constants name => value
*/ */
public function read_adapter_metas($adapter_file) public function read_adapter_metas($adapter_file)
@ -102,7 +106,7 @@ namespace controllers\internals;
{ {
$start_with = mb_substr($method->getName(), 0, mb_strlen(self::ADAPTERS_META_START)); $start_with = mb_substr($method->getName(), 0, mb_strlen(self::ADAPTERS_META_START));
if ($start_with !== self::ADAPTERS_META_START) if (self::ADAPTERS_META_START !== $start_with)
{ {
continue; continue;
} }

View File

@ -13,25 +13,16 @@ namespace controllers\internals;
class Command extends StandardController class Command extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a new command.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Command($this->bdd);
return $this->model;
}
/**
* Create a new command
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Command name * @param string $name : Command name
* @param string $script : Script file * @param string $script : Script file
* @param bool $admin : Is command admin only * @param bool $admin : Is command admin only
*
* @return mixed bool|int : False if cannot create command, id of the new command else * @return mixed bool|int : False if cannot create command, id of the new command else
*/ */
public function create(int $id_user, string $name, string $script, bool $admin) public function create(int $id_user, string $name, string $script, bool $admin)
@ -55,14 +46,15 @@ namespace controllers\internals;
return $result; return $result;
} }
/** /**
* Update a command * Update a command.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Command id * @param int $id : Command id
* @param string $name : Command name * @param string $name : Command name
* @param string $script : Script file * @param string $script : Script file
* @param bool $admin : Is command admin only * @param bool $admin : Is command admin only
*
* @return mixed bool|int : False if cannot create command, id of the new command else * @return mixed bool|int : False if cannot create command, id of the new command else
*/ */
public function update_for_user(int $id_user, int $id, string $name, string $script, bool $admin) public function update_for_user(int $id_user, int $id, string $name, string $script, bool $admin)
@ -76,11 +68,12 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id, $datas); return $this->get_model()->update_for_user($id_user, $id, $datas);
} }
/** /**
* Analyse a message to check if it's a command and extract it * Analyse a message to check if it's a command and extract it.
*
* @param int $id_user : User id to search a command for * @param int $id_user : User id to search a command for
* @param string $message : Text of the message to analyse * @param string $message : Text of the message to analyse
*
* @return mixed : false on error, array with new text and command to execute ['updated_text' => string, 'command' => string] * @return mixed : false on error, array with new text and command to execute ['updated_text' => string, 'command' => string]
*/ */
public function check_for_command(int $id_user, string $message) public function check_for_command(int $id_user, string $message)
@ -88,27 +81,24 @@ namespace controllers\internals;
$extracted_command = []; $extracted_command = [];
$decode_message = json_decode(trim($message), true); $decode_message = json_decode(trim($message), true);
if ($decode_message === null) if (null === $decode_message)
{ {
return false; return false;
} }
if (!isset($decode_message['login'], $decode_message['password'], $decode_message['command'])) if (!isset($decode_message['login'], $decode_message['password'], $decode_message['command']))
{ {
return false; return false;
} }
//Check for user //Check for user
$internal_user = new \controllers\internals\User($this->bdd); $internal_user = new \controllers\internals\User($this->bdd);
$user = $internal_user->check_credentials($decode_message['login'], $decode_message['password']); $user = $internal_user->check_credentials($decode_message['login'], $decode_message['password']);
if (!$user || $user['id'] != $id_user) if (!$user || $user['id'] !== $id_user)
{ {
return false; return false;
} }
//Find command //Find command
$commands = $this->gets_for_user($user['id']); $commands = $this->gets_for_user($user['id']);
$find_command = false; $find_command = false;
@ -117,6 +107,7 @@ namespace controllers\internals;
if ($decode_message['command'] === $command['name']) if ($decode_message['command'] === $command['name'])
{ {
$find_command = $command; $find_command = $command;
break; break;
} }
} }
@ -126,16 +117,12 @@ namespace controllers\internals;
return false; return false;
} }
//Check for admin rights //Check for admin rights
if ($find_command['admin'] && !$user['admin']) if ($find_command['admin'] && !$user['admin'])
{ {
return false; return false;
} }
//Forge command and return //Forge command and return
$decode_message['password'] = '******'; $decode_message['password'] = '******';
$updated_text = json_encode($decode_message); $updated_text = json_encode($decode_message);
@ -149,4 +136,16 @@ namespace controllers\internals;
'command' => $generated_command, 'command' => $generated_command,
]; ];
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Command($this->bdd);
return $this->model;
}
} }

View File

@ -13,24 +13,15 @@ namespace controllers\internals;
class ConditionalGroup extends StandardController class ConditionalGroup extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a new group for a user.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\ConditionalGroup($this->bdd);
return $this->model;
}
/**
* Create a new group for a user
* @param int $id_user : user id * @param int $id_user : user id
* @param string $name : Group name * @param string $name : Group name
* @param string $condition : Condition for forming group content * @param string $condition : Condition for forming group content
*
* @return mixed bool|int : false on error, new group id * @return mixed bool|int : false on error, new group id
*/ */
public function create(int $id_user, string $name, string $condition) public function create(int $id_user, string $name, string $condition)
@ -60,13 +51,14 @@ namespace controllers\internals;
return $id_group; return $id_group;
} }
/** /**
* Update a group for a user * Update a group for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_group : Group id * @param int $id_group : Group id
* @param string $name : Group name * @param string $name : Group name
* @param string $condition : Condition for forming group content * @param string $condition : Condition for forming group content
*
* @return bool : False on error, true on success * @return bool : False on error, true on success
*/ */
public function update_for_user(int $id_user, int $id_group, string $name, string $condition) public function update_for_user(int $id_user, int $id_group, string $name, string $condition)
@ -92,11 +84,12 @@ namespace controllers\internals;
return true; return true;
} }
/** /**
* Return a group by his name for a user * Return a group by his name for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Group name * @param string $name : Group name
*
* @return array * @return array
*/ */
public function get_by_name_for_user(int $id_user, string $name) public function get_by_name_for_user(int $id_user, string $name)
@ -104,11 +97,12 @@ namespace controllers\internals;
return $this->get_model()->get_by_name_for_user($id_user, $name); return $this->get_model()->get_by_name_for_user($id_user, $name);
} }
/** /**
* Gets the user's contacts that respects a condition * Gets the user's contacts that respects a condition.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $condition : Condition string to verify * @param string $condition : Condition string to verify
*
* @return array * @return array
*/ */
public function get_contacts_for_condition_and_user(int $id_user, string $condition): array public function get_contacts_for_condition_and_user(int $id_user, string $condition): array
@ -133,4 +127,16 @@ namespace controllers\internals;
return $contacts; return $contacts;
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\ConditionalGroup($this->bdd);
return $this->model;
}
} }

View File

@ -12,39 +12,37 @@
namespace controllers\internals; namespace controllers\internals;
/** /**
* Class to call the console scripts * Class to call the console scripts.
*/ */
class Console extends \descartes\InternalController class Console extends \descartes\InternalController
{ {
/** /**
* Start launcher daemon * Start launcher daemon.
*/ */
public function launcher() public function launcher()
{ {
new \daemons\Launcher(); new \daemons\Launcher();
} }
/** /**
* Start sender daemon * Start sender daemon.
*/ */
public function sender() public function sender()
{ {
new \daemons\Sender(); new \daemons\Sender();
} }
/** /**
* Start webhook daemon * Start webhook daemon.
*/ */
public function webhook() public function webhook()
{ {
new \daemons\Webhook(); new \daemons\Webhook();
} }
/** /**
* Start a phone daemon * Start a phone daemon.
*
* @param $id_phone : Phone id * @param $id_phone : Phone id
*/ */
public function phone($id_phone) public function phone($id_phone)
@ -63,6 +61,8 @@ namespace controllers\internals;
/** /**
* Cette fonction retourne la fenetre de connexion. * Cette fonction retourne la fenetre de connexion.
*
* @param mixed $id_phone
*/ */
public function test($id_phone) public function test($id_phone)
{ {
@ -71,11 +71,12 @@ namespace controllers\internals;
$phone = $internal_phone->get($id_phone); $phone = $internal_phone->get($id_phone);
if (!$phone) if (!$phone)
{ {
echo "No phone for id : $id_phone\n"; echo "No phone for id : {$id_phone}\n";
return false; return false;
} }
echo "Found phone for id : $id_phone\n"; echo "Found phone for id : {$id_phone}\n";
$adapter_classname = $phone['adapter']; $adapter_classname = $phone['adapter'];
$adapter = new $adapter_classname($phone['number'], $phone['adapter_datas']); $adapter = new $adapter_classname($phone['number'], $phone['adapter_datas']);

View File

@ -13,22 +13,14 @@ namespace controllers\internals;
class Contact extends StandardController class Contact extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Return a contact for a user by a number.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Contact($this->bdd);
return $this->model;
}
/**
* Return a contact for a user by a number
* @param int $id_user : user id * @param int $id_user : user id
* @param string $number : Contact number * @param string $number : Contact number
*
* @return array * @return array
*/ */
public function get_by_number_and_user(int $id_user, string $number) public function get_by_number_and_user(int $id_user, string $number)
@ -36,11 +28,12 @@ namespace controllers\internals;
return $this->get_model()->get_by_number_and_user($id_user, $number); return $this->get_model()->get_by_number_and_user($id_user, $number);
} }
/** /**
* Return a contact by his name for a user * Return a contact by his name for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Contact name * @param string $name : Contact name
*
* @return array * @return array
*/ */
public function get_by_name_and_user(int $id_user, string $name) public function get_by_name_and_user(int $id_user, string $name)
@ -48,10 +41,11 @@ namespace controllers\internals;
return $this->get_model()->get_by_name_and_user($id_user, $name); return $this->get_model()->get_by_name_and_user($id_user, $name);
} }
/** /**
* Return all contacts of a user. * Return all contacts of a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -59,13 +53,14 @@ namespace controllers\internals;
return $this->get_model()->gets_for_user($id_user); return $this->get_model()->gets_for_user($id_user);
} }
/** /**
* Create a new contact * Create a new contact.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $number : Contact number * @param string $number : Contact number
* @param string $name : Contact name * @param string $name : Contact name
* @param string $datas : Contact datas * @param string $datas : Contact datas
*
* @return mixed bool|int : False if cannot create contact, id of the new contact else * @return mixed bool|int : False if cannot create contact, id of the new contact else
*/ */
public function create($id_user, $number, $name, $datas) public function create($id_user, $number, $name, $datas)
@ -89,14 +84,15 @@ namespace controllers\internals;
return $result; return $result;
} }
/** /**
* Update a contact * Update a contact.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Contact id * @param int $id : Contact id
* @param string $number : Contact number * @param string $number : Contact number
* @param string $name : Contact name * @param string $name : Contact name
* @param ?string $datas : Contact datas * @param ?string $datas : Contact datas
*
* @return int : number of modified rows * @return int : number of modified rows
*/ */
public function update_for_user(int $id_user, int $id, string $number, string $name, string $datas) public function update_for_user(int $id_user, int $id, string $number, string $name, string $datas)
@ -110,16 +106,17 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id, $contact); return $this->get_model()->update_for_user($id_user, $id, $contact);
} }
/** /**
* Import a list of contacts as csv * Import a list of contacts as csv.
*
* @param resource $file_handler : File handler to import contacts from * @param resource $file_handler : File handler to import contacts from
* @param int $id_user : User id * @param int $id_user : User id
*
* @return mixed : False on error, number of inserted contacts else * @return mixed : False on error, number of inserted contacts else
*/ */
public function import_csv(int $id_user, $file_handler) public function import_csv(int $id_user, $file_handler)
{ {
if (!is_resource($file_handler)) if (!\is_resource($file_handler))
{ {
return false; return false;
} }
@ -129,14 +126,15 @@ namespace controllers\internals;
$head = null; $head = null;
while ($line = fgetcsv($file_handler)) while ($line = fgetcsv($file_handler))
{ {
if ($head === null) if (null === $head)
{ {
$head = $line; $head = $line;
continue; continue;
} }
$line = array_combine($head, $line); $line = array_combine($head, $line);
if ($line === false) if (false === $line)
{ {
continue; continue;
} }
@ -149,12 +147,12 @@ namespace controllers\internals;
$datas = []; $datas = [];
foreach ($line as $key => $value) foreach ($line as $key => $value)
{ {
if ($key == 'name' || $key == 'number') if ('name' === $key || 'number' === $key)
{ {
continue; continue;
} }
if ($value === '') if ('' === $value)
{ {
continue; continue;
} }
@ -167,23 +165,24 @@ namespace controllers\internals;
$success = $this->create($id_user, $line['number'], $line['name'], $datas); $success = $this->create($id_user, $line['number'], $line['name'], $datas);
if ($success) if ($success)
{ {
$nb_insert ++; ++$nb_insert;
} }
} }
return $nb_insert; return $nb_insert;
} }
/** /**
* Import a list of contacts as json * Import a list of contacts as json.
*
* @param resource $file_handler : File handler to import contacts from * @param resource $file_handler : File handler to import contacts from
* @param int $id_user : User id * @param int $id_user : User id
*
* @return mixed : False on error, number of inserted contacts else * @return mixed : False on error, number of inserted contacts else
*/ */
public function import_json(int $id_user, $file_handler) public function import_json(int $id_user, $file_handler)
{ {
if (!is_resource($file_handler)) if (!\is_resource($file_handler))
{ {
return false; return false;
} }
@ -198,7 +197,7 @@ namespace controllers\internals;
{ {
$contacts = json_decode($file_content, true); $contacts = json_decode($file_content, true);
if (!is_array($contacts)) if (!\is_array($contacts))
{ {
return false; return false;
} }
@ -206,7 +205,7 @@ namespace controllers\internals;
$nb_insert = 0; $nb_insert = 0;
foreach ($contacts as $contact) foreach ($contacts as $contact)
{ {
if (!is_array($contact)) if (!\is_array($contact))
{ {
continue; continue;
} }
@ -222,7 +221,7 @@ namespace controllers\internals;
$success = $this->create($id_user, $contact['number'], $contact['name'], $datas); $success = $this->create($id_user, $contact['number'], $contact['name'], $datas);
if ($success) if ($success)
{ {
$nb_insert ++; ++$nb_insert;
} }
} }
@ -234,10 +233,11 @@ namespace controllers\internals;
} }
} }
/** /**
* Export the contacts of a user as csv * Export the contacts of a user as csv.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array : ['headers' => array of headers to return, 'content' => the generated file] * @return array : ['headers' => array of headers to return, 'content' => the generated file]
*/ */
public function export_csv(int $id_user): array public function export_csv(int $id_user): array
@ -270,12 +270,14 @@ namespace controllers\internals;
if (isset($contact[$column])) if (isset($contact[$column]))
{ {
$line[] = $contact[$column]; $line[] = $contact[$column];
continue; continue;
} }
if (isset($datas[$column])) if (isset($datas[$column]))
{ {
$line[] = $datas[$column]; $line[] = $datas[$column];
continue; continue;
} }
@ -300,16 +302,17 @@ namespace controllers\internals;
'headers' => [ 'headers' => [
'Content-Disposition: attachment; filename=contacts.csv', 'Content-Disposition: attachment; filename=contacts.csv',
'Content-Type: text/csv', 'Content-Type: text/csv',
'Content-Length: ' . strlen($csv_string), 'Content-Length: '.\mb_strlen($csv_string),
], ],
'content' => $csv_string, 'content' => $csv_string,
]; ];
} }
/** /**
* Export the contacts of a user as json * Export the contacts of a user as json.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array : ['headers' => array of headers to return, 'content' => the generated file] * @return array : ['headers' => array of headers to return, 'content' => the generated file]
*/ */
public function export_json(int $id_user): array public function export_json(int $id_user): array
@ -318,8 +321,8 @@ namespace controllers\internals;
foreach ($contacts as &$contact) foreach ($contacts as &$contact)
{ {
unset($contact['id']); unset($contact['id'], $contact['id_user']);
unset($contact['id_user']);
$contact['datas'] = json_decode($contact['datas']); $contact['datas'] = json_decode($contact['datas']);
} }
$content = json_encode($contacts); $content = json_encode($contacts);
@ -328,10 +331,21 @@ namespace controllers\internals;
'headers' => [ 'headers' => [
'Content-Disposition: attachment; filename=contacts.json', 'Content-Disposition: attachment; filename=contacts.json',
'Content-Type: application/json', 'Content-Type: application/json',
'Content-Length: ' . strlen($content), 'Content-Length: '.\mb_strlen($content),
], ],
'content' => $content, 'content' => $content,
]; ];
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Contact($this->bdd);
return $this->model;
}
} }

View File

@ -13,29 +13,22 @@ namespace controllers\internals;
class Event extends StandardController class Event extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Disabled methods.
* @return \descartes\Model
*/ */
protected function get_model () : \descartes\Model public function update_for_user()
{ {
$this->model = $this->model ?? new \models\Event($this->bdd); return false;
return $this->model;
} }
/** /**
* Disabled methods * Gets lasts x events for a user order by date.
*/ *
public function update_for_user() { return false; }
/**
* Gets lasts x events for a user order by date
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of events to return * @param int $nb_entry : Number of events to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user(int $id_user, int $nb_entry) public function get_lasts_by_date_for_user(int $id_user, int $nb_entry)
@ -43,12 +36,13 @@ namespace controllers\internals;
return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry); return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
} }
/** /**
* Create a new event * Create a new event.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param mixed $type * @param mixed $type
* @param mixed $text * @param mixed $text
*
* @return mixed bool : false on fail, new event id else * @return mixed bool : false on fail, new event id else
*/ */
public function create($id_user, $type, $text) public function create($id_user, $type, $text)
@ -61,4 +55,16 @@ namespace controllers\internals;
return $this->get_model()->insert($event); return $this->get_model()->insert($event);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Event($this->bdd);
return $this->model;
}
} }

View File

@ -1,5 +1,14 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace controllers\internals; namespace controllers\internals;
use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunction;

View File

@ -16,24 +16,15 @@ namespace controllers\internals;
*/ */
class Group extends StandardController class Group extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a new group for a user.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Group($this->bdd);
return $this->model;
}
/**
* Create a new group for a user
* @param int $id_user : user id * @param int $id_user : user id
* @param stirng $name : Group name * @param stirng $name : Group name
* @param array $contacts_ids : Ids of the contacts of the group * @param array $contacts_ids : Ids of the contacts of the group
*
* @return mixed bool|int : false on error, new group id * @return mixed bool|int : false on error, new group id
*/ */
public function create(int $id_user, string $name, array $contacts_ids) public function create(int $id_user, string $name, array $contacts_ids)
@ -43,7 +34,6 @@ namespace controllers\internals;
'name' => $name, 'name' => $name,
]; ];
$id_group = $this->get_model()->insert($group); $id_group = $this->get_model()->insert($group);
if (!$id_group) if (!$id_group)
{ {
@ -68,13 +58,14 @@ namespace controllers\internals;
return $id_group; return $id_group;
} }
/** /**
* Update a group for a user * Update a group for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_group : Group id * @param int $id_group : Group id
* @param stirng $name : Group name * @param stirng $name : Group name
* @param array $contacts_ids : Ids of the contacts of the group * @param array $contacts_ids : Ids of the contacts of the group
*
* @return bool : False on error, true on success * @return bool : False on error, true on success
*/ */
public function update_for_user(int $id_user, int $id_group, string $name, array $contacts_ids) public function update_for_user(int $id_user, int $id_group, string $name, array $contacts_ids)
@ -99,7 +90,7 @@ namespace controllers\internals;
if ($this->get_model()->insert_group_contact_relation($id_group, $contact_id)) if ($this->get_model()->insert_group_contact_relation($id_group, $contact_id))
{ {
$nb_contact_insert++; ++$nb_contact_insert;
} }
} }
@ -111,11 +102,12 @@ namespace controllers\internals;
return true; return true;
} }
/** /**
* Return a group by his name for a user * Return a group by his name for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Group name * @param string $name : Group name
*
* @return array * @return array
*/ */
public function get_by_name_for_user(int $id_user, string $name) public function get_by_name_for_user(int $id_user, string $name)
@ -123,14 +115,27 @@ namespace controllers\internals;
return $this->get_model()->get_by_name_for_user($id_user, $name); return $this->get_model()->get_by_name_for_user($id_user, $name);
} }
/** /**
* Get groups contacts * Get groups contacts.
*
* @param int $id_group : Group id * @param int $id_group : Group id
*
* @return array : Contacts of the group * @return array : Contacts of the group
*/ */
public function get_contacts($id_group) public function get_contacts($id_group)
{ {
return $this->get_model()->get_contacts($id_group); return $this->get_model()->get_contacts($id_group);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Group($this->bdd);
return $this->model;
}
} }

View File

@ -13,23 +13,15 @@ namespace controllers\internals;
class Media extends StandardController class Media extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a media.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Media($this->bdd);
return $this->model;
}
/**
* Create a media
* @param int $id_user : Id of the user * @param int $id_user : Id of the user
* @param int $id_scheduled : Id of the scheduled * @param int $id_scheduled : Id of the scheduled
* @param array $media : $_FILES media array * @param array $media : $_FILES media array
*
* @return bool : false on error, new media id else * @return bool : false on error, new media id else
*/ */
public function create(int $id_user, int $id_scheduled, array $media): bool public function create(int $id_user, int $id_scheduled, array $media): bool
@ -42,7 +34,7 @@ namespace controllers\internals;
} }
$result_upload_media = \controllers\internals\Tool::upload_file($media); $result_upload_media = \controllers\internals\Tool::upload_file($media);
if ($result_upload_media['success'] == false) if (false === $result_upload_media['success'])
{ {
return false; return false;
} }
@ -55,13 +47,14 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($datas); return (bool) $this->get_model()->insert($datas);
} }
/** /**
* Update a media for a user * Update a media for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_media : Media id * @param int $id_media : Media id
* @param int $id_scheduled : Id of the scheduled * @param int $id_scheduled : Id of the scheduled
* @param string $path : Path of the file * @param string $path : Path of the file
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_for_user(int $id_user, int $id_media, int $id_scheduled, string $path): bool public function update_for_user(int $id_user, int $id_media, int $id_scheduled, string $path): bool
@ -81,11 +74,12 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_media, $media); return (bool) $this->get_model()->update_for_user($id_user, $id_media, $media);
} }
/** /**
* Delete a media for a user * Delete a media for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id_media): bool public function delete_for_user(int $id_user, int $id_media): bool
@ -101,11 +95,12 @@ namespace controllers\internals;
return $this->get_model()->delete_for_user($id_user, $id); return $this->get_model()->delete_for_user($id_user, $id);
} }
/** /**
* Delete a media for a scheduled and a user * Delete a media for a scheduled and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_scheduled : Scheduled id to delete medias for * @param int $id_scheduled : Scheduled id to delete medias for
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_scheduled_and_user(int $id_user, int $id_scheduled): bool public function delete_for_scheduled_and_user(int $id_user, int $id_scheduled): bool
@ -119,15 +114,28 @@ namespace controllers\internals;
return $this->get_model()->delete_for_scheduled_and_user($id_user, $id_scheduled); return $this->get_model()->delete_for_scheduled_and_user($id_user, $id_scheduled);
} }
/** /**
* Find medias for a scheduled and a user * Find medias for a scheduled and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_scheduled : Scheduled id to delete medias for * @param int $id_scheduled : Scheduled id to delete medias for
*
* @return mixed : Medias || false * @return mixed : Medias || false
*/ */
public function get_for_scheduled_and_user(int $id_user, int $id_scheduled) public function get_for_scheduled_and_user(int $id_user, int $id_scheduled)
{ {
return $this->get_model()->get_for_scheduled_and_user($id_user, $id_scheduled); return $this->get_model()->get_for_scheduled_and_user($id_user, $id_scheduled);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Media($this->bdd);
return $this->model;
}
} }

View File

@ -13,22 +13,13 @@ namespace controllers\internals;
class Phone extends StandardController class Phone extends StandardController
{ {
protected $model = null; protected $model;
/**
* Get the model for the Controller
* @return \descartes\Model
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Phone($this->bdd);
return $this->model;
}
/** /**
* Return all phones of a user. * Return all phones of a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -36,10 +27,11 @@ namespace controllers\internals;
return $this->get_model()->gets_for_user($id_user); return $this->get_model()->gets_for_user($id_user);
} }
/** /**
* Return a phone by his number * Return a phone by his number.
*
* @param string $number : Phone number * @param string $number : Phone number
*
* @return array * @return array
*/ */
public function get_by_number(string $number) public function get_by_number(string $number)
@ -47,11 +39,12 @@ namespace controllers\internals;
return $this->get_model()->get_by_number($number); return $this->get_model()->get_by_number($number);
} }
/** /**
* Return a phone for a user by a number * Return a phone for a user by a number.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param string $number : Phone number * @param string $number : Phone number
*
* @return array * @return array
*/ */
public function get_by_number_and_user(int $id_user, string $number) public function get_by_number_and_user(int $id_user, string $number)
@ -59,13 +52,14 @@ namespace controllers\internals;
return $this->get_model()->get_by_number_and_user($id_user, $number); return $this->get_model()->get_by_number_and_user($id_user, $number);
} }
/** /**
* Create a phone * Create a phone.
*
* @param int $id_user : User to insert phone for * @param int $id_user : User to insert phone for
* @param string $number : The number of the phone * @param string $number : The number of the phone
* @param string $adapter : The adapter to use the phone * @param string $adapter : The adapter to use the phone
* @param string json $adapter_datas : A JSON string representing adapter's datas (for example credentials for an api) * @param string json $adapter_datas : A JSON string representing adapter's datas (for example credentials for an api)
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function create(int $id_user, string $number, string $adapter, string $adapter_datas): bool public function create(int $id_user, string $number, string $adapter, string $adapter_datas): bool
@ -80,14 +74,15 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($phone); return (bool) $this->get_model()->insert($phone);
} }
/** /**
* Update a phone * Update a phone.
*
* @param int $id_user : User to insert phone for * @param int $id_user : User to insert phone for
* @param int $id : Phone id * @param int $id : Phone id
* @param string $number : The number of the phone * @param string $number : The number of the phone
* @param string $adapter : The adapter to use the phone * @param string $adapter : The adapter to use the phone
* @param array $adapter_datas : An array of the datas of the adapter (for example credentials for an api) * @param array $adapter_datas : An array of the datas of the adapter (for example credentials for an api)
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_for_user(int $id_user, int $id, string $number, string $adapter, array $adapter_datas): bool public function update_for_user(int $id_user, int $id, string $number, string $adapter, array $adapter_datas): bool
@ -101,4 +96,16 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id, $phone); return (bool) $this->get_model()->update_for_user($id_user, $id, $phone);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Phone($this->bdd);
return $this->model;
}
} }

View File

@ -13,24 +13,15 @@ namespace controllers\internals;
class Received extends StandardController class Received extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Return the list of unread messages for a user.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Received($this->bdd);
return $this->model;
}
/**
* Return the list of unread messages for a user
* @param int $id_user : User id * @param int $id_user : User id
* @param ?int $nb_entry : Number of entry to return * @param ?int $nb_entry : Number of entry to return
* @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page * @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page
*
* @return array : Entrys list * @return array : Entrys list
*/ */
public function list_unread_for_user(int $id_user, ?int $nb_entry = null, ?int $page = null) public function list_unread_for_user(int $id_user, ?int $nb_entry = null, ?int $page = null)
@ -38,15 +29,16 @@ namespace controllers\internals;
return $this->get_model()->list_unread_for_user($id_user, $nb_entry, $nb_entry * $page); return $this->get_model()->list_unread_for_user($id_user, $nb_entry, $nb_entry * $page);
} }
/** /**
* Create a received * Create a received.
*
* @param $at : Reception date * @param $at : Reception date
* @param $text : Text of the message * @param $text : Text of the message
* @param string $origin : Number of the sender * @param string $origin : Number of the sender
* @param string $destination : Number of the receiver * @param string $destination : Number of the receiver
* @param string $status : Status of the received message * @param string $status : Status of the received message
* @param bool $command : Is the sms a command * @param bool $command : Is the sms a command
*
* @return bool : false on error, new received id else * @return bool : false on error, new received id else
*/ */
public function create($at, string $text, string $origin, string $destination, string $status = 'unread', bool $command = false): bool public function create($at, string $text, string $origin, string $destination, string $status = 'unread', bool $command = false): bool
@ -63,9 +55,9 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($received); return (bool) $this->get_model()->insert($received);
} }
/** /**
* Update a received for a user * Update a received for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_received : received id * @param int $id_received : received id
* @param $at : Reception date * @param $at : Reception date
@ -74,6 +66,7 @@ namespace controllers\internals;
* @param string $destination : Number of the receiver * @param string $destination : Number of the receiver
* @param string $status : Status of the received message * @param string $status : Status of the received message
* @param bool $command : Is the sms a command * @param bool $command : Is the sms a command
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_for_user(int $id_user, int $id_received, $at, string $text, string $origin, string $destination, string $status = 'unread', bool $command = false): bool public function update_for_user(int $id_user, int $id_received, $at, string $text, string $origin, string $destination, string $status = 'unread', bool $command = false): bool
@ -90,11 +83,12 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received); return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received);
} }
/** /**
* Update a received message for a user to mark the message as read * Update a received message for a user to mark the message as read.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_received : received id * @param int $id_received : received id
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function mark_as_read_for_user(int $id_user, int $id_received): bool public function mark_as_read_for_user(int $id_user, int $id_received): bool
@ -106,11 +100,12 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received); return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received);
} }
/** /**
* Update a received message for a user to mark the message as unread * Update a received message for a user to mark the message as unread.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_received : received id * @param int $id_received : received id
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function mark_as_unread_for_user(int $id_user, int $id_received): bool public function mark_as_unread_for_user(int $id_user, int $id_received): bool
@ -122,10 +117,11 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received); return (bool) $this->get_model()->update_for_user($id_user, $id_received, $received);
} }
/** /**
* Return number of unread messages for a user * Return number of unread messages for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array * @return array
*/ */
public function count_unread_for_user(int $id_user) public function count_unread_for_user(int $id_user)
@ -133,12 +129,12 @@ namespace controllers\internals;
return $this->get_model()->count_unread_for_user($id_user); return $this->get_model()->count_unread_for_user($id_user);
} }
/** /**
* Return x last receiveds message for a user, order by date * Return x last receiveds message for a user, order by date.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of receiveds messages to return * @param int $nb_entry : Number of receiveds messages to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user(int $id_user, int $nb_entry) public function get_lasts_by_date_for_user(int $id_user, int $nb_entry)
@ -146,11 +142,12 @@ namespace controllers\internals;
return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry); return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
} }
/** /**
* Return receiveds for an origin and a user * Return receiveds for an origin and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $origin : Number who sent the message * @param string $origin : Number who sent the message
*
* @return array * @return array
*/ */
public function gets_by_origin_and_user(int $id_user, string $origin) public function gets_by_origin_and_user(int $id_user, string $origin)
@ -158,11 +155,12 @@ namespace controllers\internals;
return $this->get_model()->gets_by_origin_and_user($id_user, $origin); return $this->get_model()->gets_by_origin_and_user($id_user, $origin);
} }
/** /**
* Get number of sended SMS for every date since a date for a specific user * Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages * @param \DateTime $date : Date since which we want the messages
*
* @return array * @return array
*/ */
public function count_by_day_since_for_user(int $id_user, $date) public function count_by_day_since_for_user(int $id_user, $date)
@ -178,10 +176,11 @@ namespace controllers\internals;
return $return; return $return;
} }
/** /**
* Return all discussions (ie : numbers we have a message received from or sended to) for a user * Return all discussions (ie : numbers we have a message received from or sended to) for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array * @return array
*/ */
public function get_discussions_for_user(int $id_user) public function get_discussions_for_user(int $id_user)
@ -189,11 +188,12 @@ namespace controllers\internals;
return $this->get_model()->get_discussions_for_user($id_user); return $this->get_model()->get_discussions_for_user($id_user);
} }
/** /**
* Get SMS received since a date for a user * Get SMS received since a date for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05) * @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05)
*
* @return array : Tableau avec tous les SMS depuis la date * @return array : Tableau avec tous les SMS depuis la date
*/ */
public function get_since_by_date_for_user(int $id_user, $date) public function get_since_by_date_for_user(int $id_user, $date)
@ -201,12 +201,13 @@ namespace controllers\internals;
return $this->get_model()->get_since_by_date_for_user($id_user, $date); return $this->get_model()->get_since_by_date_for_user($id_user, $date);
} }
/** /**
* Find messages received since a date for a certain origin and user * Find messages received since a date for a certain origin and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : Date we want messages sinces * @param $date : Date we want messages sinces
* @param string $origin : Origin number * @param string $origin : Origin number
*
* @return array * @return array
*/ */
public function get_since_by_date_for_origin_and_user(int $id_user, $date, string $origin) public function get_since_by_date_for_origin_and_user(int $id_user, $date, string $origin)
@ -214,15 +215,28 @@ namespace controllers\internals;
return $this->get_model()->get_since_by_date_for_origin_and_user($id_user, $date, $origin); return $this->get_model()->get_since_by_date_for_origin_and_user($id_user, $date, $origin);
} }
/** /**
* Find destination of last received message for an origin and user * Find destination of last received message for an origin and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $origin : Origin number * @param string $origin : Origin number
*
* @return array * @return array
*/ */
public function get_last_for_origin_and_user(int $id_user, string $origin) public function get_last_for_origin_and_user(int $id_user, string $origin)
{ {
return $this->get_model()->get_last_for_origin_and_user($id_user, $origin); return $this->get_model()->get_last_for_origin_and_user($id_user, $origin);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Received($this->bdd);
return $this->model;
}
} }

View File

@ -10,18 +10,18 @@
*/ */
namespace controllers\internals; namespace controllers\internals;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
/** /**
* Class to analyse rules used by conditional groups * Class to analyse rules used by conditional groups.
*/ */
class Ruler extends \descartes\InternalController class Ruler extends \descartes\InternalController
{ {
private $expression_language; private $expression_language;
/** /**
* Constructor * Constructor.
*/ */
public function __construct() public function __construct()
{ {
@ -31,11 +31,12 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
$this->expression_language->registerProvider(new ExpressionProvider()); $this->expression_language->registerProvider(new ExpressionProvider());
} }
/** /**
* Verify if a condition is valid. i.e we can evaluate it without error. * Verify if a condition is valid. i.e we can evaluate it without error.
* @param string $condition : The condition to evaluate. *
* @param string $condition : The condition to evaluate
* @param array $datas : The datas to made available to condition * @param array $datas : The datas to made available to condition
*
* @return bool : false if invalid, true else * @return bool : false if invalid, true else
*/ */
public function validate_condition(string $condition, array $datas = []): bool public function validate_condition(string $condition, array $datas = []): bool
@ -43,6 +44,7 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
try try
{ {
$this->expression_language->evaluate($condition, $datas); $this->expression_language->evaluate($condition, $datas);
return true; return true;
} }
catch (\Exception $e) catch (\Exception $e)
@ -51,11 +53,12 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
} }
} }
/** /**
* Evaluate a condition * Evaluate a condition.
* @param string $condition : The condition to evaluate. *
* @param string $condition : The condition to evaluate
* @param array $datas : The datas to made available to condition * @param array $datas : The datas to made available to condition
*
* @return ?bool : false if invalid, true else, null only on error * @return ?bool : false if invalid, true else, null only on error
*/ */
public function evaluate_condition(string $condition, array $datas = []): ?bool public function evaluate_condition(string $condition, array $datas = []): ?bool
@ -63,6 +66,7 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
try try
{ {
$result = $this->expression_language->evaluate($condition, $datas); $result = $this->expression_language->evaluate($condition, $datas);
return (bool) $result; return (bool) $result;
} }
catch (\Exception $e) catch (\Exception $e)

View File

@ -13,20 +13,11 @@ namespace controllers\internals;
class Scheduled extends StandardController class Scheduled extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a scheduled.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Scheduled($this->bdd);
return $this->model;
}
/**
* Create a scheduled
* @param int $id_user : User to insert scheduled for * @param int $id_user : User to insert scheduled for
* @param $at : Scheduled date to send * @param $at : Scheduled date to send
* @param string $text : Text of the message * @param string $text : Text of the message
@ -36,6 +27,7 @@ namespace controllers\internals;
* @param array $contacts_ids : Contact ids to send message to * @param array $contacts_ids : Contact ids to send message to
* @param array $groups_ids : Group ids to send message to * @param array $groups_ids : Group ids to send message to
* @param array $conditional_group_ids : Conditional Groups ids to send message to * @param array $conditional_group_ids : Conditional Groups ids to send message to
*
* @return bool : false on error, new id on success * @return bool : false on error, new id on success
*/ */
public function create(int $id_user, $at, string $text, ?string $origin = null, bool $flash = false, array $numbers = [], array $contacts_ids = [], array $groups_ids = [], array $conditional_group_ids = []) public function create(int $id_user, $at, string $text, ?string $origin = null, bool $flash = false, array $numbers = [], array $contacts_ids = [], array $groups_ids = [], array $conditional_group_ids = [])
@ -59,13 +51,13 @@ namespace controllers\internals;
} }
} }
$id_scheduled = $this->get_model()->insert($scheduled); $id_scheduled = $this->get_model()->insert($scheduled);
if (!$id_scheduled) if (!$id_scheduled)
{ {
$date = date('Y-m-d H:i:s'); $date = date('Y-m-d H:i:s');
$internal_event = new Event($this->bdd); $internal_event = new Event($this->bdd);
$internal_event->create($id_user, 'SCHEDULED_ADD', 'Ajout d\'un Sms pour le '.$date.'.'); $internal_event->create($id_user, 'SCHEDULED_ADD', 'Ajout d\'un Sms pour le '.$date.'.');
return false; return false;
} }
@ -113,9 +105,9 @@ namespace controllers\internals;
return $id_scheduled; return $id_scheduled;
} }
/** /**
* Update a scheduled * Update a scheduled.
*
* @param int $id_user : User to insert scheduled for * @param int $id_user : User to insert scheduled for
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
* @param $at : Scheduled date to send * @param $at : Scheduled date to send
@ -126,6 +118,7 @@ namespace controllers\internals;
* @param array $contacts_ids : Contact ids to send message to * @param array $contacts_ids : Contact ids to send message to
* @param array $groups_ids : Group ids to send message to * @param array $groups_ids : Group ids to send message to
* @param array $conditional_group_ids : Conditional Groups ids to send message to * @param array $conditional_group_ids : Conditional Groups ids to send message to
*
* @return bool : false on error, new id on success * @return bool : false on error, new id on success
*/ */
public function update_for_user(int $id_user, int $id_scheduled, $at, string $text, ?string $origin = null, bool $flash = false, array $numbers = [], array $contacts_ids = [], array $groups_ids = [], array $conditional_group_ids = []) public function update_for_user(int $id_user, int $id_scheduled, $at, string $text, ?string $origin = null, bool $flash = false, array $numbers = [], array $contacts_ids = [], array $groups_ids = [], array $conditional_group_ids = [])
@ -138,7 +131,6 @@ namespace controllers\internals;
'flash' => $flash, 'flash' => $flash,
]; ];
if ($origin) if ($origin)
{ {
$internal_phone = new Phone($this->bdd); $internal_phone = new Phone($this->bdd);
@ -201,12 +193,13 @@ namespace controllers\internals;
return true; return true;
} }
/** /**
* Get messages scheduled before a date for a number and a user * Get messages scheduled before a date for a number and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : Date before which we want messages * @param $date : Date before which we want messages
* @param string $number : Number for which we want messages * @param string $number : Number for which we want messages
*
* @return array * @return array
*/ */
public function gets_before_date_for_number_and_user(int $id_user, $date, string $number) public function gets_before_date_for_number_and_user(int $id_user, $date, string $number)
@ -214,9 +207,9 @@ namespace controllers\internals;
return $this->get_model()->gets_before_date_for_number_and_user($id_user, $date, $number); return $this->get_model()->gets_before_date_for_number_and_user($id_user, $date, $number);
} }
/** /**
* Get all messages to send and the number to use to send theme * Get all messages to send and the number to use to send theme.
*
* @return array : [['id_scheduled', 'text', 'origin', 'destination', 'flash'], ...] * @return array : [['id_scheduled', 'text', 'origin', 'destination', 'flash'], ...]
*/ */
public function get_smss_to_send() public function get_smss_to_send()
@ -251,7 +244,7 @@ namespace controllers\internals;
if (!isset($users_phones[$scheduled['id_user']])) if (!isset($users_phones[$scheduled['id_user']]))
{ {
$phones = $internal_phone->gets_for_user($scheduled['id_user']); $phones = $internal_phone->gets_for_user($scheduled['id_user']);
$users_phones[$scheduled['id_user']] = $phones ? $phones : [];; $users_phones[$scheduled['id_user']] = $phones ? $phones : [];
} }
$messages = []; $messages = [];
@ -268,7 +261,7 @@ namespace controllers\internals;
'flash' => $scheduled['flash'], 'flash' => $scheduled['flash'],
]; ];
if ($message['origin'] == null) if (null === $message['origin'])
{ {
$k = array_rand($users_phones[$scheduled['id_user']]); $k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k]; $rnd_phone = $users_phones[$scheduled['id_user']][$k];
@ -294,7 +287,6 @@ namespace controllers\internals;
$messages[] = $message; $messages[] = $message;
} }
//Add messages for contacts //Add messages for contacts
$contacts = $this->get_contacts($scheduled['id']); $contacts = $this->get_contacts($scheduled['id']);
@ -330,7 +322,7 @@ namespace controllers\internals;
'flash' => $scheduled['flash'], 'flash' => $scheduled['flash'],
]; ];
if ($message['origin'] == null) if (null === $message['origin'])
{ {
$k = array_rand($users_phones[$scheduled['id_user']]); $k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k]; $rnd_phone = $users_phones[$scheduled['id_user']][$k];
@ -361,7 +353,7 @@ namespace controllers\internals;
foreach ($messages as $message) foreach ($messages as $message)
{ {
//Remove empty messages //Remove empty messages
if (trim($message['text']) == '') if ('' === trim($message['text']))
{ {
continue; continue;
} }
@ -373,10 +365,11 @@ namespace controllers\internals;
return $smss_to_send; return $smss_to_send;
} }
/** /**
* Return numbers for a scheduled message * Return numbers for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_numbers(int $id_scheduled) public function get_numbers(int $id_scheduled)
@ -384,10 +377,11 @@ namespace controllers\internals;
return $this->get_model()->get_numbers($id_scheduled); return $this->get_model()->get_numbers($id_scheduled);
} }
/** /**
* Return contacts for a scheduled message * Return contacts for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_contacts(int $id_scheduled) public function get_contacts(int $id_scheduled)
@ -395,10 +389,11 @@ namespace controllers\internals;
return $this->get_model()->get_contacts($id_scheduled); return $this->get_model()->get_contacts($id_scheduled);
} }
/** /**
* Return groups for a scheduled message * Return groups for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_groups(int $id_scheduled) public function get_groups(int $id_scheduled)
@ -406,14 +401,27 @@ namespace controllers\internals;
return $this->get_model()->get_groups($id_scheduled); return $this->get_model()->get_groups($id_scheduled);
} }
/** /**
* Return conditional groups for a scheduled message * Return conditional groups for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_conditional_groups(int $id_scheduled) public function get_conditional_groups(int $id_scheduled)
{ {
return $this->get_model()->get_conditional_groups($id_scheduled); return $this->get_model()->get_conditional_groups($id_scheduled);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Scheduled($this->bdd);
return $this->model;
}
} }

View File

@ -13,20 +13,11 @@ namespace controllers\internals;
class Sended extends StandardController class Sended extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a sended.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Sended($this->bdd);
return $this->model;
}
/**
* Create a sended
* @param $at : Reception date * @param $at : Reception date
* @param $text : Text of the message * @param $text : Text of the message
* @param string $origin : Number of the sender * @param string $origin : Number of the sender
@ -35,6 +26,7 @@ namespace controllers\internals;
* @param string $adapter : Name of the adapter service used to send the message * @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash * @param bool $flash : Is the sms a flash
* @param string $status : Status of a the sms. By default 'unknown' * @param string $status : Status of a the sms. By default 'unknown'
*
* @return bool : false on error, new sended id else * @return bool : false on error, new sended id else
*/ */
public function create($at, string $text, string $origin, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = 'unknown'): bool public function create($at, string $text, string $origin, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = 'unknown'): bool
@ -53,9 +45,9 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($sended); return (bool) $this->get_model()->insert($sended);
} }
/** /**
* Update a sended for a user * Update a sended for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_sended : Sended id * @param int $id_sended : Sended id
* @param $at : Reception date * @param $at : Reception date
@ -66,6 +58,7 @@ namespace controllers\internals;
* @param string $adapter : Name of the adapter service used to send the message * @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash * @param bool $flash : Is the sms a flash
* @param ?string $status : Status of a the sms. By default null -> unknown * @param ?string $status : Status of a the sms. By default null -> unknown
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_for_user(int $id_user, int $id_sended, $at, string $text, string $origin, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = null): bool public function update_for_user(int $id_user, int $id_sended, $at, string $text, string $origin, string $destination, string $uid, string $adapter, bool $flash = false, ?string $status = null): bool
@ -84,12 +77,13 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended); return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended);
} }
/** /**
* Update a sended status for a user * Update a sended status for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_sended : Sended id * @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed) * @param string $status : Status of a the sms (unknown, delivered, failed)
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_status_for_user(int $id_user, int $id_sended, string $status): bool public function update_status_for_user(int $id_user, int $id_sended, string $status): bool
@ -101,11 +95,12 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended); return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended);
} }
/** /**
* Update a sended status for a sended * Update a sended status for a sended.
*
* @param int $id_sended : Sended id * @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed) * @param string $status : Status of a the sms (unknown, delivered, failed)
*
* @return bool : false on error, true on success * @return bool : false on error, true on success
*/ */
public function update_status(int $id_sended, string $status): bool public function update_status(int $id_sended, string $status): bool
@ -117,11 +112,12 @@ namespace controllers\internals;
return (bool) $this->get_model()->update($id_sended, $sended); return (bool) $this->get_model()->update($id_sended, $sended);
} }
/** /**
* Return x last sendeds message for a user, order by date * Return x last sendeds message for a user, order by date.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of sendeds messages to return * @param int $nb_entry : Number of sendeds messages to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user(int $id_user, int $nb_entry) public function get_lasts_by_date_for_user(int $id_user, int $nb_entry)
@ -129,11 +125,12 @@ namespace controllers\internals;
return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry); return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
} }
/** /**
* Return sendeds for a destination and a user * Return sendeds for a destination and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $origin : Number who sent the message * @param string $origin : Number who sent the message
*
* @return array * @return array
*/ */
public function gets_by_destination_and_user(int $id_user, string $origin) public function gets_by_destination_and_user(int $id_user, string $origin)
@ -141,11 +138,12 @@ namespace controllers\internals;
return $this->get_model()->gets_by_destination_and_user($id_user, $origin); return $this->get_model()->gets_by_destination_and_user($id_user, $origin);
} }
/** /**
* Return sended for an uid and an adapter * Return sended for an uid and an adapter.
*
* @param string $uid : Uid of the sended * @param string $uid : Uid of the sended
* @param string $adapter : Adapter used to send the message * @param string $adapter : Adapter used to send the message
*
* @return array * @return array
*/ */
public function get_by_uid_and_adapter(string $uid, string $adapter) public function get_by_uid_and_adapter(string $uid, string $adapter)
@ -153,11 +151,12 @@ namespace controllers\internals;
return $this->get_model()->get_by_uid_and_adapter($uid, $adapter); return $this->get_model()->get_by_uid_and_adapter($uid, $adapter);
} }
/** /**
* Get number of sended SMS for every date since a date for a specific user * Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages * @param \DateTime $date : Date since which we want the messages
*
* @return array * @return array
*/ */
public function count_by_day_since_for_user(int $id_user, $date) public function count_by_day_since_for_user(int $id_user, $date)
@ -173,15 +172,28 @@ namespace controllers\internals;
return $return; return $return;
} }
/** /**
* Find last sended message for a destination and user * Find last sended message for a destination and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $destination : Destination number * @param string $destination : Destination number
*
* @return array * @return array
*/ */
public function get_last_for_destination_and_user(int $id_user, string $destination) public function get_last_for_destination_and_user(int $id_user, string $destination)
{ {
return $this->get_model()->get_last_for_destination_and_user($id_user, $destination); return $this->get_model()->get_last_for_destination_and_user($id_user, $destination);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Sended($this->bdd);
return $this->model;
}
} }

View File

@ -13,22 +13,13 @@ namespace controllers\internals;
class Setting extends StandardController class Setting extends StandardController
{ {
protected $model = null; protected $model;
/**
* Get the model for the Controller
* @return \descartes\Model
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Setting($this->bdd);
return $this->model;
}
/** /**
* Return all settings of a user. * Return all settings of a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -44,12 +35,13 @@ namespace controllers\internals;
return $settings_array; return $settings_array;
} }
/** /**
* Update a setting by his name and user id. * Update a setting by his name and user id.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param string $name : setting name * @param string $name : setting name
* @param mixed $value * @param mixed $value
*
* @return int : number of modified lines * @return int : number of modified lines
*/ */
public function update_for_user(int $id_user, string $name, $value): bool public function update_for_user(int $id_user, string $name, $value): bool
@ -57,12 +49,13 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_by_name_for_user($id_user, $name, $value); return (bool) $this->get_model()->update_by_name_for_user($id_user, $name, $value);
} }
/** /**
* Create a new setting * Create a new setting.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param string $name : setting name * @param string $name : setting name
* @param mixed $value : value of the setting * @param mixed $value : value of the setting
*
* @return bool * @return bool
*/ */
public function create(int $id_user, string $name, $value): bool public function create(int $id_user, string $name, $value): bool
@ -76,10 +69,11 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($setting); return (bool) $this->get_model()->insert($setting);
} }
/** /**
* Generate and insert default settings for a user * Generate and insert default settings for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return bool * @return bool
*/ */
public function create_defaults_for_user(int $id_user) public function create_defaults_for_user(int $id_user)
@ -93,4 +87,16 @@ namespace controllers\internals;
return $all_success; return $all_success;
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Setting($this->bdd);
return $this->model;
}
} }

View File

@ -13,23 +13,14 @@ namespace controllers\internals;
class SmsStop extends StandardController class SmsStop extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a new smsstop.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\SmsStop($this->bdd);
return $this->model;
}
/**
* Create a new smsstop
* @param int $id_user : User id * @param int $id_user : User id
* @param string $number : Number to stop smss for * @param string $number : Number to stop smss for
*
* @return mixed bool|int : False if cannot create smsstop, id of the new smsstop else * @return mixed bool|int : False if cannot create smsstop, id of the new smsstop else
*/ */
public function create(int $id_user, string $number) public function create(int $id_user, string $number)
@ -42,12 +33,13 @@ namespace controllers\internals;
return $this->get_model()->insert($smsstop); return $this->get_model()->insert($smsstop);
} }
/** /**
* Update a smsstop * Update a smsstop.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_smsstop : SmsStop id * @param int $id_smsstop : SmsStop id
* @param string $number : Number to stop smss for * @param string $number : Number to stop smss for
*
* @return mixed bool|int : False if cannot create smsstop, id of the new smsstop else * @return mixed bool|int : False if cannot create smsstop, id of the new smsstop else
*/ */
public function update_for_user(int $id_user, int $id_smsstop, string $number) public function update_for_user(int $id_user, int $id_smsstop, string $number)
@ -59,15 +51,28 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id_smsstop, $datas); return $this->get_model()->update_for_user($id_user, $id_smsstop, $datas);
} }
/** /**
* Return a smsstop by his number and user * Return a smsstop by his number and user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param string $number : phone number * @param string $number : phone number
*
* @return array * @return array
*/ */
public function get_by_number_for_user(int $id_user, string $number) public function get_by_number_for_user(int $id_user, string $number)
{ {
return $this->get_model()->get_by_number_for_user($id_user, $number); return $this->get_model()->get_by_number_for_user($id_user, $number);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\SmsStop($this->bdd);
return $this->model;
}
} }

View File

@ -19,14 +19,8 @@ namespace controllers\internals;
} }
/** /**
* Get the model for the Controller * Return all the entries.
* @return \descartes\Model *
*/
abstract protected function get_model () : \descartes\Model;
/**
* Return all the entries
* @return array * @return array
*/ */
public function get_all() public function get_all()
@ -34,10 +28,11 @@ namespace controllers\internals;
return $this->get_model()->get_all(); return $this->get_model()->get_all();
} }
/** /**
* Return a entry by his id * Return a entry by his id.
*
* @param int $id : Entry id * @param int $id : Entry id
*
* @return array * @return array
*/ */
public function get(int $id) public function get(int $id)
@ -45,11 +40,12 @@ namespace controllers\internals;
return $this->get_model()->get($id); return $this->get_model()->get($id);
} }
/** /**
* Return a entry by his id and a user * Return a entry by his id and a user.
*
* @param int $id_user : Entry id * @param int $id_user : Entry id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return array * @return array
*/ */
public function get_for_user(int $id_user, int $id) public function get_for_user(int $id_user, int $id)
@ -57,10 +53,11 @@ namespace controllers\internals;
return $this->get_model()->get_for_user($id_user, $id); return $this->get_model()->get_for_user($id_user, $id);
} }
/** /**
* Return all entries for a user * Return all entries for a user.
*
* @param int $id_user : Entry id * @param int $id_user : Entry id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -68,12 +65,13 @@ namespace controllers\internals;
return $this->get_model()->gets_for_user($id_user); return $this->get_model()->gets_for_user($id_user);
} }
/** /**
* Return the list of entries for a user * Return the list of entries for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param ?int $nb_entry : Number of entry to return * @param ?int $nb_entry : Number of entry to return
* @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page * @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page
*
* @return array : Entrys list * @return array : Entrys list
*/ */
public function list_for_user(int $id_user, ?int $nb_entry = null, ?int $page = null) public function list_for_user(int $id_user, ?int $nb_entry = null, ?int $page = null)
@ -81,11 +79,12 @@ namespace controllers\internals;
return $this->get_model()->list_for_user($id_user, $nb_entry, $nb_entry * $page); return $this->get_model()->list_for_user($id_user, $nb_entry, $nb_entry * $page);
} }
/** /**
* Return a list of entries in a group of ids and for a user * Return a list of entries in a group of ids and for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param array $ids : ids of entries to find * @param array $ids : ids of entries to find
*
* @return array * @return array
*/ */
public function gets_in_for_user(int $id_user, array $ids) public function gets_in_for_user(int $id_user, array $ids)
@ -93,11 +92,12 @@ namespace controllers\internals;
return $this->get_model()->gets_in_for_user($id_user, $ids); return $this->get_model()->gets_in_for_user($id_user, $ids);
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id) public function delete_for_user(int $id_user, int $id)
@ -105,10 +105,11 @@ namespace controllers\internals;
return $this->get_model()->delete_for_user($id_user, $id); return $this->get_model()->delete_for_user($id_user, $id);
} }
/** /**
* Delete a entry by his id * Delete a entry by his id.
*
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete(int $id) public function delete(int $id)
@ -116,14 +117,22 @@ namespace controllers\internals;
return $this->get_model()->delete($id); return $this->get_model()->delete($id);
} }
/** /**
* Count number of entry for a user * Count number of entry for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return int : number of entries * @return int : number of entries
*/ */
public function count_for_user(int $id_user) public function count_for_user(int $id_user)
{ {
return $this->get_model()->count_for_user($id_user); return $this->get_model()->count_for_user($id_user);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
abstract protected function get_model(): \descartes\Model;
} }

View File

@ -13,12 +13,12 @@ namespace controllers\internals;
/** /**
* Templating questions relative class * Templating questions relative class
* Not a standard controller as it's not linked to a model in any way * Not a standard controller as it's not linked to a model in any way.
*/ */
class Templating class Templating
{ {
/** /**
* Twig environment * Twig environment.
*/ */
private $sandbox; private $sandbox;
@ -52,11 +52,12 @@ namespace controllers\internals;
$this->sandbox = new \Twig\Extension\SandboxExtension($policy, true); $this->sandbox = new \Twig\Extension\SandboxExtension($policy, true);
} }
/** /**
* Render a string as a twig template * Render a string as a twig template.
*
* @param string $template : Template string * @param string $template : Template string
* @param array $datas : Datas to pass to the template * @param array $datas : Datas to pass to the template
*
* @return array : keys, success, error, result * @return array : keys, success, error, result
*/ */
public function render(string $template, array $datas = []) public function render(string $template, array $datas = [])
@ -83,5 +84,4 @@ namespace controllers\internals;
]; ];
} }
} }
} }

View File

@ -13,7 +13,7 @@ namespace controllers\internals;
/** /**
* Some tools frequently used. * Some tools frequently used.
* Not a standard controller as it's not linked to a model in any way * Not a standard controller as it's not linked to a model in any way.
*/ */
class Tool extends \descartes\InternalController class Tool extends \descartes\InternalController
{ {
@ -69,14 +69,17 @@ namespace controllers\internals;
} }
/** /**
* Format a number and make a link to a discussion with this number * Format a number and make a link to a discussion with this number.
*
* @param string $number : Number to format and make a link for * @param string $number : Number to format and make a link for
*
* @return string : Link to the number * @return string : Link to the number
*/ */
public static function phone_link($number) public static function phone_link($number)
{ {
$number_format = \controllers\internals\Tool::phone_format($number); $number_format = self::phone_format($number);
$url = \descartes\Router::url('Discussion', 'show', ['number' => $number]); $url = \descartes\Router::url('Discussion', 'show', ['number' => $number]);
return '<a href="'.self::s($url, false, true, false).'">'.self::s($number_format, false, true, false).'</a>'; return '<a href="'.self::s($url, false, true, false).'">'.self::s($number_format, false, true, false).'</a>';
} }
@ -132,7 +135,6 @@ namespace controllers\internals;
return $objectDate && $objectDate->format($format) === $date; return $objectDate && $objectDate->format($format) === $date;
} }
/** /**
* Cette fonction retourne un mot de passe généré aléatoirement. * Cette fonction retourne un mot de passe généré aléatoirement.
* *
@ -206,8 +208,10 @@ namespace controllers\internals;
} }
/** /**
* Allow to read an uploaded file * Allow to read an uploaded file.
*
* @param array $file : The array extracted from $_FILES['file'] * @param array $file : The array extracted from $_FILES['file']
*
* @return array : ['success' => bool, 'content' => file handler | error message, 'error_code' => $file['error']] * @return array : ['success' => bool, 'content' => file handler | error message, 'error_code' => $file['error']]
*/ */
public static function read_uploaded_file(array $file) public static function read_uploaded_file(array $file)
@ -219,36 +223,37 @@ namespace controllers\internals;
'mime_type' => false, 'mime_type' => false,
]; ];
if ($file['error'] !== UPLOAD_ERR_OK) if (UPLOAD_ERR_OK !== $file['error'])
{ {
switch ($file['error']) switch ($file['error'])
{ {
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
$result['content'] = 'Impossible de télécharger le fichier car il dépasse les '.ini_get('upload_max_filesize') / (1000 * 1000).' Mégaoctets.'; $result['content'] = 'Impossible de télécharger le fichier car il dépasse les '.ini_get('upload_max_filesize') / (1000 * 1000).' Mégaoctets.';
break;
break;
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
$result['content'] = 'Le fichier dépasse la limite de taille.'; $result['content'] = 'Le fichier dépasse la limite de taille.';
break;
break;
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
$result['content'] = 'L\'envoi du fichier a été interrompu.'; $result['content'] = 'L\'envoi du fichier a été interrompu.';
break;
break;
case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_NO_FILE:
$result['content'] = 'Aucun fichier n\'a été envoyé.'; $result['content'] = 'Aucun fichier n\'a été envoyé.';
break;
break;
case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_NO_TMP_DIR:
$result['content'] = 'Le serveur ne dispose pas de fichier temporaire permettant l\'envoi de fichiers.'; $result['content'] = 'Le serveur ne dispose pas de fichier temporaire permettant l\'envoi de fichiers.';
break;
break;
case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_CANT_WRITE:
$result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.'; $result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.';
break;
break;
case UPLOAD_ERR_EXTENSION: case UPLOAD_ERR_EXTENSION:
$result['content'] = 'Le serveur a interrompu l\'envoi du fichier.'; $result['content'] = 'Le serveur a interrompu l\'envoi du fichier.';
break; break;
} }
@ -261,7 +266,7 @@ namespace controllers\internals;
return $result; return $result;
} }
$result['mime_type'] = mime_content_type($tmp_filename) == 'text/plain' ? $file['type'] : mime_content_type($tmp_filename); $result['mime_type'] = 'text/plain' === mime_content_type($tmp_filename) ? $file['type'] : mime_content_type($tmp_filename);
$file_handler = fopen($tmp_filename, 'r'); $file_handler = fopen($tmp_filename, 'r');
$result['success'] = true; $result['success'] = true;
@ -270,10 +275,11 @@ namespace controllers\internals;
return $result; return $result;
} }
/** /**
* Allow to upload file * Allow to upload file.
*
* @param array $file : The array extracted from $_FILES['file'] * @param array $file : The array extracted from $_FILES['file']
*
* @return array : ['success' => bool, 'content' => file path | error message, 'error_code' => $file['error']] * @return array : ['success' => bool, 'content' => file path | error message, 'error_code' => $file['error']]
*/ */
public static function upload_file(array $file) public static function upload_file(array $file)
@ -284,36 +290,37 @@ namespace controllers\internals;
'error_code' => $file['error'] ?? 99, 'error_code' => $file['error'] ?? 99,
]; ];
if ($file['error'] !== UPLOAD_ERR_OK) if (UPLOAD_ERR_OK !== $file['error'])
{ {
switch ($file['error']) switch ($file['error'])
{ {
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
$result['content'] = 'Impossible de télécharger le fichier car il dépasse les '.ini_get('upload_max_filesize') / (1000 * 1000).' Mégaoctets.'; $result['content'] = 'Impossible de télécharger le fichier car il dépasse les '.ini_get('upload_max_filesize') / (1000 * 1000).' Mégaoctets.';
break;
break;
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
$result['content'] = 'Le fichier dépasse la limite de taille.'; $result['content'] = 'Le fichier dépasse la limite de taille.';
break;
break;
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
$result['content'] = 'L\'envoi du fichier a été interrompu.'; $result['content'] = 'L\'envoi du fichier a été interrompu.';
break;
break;
case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_NO_FILE:
$result['content'] = 'Aucun fichier n\'a été envoyé.'; $result['content'] = 'Aucun fichier n\'a été envoyé.';
break;
break;
case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_NO_TMP_DIR:
$result['content'] = 'Le serveur ne dispose pas de fichier temporaire permettant l\'envoi de fichiers.'; $result['content'] = 'Le serveur ne dispose pas de fichier temporaire permettant l\'envoi de fichiers.';
break;
break;
case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_CANT_WRITE:
$result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.'; $result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.';
break;
break;
case UPLOAD_ERR_EXTENSION: case UPLOAD_ERR_EXTENSION:
$result['content'] = 'Le serveur a interrompu l\'envoi du fichier.'; $result['content'] = 'Le serveur a interrompu l\'envoi du fichier.';
break; break;
} }
@ -346,6 +353,7 @@ namespace controllers\internals;
if (!$success) if (!$success)
{ {
$result['content'] = 'Impossible d\'écrire le fichier sur le serveur.'; $result['content'] = 'Impossible d\'écrire le fichier sur le serveur.';
return $result; return $result;
} }

View File

@ -12,7 +12,7 @@
namespace controllers\internals; namespace controllers\internals;
/** /**
* Methods to manage user. Not a standard controller as it has nothing to do with user based restrictions and must be usable only by admin * Methods to manage user. Not a standard controller as it has nothing to do with user based restrictions and must be usable only by admin.
*/ */
class User extends \descartes\InternalController class User extends \descartes\InternalController
{ {
@ -52,9 +52,8 @@ namespace controllers\internals;
return $this->model_user->remove($id); return $this->model_user->remove($id);
} }
/** /**
* Check user credentials * Check user credentials.
* *
* @param string $email : User email * @param string $email : User email
* @param string $password : User password * @param string $password : User password
@ -92,7 +91,6 @@ namespace controllers\internals;
return (bool) $this->model_user->update_password($id, $password); return (bool) $this->model_user->update_password($id, $password);
} }
/** /**
* Update user email. * Update user email.
* *
@ -106,7 +104,6 @@ namespace controllers\internals;
return (bool) $this->model_user->update_email($id, $email); return (bool) $this->model_user->update_email($id, $email);
} }
/** /**
* Update user api key. * Update user api key.
* *
@ -129,7 +126,8 @@ namespace controllers\internals;
} }
/** /**
* Get a user by his email address * Get a user by his email address.
*
* @param string $email : User email * @param string $email : User email
* *
* @return mixed boolean | array : false if cannot find user for this email, the user else * @return mixed boolean | array : false if cannot find user for this email, the user else
@ -139,10 +137,11 @@ namespace controllers\internals;
return $this->model_user->get_by_email($email); return $this->model_user->get_by_email($email);
} }
/** /**
* Find a user by his id * Find a user by his id.
*
* @param string $id : User id * @param string $id : User id
*
* @return mixed array * @return mixed array
*/ */
public function get($id) public function get($id)
@ -150,9 +149,9 @@ namespace controllers\internals;
return $this->model_user->get($id); return $this->model_user->get($id);
} }
/** /**
* Get a user by his api_key address * Get a user by his api_key address.
*
* @param string $api_key : User api key * @param string $api_key : User api key
* *
* @return mixed boolean | array : false if cannot find user for this api key, the user else * @return mixed boolean | array : false if cannot find user for this api key, the user else
@ -163,11 +162,13 @@ namespace controllers\internals;
} }
/** /**
* Update a user by his id * Update a user by his id.
*
* @param mixed $id * @param mixed $id
* @param mixed $email * @param mixed $email
* @param mixed $password * @param mixed $password
* @param mixed $admin * @param mixed $admin
* @param mixed $api_key
* *
* @return int : Number of modified user * @return int : Number of modified user
*/ */
@ -184,7 +185,7 @@ namespace controllers\internals;
} }
/** /**
* Create a new user * Create a new user.
* *
* @param mixed $email * @param mixed $email
* @param mixed $password * @param mixed $password
@ -214,15 +215,16 @@ namespace controllers\internals;
if (!$success) if (!$success)
{ {
$this->delete($new_user_id); $this->delete($new_user_id);
return false; return false;
} }
return $new_user_id; return $new_user_id;
} }
/** /**
* Generate a random api key * Generate a random api key.
*
* @return string : The api key * @return string : The api key
*/ */
public function generate_random_api_key(): string public function generate_random_api_key(): string

View File

@ -13,24 +13,15 @@ namespace controllers\internals;
class Webhook extends StandardController class Webhook extends StandardController
{ {
protected $model = null; protected $model;
/** /**
* Get the model for the Controller * Create a new webhook.
* @return \descartes\Model *
*/
protected function get_model () : \descartes\Model
{
$this->model = $this->model ?? new \models\Webhook($this->bdd);
return $this->model;
}
/**
* Create a new webhook
* @param int $id_user : User id * @param int $id_user : User id
* @param string $url : Webhook url * @param string $url : Webhook url
* @param string $type : Webhook type * @param string $type : Webhook type
*
* @return mixed bool|int : False if cannot create webhook, id of the new webhook else * @return mixed bool|int : False if cannot create webhook, id of the new webhook else
*/ */
public function create(int $id_user, string $url, string $type) public function create(int $id_user, string $url, string $type)
@ -50,13 +41,14 @@ namespace controllers\internals;
return $result; return $result;
} }
/** /**
* Update a webhook * Update a webhook.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Webhook id * @param int $id : Webhook id
* @param string $url : Webhook url * @param string $url : Webhook url
* @param string $type : Webhook type * @param string $type : Webhook type
*
* @return mixed bool|int : False if cannot create webhook, id of the new webhook else * @return mixed bool|int : False if cannot create webhook, id of the new webhook else
*/ */
public function update_for_user(int $id_user, int $id, string $url, string $type) public function update_for_user(int $id_user, int $id, string $url, string $type)
@ -69,15 +61,28 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id, $datas); return $this->get_model()->update_for_user($id_user, $id, $datas);
} }
/** /**
* Find all webhooks for a user and for a type of webhook * Find all webhooks for a user and for a type of webhook.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $type : Webhook type * @param string $type : Webhook type
*
* @return array * @return array
*/ */
public function gets_for_type_and_user(int $id_user, string $type) public function gets_for_type_and_user(int $id_user, string $type)
{ {
return $this->get_model()->gets_for_type_and_user($id_user, $type); return $this->get_model()->gets_for_type_and_user($id_user, $type);
} }
/**
* Get the model for the Controller.
*
* @return \descartes\Model
*/
protected function get_model(): \descartes\Model
{
$this->model = $this->model ?? new \models\Webhook($this->bdd);
return $this->model;
}
} }

View File

@ -70,7 +70,6 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Account', 'show')); return $this->redirect(\descartes\Router::url('Account', 'show'));
} }
/** /**
* Update user email. * Update user email.
* *
@ -118,7 +117,6 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Account', 'show')); return $this->redirect(\descartes\Router::url('Account', 'show'));
} }
/** /**
* Update user api key. * Update user api key.
* *
@ -148,7 +146,6 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Account', 'show')); return $this->redirect(\descartes\Router::url('Account', 'show'));
} }
/** /**
* Delete a user. * Delete a user.
* *

View File

@ -12,11 +12,11 @@
namespace controllers\publics; namespace controllers\publics;
/** /**
* Api to interact with raspisms * Api to interact with raspisms.
*/ */
class Api extends \descartes\ApiController class Api extends \descartes\ApiController
{ {
CONST DEFAULT_RETURN = [ const DEFAULT_RETURN = [
'error' => 0, //Error code 'error' => 0, //Error code
'message' => null, //Any message to describe a potential error 'message' => null, //Any message to describe a potential error
'response' => null, //The content of the response 'response' => null, //The content of the response
@ -24,7 +24,7 @@ namespace controllers\publics;
'prev' => null, //Link to the previous results 'prev' => null, //Link to the previous results
]; ];
CONST ERROR_CODES = [ const ERROR_CODES = [
'NONE' => 0, 'NONE' => 0,
'INVALID_CREDENTIALS' => 1, 'INVALID_CREDENTIALS' => 1,
'INVALID_PARAMETER' => 2, 'INVALID_PARAMETER' => 2,
@ -32,14 +32,13 @@ namespace controllers\publics;
'CANNOT_CREATE' => 8, 'CANNOT_CREATE' => 8,
]; ];
CONST ERROR_MESSAGES = [ const ERROR_MESSAGES = [
'INVALID_CREDENTIALS' => 'Invalid API Key. Please provide a valid API as GET parameter "api_key".', 'INVALID_CREDENTIALS' => 'Invalid API Key. Please provide a valid API as GET parameter "api_key".',
'INVALID_PARAMETER' => 'You have specified an invalid parameter : ', 'INVALID_PARAMETER' => 'You have specified an invalid parameter : ',
'MISSING_PARAMETER' => 'One require parameter is missing : ', 'MISSING_PARAMETER' => 'One require parameter is missing : ',
'CANNOT_CREATE' => 'Cannot create a new entry.', 'CANNOT_CREATE' => 'Cannot create a new entry.',
]; ];
private $internal_user; private $internal_user;
private $internal_phone; private $internal_phone;
private $internal_received; private $internal_received;
@ -49,7 +48,8 @@ namespace controllers\publics;
private $user; private $user;
/** /**
* Construct the object and quit if failed authentication * Construct the object and quit if failed authentication.
*
* @return void; * @return void;
*/ */
public function __construct() public function __construct()
@ -86,22 +86,23 @@ namespace controllers\publics;
} }
} }
/** /**
* List all entries of a certain type for the current user, sorted by id. * List all entries of a certain type for the current user, sorted by id.
*
* @param string $entry_type : Type of entries we want to list ['sended', 'received', 'scheduled', 'contact', 'group', 'conditional_group', 'phone'] * @param string $entry_type : Type of entries we want to list ['sended', 'received', 'scheduled', 'contact', 'group', 'conditional_group', 'phone']
* @param int $page : Pagination number, Default = 0. Group of 25 results. * @param int $page : Pagination number, Default = 0. Group of 25 results.
*
* @return List of entries * @return List of entries
*/ */
public function get_entries(string $entry_type, int $page = 0) public function get_entries(string $entry_type, int $page = 0)
{ {
$entry_types = ['sended', 'received', 'scheduled', 'contact', 'group', 'conditional_group', 'phone']; $entry_types = ['sended', 'received', 'scheduled', 'contact', 'group', 'conditional_group', 'phone'];
if (!in_array($entry_type, $entry_types)) if (!\in_array($entry_type, $entry_types, true))
{ {
$return = self::DEFAULT_RETURN; $return = self::DEFAULT_RETURN;
$return['error'] = self::ERROR_CODES['INVALID_PARAMETER']; $return['error'] = self::ERROR_CODES['INVALID_PARAMETER'];
$return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'] . 'entry_type must be one of : ' . join(', ', $entry_types) . '.'; $return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'].'entry_type must be one of : '.implode(', ', $entry_types).'.';
$this->auto_http_code(false); $this->auto_http_code(false);
$this->json($return); $this->json($return);
@ -109,14 +110,14 @@ namespace controllers\publics;
} }
$controller_str = 'internal_'.$entry_type; $controller_str = 'internal_'.$entry_type;
$controller = $this->$controller_str; $controller = $this->{$controller_str};
$page = (int) $page; $page = (int) $page;
$limit = 25; $limit = 25;
$entries = $controller->list_for_user($this->user['id'], $limit, $page); $entries = $controller->list_for_user($this->user['id'], $limit, $page);
//Special case for scheduled, we must add numbers because its a join //Special case for scheduled, we must add numbers because its a join
if ($entry_type === 'scheduled') if ('scheduled' === $entry_type)
{ {
foreach ($entries as $key => $entry) foreach ($entries as $key => $entry)
{ {
@ -127,7 +128,7 @@ namespace controllers\publics;
} }
} }
//Special case for group we must add contact because its a join //Special case for group we must add contact because its a join
elseif ($entry_type === 'group') elseif ('group' === $entry_type)
{ {
foreach ($entries as $key => $entry) foreach ($entries as $key => $entry)
{ {
@ -135,11 +136,10 @@ namespace controllers\publics;
} }
} }
$return = self::DEFAULT_RETURN; $return = self::DEFAULT_RETURN;
$return['response'] = $entries; $return['response'] = $entries;
if (count($entries) == $limit) if (\count($entries) === $limit)
{ {
$return['next'] = \descartes\Router::url('Api', __FUNCTION__, ['entry_type' => $entry_type, 'page' => $page + 1], ['api_key' => $this->user['api_key']]); $return['next'] = \descartes\Router::url('Api', __FUNCTION__, ['entry_type' => $entry_type, 'page' => $page + 1], ['api_key' => $this->user['api_key']]);
} }
@ -153,9 +153,9 @@ namespace controllers\publics;
$this->json($return); $this->json($return);
} }
/** /**
* Schedule a message to be send * Schedule a message to be send.
*
* @param string $_POST['at'] : Date to send message at format Y-m-d H:i:s * @param string $_POST['at'] : Date to send message at format Y-m-d H:i:s
* @param string $_POST['text'] : Text of the message to send * @param string $_POST['text'] : Text of the message to send
* @param string $_POST['origin'] : Default null. Number to send the message from. If null use a random phone * @param string $_POST['origin'] : Default null. Number to send the message from. If null use a random phone
@ -164,6 +164,7 @@ namespace controllers\publics;
* @param string $_POST['contacts'] : Array of ids of contacts to send message to * @param string $_POST['contacts'] : Array of ids of contacts to send message to
* @param string $_POST['groups'] : Array of ids of groups to send message to * @param string $_POST['groups'] : Array of ids of groups to send message to
* @param string $_POST['conditional_groups'] : Array of ids of conditional groups to send message to * @param string $_POST['conditional_groups'] : Array of ids of conditional groups to send message to
*
* @return Id of scheduled created * @return Id of scheduled created
*/ */
public function post_scheduled() public function post_scheduled()
@ -206,6 +207,7 @@ namespace controllers\publics;
if (!$number) if (!$number)
{ {
unset($numbers[$key]); unset($numbers[$key]);
continue; continue;
} }
@ -252,11 +254,10 @@ namespace controllers\publics;
$this->json($return); $this->json($return);
} }
/** /**
* Delete a scheduled message * Delete a scheduled message.
*
* @param int $id : Id of scheduled message to delete * @param int $id : Id of scheduled message to delete
* @return void on success, error else
*/ */
public function delete_scheduled(int $id) public function delete_scheduled(int $id)
{ {
@ -265,10 +266,10 @@ namespace controllers\publics;
if (!$success) if (!$success)
{ {
$this->auto_http_code(false); $this->auto_http_code(false);
return false; return false;
} }
$this->auto_http_code(true); $this->auto_http_code(true);
} }
} }

View File

@ -12,7 +12,7 @@
namespace controllers\publics; namespace controllers\publics;
/** /**
* Controller of callback pages, like sms status update notification * Controller of callback pages, like sms status update notification.
*/ */
class Callback extends \descartes\Controller class Callback extends \descartes\Controller
{ {
@ -30,8 +30,10 @@ namespace controllers\publics;
} }
/** /**
* Function call on a sended sms status change notification reception * Function call on a sended sms status change notification reception.
*
* @param string $adapter_name : Name of the adapter to use * @param string $adapter_name : Name of the adapter to use
*
* @return false : We must always return false, and we respect a random usleep before returning anything * @return false : We must always return false, and we respect a random usleep before returning anything
* in order to prevent bruteforce api key guessing and time guessing * in order to prevent bruteforce api key guessing and time guessing
*/ */
@ -40,7 +42,6 @@ namespace controllers\publics;
//Wait between 0.5 and 1.03s in order to counter time guessing bruteforce attack against api key //Wait between 0.5 and 1.03s in order to counter time guessing bruteforce attack against api key
usleep(mt_rand(5, 10) / 10 * 1000000 + mt_rand(0, 30000)); usleep(mt_rand(5, 10) / 10 * 1000000 + mt_rand(0, 30000));
//Search for an adapter //Search for an adapter
$find_adapter = false; $find_adapter = false;
$adapters = $this->internal_adapter->list_adapters(); $adapters = $this->internal_adapter->list_adapters();

View File

@ -40,7 +40,7 @@ namespace controllers\publics;
} }
/** /**
* Return all conditionnals groups for administration * Return all conditionnals groups for administration.
* *
* @param mixed $page * @param mixed $page
*/ */
@ -48,7 +48,6 @@ namespace controllers\publics;
{ {
$page = (int) $page; $page = (int) $page;
$groups = $this->internal_conditional_group->list_for_user($_SESSION['user']['id'], 25, $page); $groups = $this->internal_conditional_group->list_for_user($_SESSION['user']['id'], 25, $page);
$this->render('conditional_group/list', ['groups' => $groups]); $this->render('conditional_group/list', ['groups' => $groups]);
} }
@ -179,10 +178,11 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('ConditionalGroup', 'list')); return $this->redirect(\descartes\Router::url('ConditionalGroup', 'list'));
} }
/** /**
* Try to get the preview of contacts for a conditionnal group * Try to get the preview of contacts for a conditionnal group.
*
* @param string $_POST['condition'] : Condition to apply * @param string $_POST['condition'] : Condition to apply
*
* @return json string * @return json string
*/ */
public function contacts_preview() public function contacts_preview()
@ -198,16 +198,17 @@ namespace controllers\publics;
{ {
$return['result'] = 'Vous devez renseigner une condition.'; $return['result'] = 'Vous devez renseigner une condition.';
echo json_encode($return); echo json_encode($return);
return false; return false;
} }
$internal_ruler = new \controllers\internals\Ruler(); $internal_ruler = new \controllers\internals\Ruler();
$valid_condition = $internal_ruler->validate_condition($condition, ['contact' => (object) ['datas' => (object) null]]); $valid_condition = $internal_ruler->validate_condition($condition, ['contact' => (object) ['datas' => (object) null]]);
if (!$valid_condition) if (!$valid_condition)
{ {
$return['result'] = 'Syntaxe de la condition invalide.'; $return['result'] = 'Syntaxe de la condition invalide.';
echo json_encode($return); echo json_encode($return);
return false; return false;
} }
@ -216,6 +217,7 @@ namespace controllers\publics;
{ {
$return['result'] = 'Aucun contact dans le groupe.'; $return['result'] = 'Aucun contact dans le groupe.';
echo json_encode($return); echo json_encode($return);
return false; return false;
} }
@ -225,16 +227,15 @@ namespace controllers\publics;
$contacts_name[] = $contact['name']; $contacts_name[] = $contact['name'];
} }
$return['result'] = "Contacts du groupe : " . implode(', ', $contacts_name); $return['result'] = 'Contacts du groupe : '.implode(', ', $contacts_name);
$return['success'] = true; $return['success'] = true;
echo json_encode($return); echo json_encode($return);
return true; return true;
} }
/** /**
* Return the list of groups as JSON * Return the list of groups as JSON.
*/ */
public function json_list() public function json_list()
{ {

View File

@ -151,7 +151,7 @@ namespace controllers\publics;
$clean_datas = []; $clean_datas = [];
foreach ($datas as $key => $value) foreach ($datas as $key => $value)
{ {
if ($value === "") if ('' === $value)
{ {
continue; continue;
} }
@ -191,7 +191,7 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
if (!array($_POST['contacts'])) if (![$_POST['contacts']])
{ {
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
@ -218,7 +218,7 @@ namespace controllers\publics;
$clean_datas = []; $clean_datas = [];
foreach ($datas as $key => $value) foreach ($datas as $key => $value)
{ {
if ($value === "") if ('' === $value)
{ {
continue; continue;
} }
@ -243,9 +243,9 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
/** /**
* Allow to import a contacts list * Allow to import a contacts list.
*
* @param string $csrf : Csrf token * @param string $csrf : Csrf token
* @param $_FILES['contacts_list_file'] : A csv file of the contacts to import * @param $_FILES['contacts_list_file'] : A csv file of the contacts to import
*/ */
@ -254,6 +254,7 @@ namespace controllers\publics;
if (!$this->verify_csrf($csrf)) if (!$this->verify_csrf($csrf))
{ {
\FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !'); \FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
@ -263,6 +264,7 @@ namespace controllers\publics;
if (!$upload_array) if (!$upload_array)
{ {
\FlashMessage\FlashMessage::push('danger', 'Vous devez fournir un fichier de contacts à importer.'); \FlashMessage\FlashMessage::push('danger', 'Vous devez fournir un fichier de contacts à importer.');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
@ -270,6 +272,7 @@ namespace controllers\publics;
if (!$read_file['success']) if (!$read_file['success'])
{ {
\FlashMessage\FlashMessage::push('danger', $read_file['content']); \FlashMessage\FlashMessage::push('danger', $read_file['content']);
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
@ -279,12 +282,12 @@ namespace controllers\publics;
{ {
case 'text/csv': case 'text/csv':
$result = $this->internal_contact->import_csv($id_user, $read_file['content']); $result = $this->internal_contact->import_csv($id_user, $read_file['content']);
break;
break;
case 'application/json': case 'application/json':
$result = $this->internal_contact->import_json($id_user, $read_file['content']); $result = $this->internal_contact->import_json($id_user, $read_file['content']);
break;
break;
default: default:
$invalid_type = true; $invalid_type = true;
} }
@ -292,12 +295,14 @@ namespace controllers\publics;
if ($invalid_type) if ($invalid_type)
{ {
\FlashMessage\FlashMessage::push('danger', 'Le type de fichier n\'est pas valide.'); \FlashMessage\FlashMessage::push('danger', 'Le type de fichier n\'est pas valide.');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
if ($result === false) if (false === $result)
{ {
\FlashMessage\FlashMessage::push('danger', 'Le fichier contient des erreurs. Impossible d\'importer les contacts.'); \FlashMessage\FlashMessage::push('danger', 'Le fichier contient des erreurs. Impossible d\'importer les contacts.');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
@ -308,12 +313,13 @@ namespace controllers\publics;
} }
\FlashMessage\FlashMessage::push('success', $msg); \FlashMessage\FlashMessage::push('success', $msg);
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
/** /**
* Allow to export a contacts list * Allow to export a contacts list.
*
* @param $format : Format to export contacts to * @param $format : Format to export contacts to
*/ */
public function export(string $format) public function export(string $format)
@ -326,12 +332,12 @@ namespace controllers\publics;
{ {
case 'csv': case 'csv':
$result = $this->internal_contact->export_csv($id_user); $result = $this->internal_contact->export_csv($id_user);
break;
break;
case 'json': case 'json':
$result = $this->internal_contact->export_json($id_user); $result = $this->internal_contact->export_json($id_user);
break;
break;
default: default:
$invalid_type = true; $invalid_type = true;
} }
@ -339,12 +345,14 @@ namespace controllers\publics;
if ($invalid_type) if ($invalid_type)
{ {
\FlashMessage\FlashMessage::push('danger', 'Le format demandé n\'est pas supporté.'); \FlashMessage\FlashMessage::push('danger', 'Le format demandé n\'est pas supporté.');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }
if ($result === false) if (false === $result)
{ {
\FlashMessage\FlashMessage::push('danger', 'Nous ne sommes par parveu à exporté les contacts.'); \FlashMessage\FlashMessage::push('danger', 'Nous ne sommes par parveu à exporté les contacts.');
return $this->redirect(\descartes\Router::url('Contact', 'list')); return $this->redirect(\descartes\Router::url('Contact', 'list'));
} }

View File

@ -71,7 +71,6 @@ namespace controllers\publics;
$receiveds = $this->internal_received->get_lasts_by_date_for_user($id_user, 10); $receiveds = $this->internal_received->get_lasts_by_date_for_user($id_user, 10);
$events = $this->internal_event->get_lasts_by_date_for_user($id_user, 10); $events = $this->internal_event->get_lasts_by_date_for_user($id_user, 10);
//Récupération du nombre de Sms envoyés et reçus depuis les 7 derniers jours //Récupération du nombre de Sms envoyés et reçus depuis les 7 derniers jours
$nb_sendeds_by_day = $this->internal_sended->count_by_day_since_for_user($id_user, $formated_date); $nb_sendeds_by_day = $this->internal_sended->count_by_day_since_for_user($id_user, $formated_date);
$nb_receiveds_by_day = $this->internal_received->count_by_day_since_for_user($id_user, $formated_date); $nb_receiveds_by_day = $this->internal_received->count_by_day_since_for_user($id_user, $formated_date);

View File

@ -113,7 +113,7 @@ namespace controllers\publics;
foreach ($receiveds as $received) foreach ($receiveds as $received)
{ {
if ($received['status'] != 'read') if ('read' !== $received['status'])
{ {
$this->internal_received->mark_as_read_for_user($id_user, $received['id']); $this->internal_received->mark_as_read_for_user($id_user, $received['id']);
} }

View File

@ -93,11 +93,13 @@ class Phone extends \descartes\Controller
public function add() public function add()
{ {
$adapters = $this->internal_adapter->list_adapters(); $adapters = $this->internal_adapter->list_adapters();
return $this->render('phone/add', ['adapters' => $adapters]); return $this->render('phone/add', ['adapters' => $adapters]);
} }
/** /**
* Create a new phone * Create a new phone.
*
* @param $csrf : CSRF token * @param $csrf : CSRF token
* @param string $_POST['number'] : Phone number * @param string $_POST['number'] : Phone number
* @param string $_POST['adapter'] : Phone adapter * @param string $_POST['adapter'] : Phone adapter
@ -108,6 +110,7 @@ class Phone extends \descartes\Controller
if (!$this->verify_csrf($csrf)) if (!$this->verify_csrf($csrf))
{ {
\FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !'); \FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
@ -119,14 +122,15 @@ class Phone extends \descartes\Controller
if (!$number || !$adapter) if (!$number || !$adapter)
{ {
\FlashMessage\FlashMessage::push('danger', 'Des champs obligatoires sont manquants.'); \FlashMessage\FlashMessage::push('danger', 'Des champs obligatoires sont manquants.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
$number = \controllers\internals\Tool::parse_phone($number); $number = \controllers\internals\Tool::parse_phone($number);
if (!$number) if (!$number)
{ {
\FlashMessage\FlashMessage::push('danger', 'Numéro de téléphone incorrect.'); \FlashMessage\FlashMessage::push('danger', 'Numéro de téléphone incorrect.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
@ -134,10 +138,10 @@ class Phone extends \descartes\Controller
if ($number_exist) if ($number_exist)
{ {
\FlashMessage\FlashMessage::push('danger', 'Ce numéro de téléphone est déjà utilisé.'); \FlashMessage\FlashMessage::push('danger', 'Ce numéro de téléphone est déjà utilisé.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
$adapters = $this->internal_adapter->list_adapters(); $adapters = $this->internal_adapter->list_adapters();
$find_adapter = false; $find_adapter = false;
foreach ($adapters as $metas) foreach ($adapters as $metas)
@ -145,6 +149,7 @@ class Phone extends \descartes\Controller
if ($metas['meta_classname'] === $adapter) if ($metas['meta_classname'] === $adapter)
{ {
$find_adapter = $metas; $find_adapter = $metas;
break; break;
} }
} }
@ -152,13 +157,14 @@ class Phone extends \descartes\Controller
if (!$find_adapter) if (!$find_adapter)
{ {
\FlashMessage\FlashMessage::push('danger', 'Cet adaptateur n\'existe pas.'); \FlashMessage\FlashMessage::push('danger', 'Cet adaptateur n\'existe pas.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
//If missing required data fields, error //If missing required data fields, error
foreach ($find_adapter['meta_datas_fields'] as $field) foreach ($find_adapter['meta_datas_fields'] as $field)
{ {
if ($field['required'] === false) if (false === $field['required'])
{ {
continue; continue;
} }
@ -169,6 +175,7 @@ class Phone extends \descartes\Controller
} }
\FlashMessage\FlashMessage::push('danger', 'Vous n\'avez pas rempli certains champs obligatoires pour l\'adaptateur choisis.'); \FlashMessage\FlashMessage::push('danger', 'Vous n\'avez pas rempli certains champs obligatoires pour l\'adaptateur choisis.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
@ -182,18 +189,20 @@ class Phone extends \descartes\Controller
if (!$adapter_working) if (!$adapter_working)
{ {
\FlashMessage\FlashMessage::push('danger', 'Impossible d\'utiliser l\'adaptateur choisis avec les données fournies. Vérifiez le numéro de téléphone et les réglages.'); \FlashMessage\FlashMessage::push('danger', 'Impossible d\'utiliser l\'adaptateur choisis avec les données fournies. Vérifiez le numéro de téléphone et les réglages.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
$success = $this->internal_phone->create($id_user, $number, $adapter, $adapter_datas); $success = $this->internal_phone->create($id_user, $number, $adapter, $adapter_datas);
if (!$success) if (!$success)
{ {
\FlashMessage\FlashMessage::push('danger', 'Impossible de créer ce téléphone.'); \FlashMessage\FlashMessage::push('danger', 'Impossible de créer ce téléphone.');
return $this->redirect(\descartes\Router::url('Phone', 'add')); return $this->redirect(\descartes\Router::url('Phone', 'add'));
} }
\FlashMessage\FlashMessage::push('success', 'Le téléphone a bien été créé.'); \FlashMessage\FlashMessage::push('success', 'Le téléphone a bien été créé.');
return $this->redirect(\descartes\Router::url('Phone', 'list')); return $this->redirect(\descartes\Router::url('Phone', 'list'));
} }
} }

View File

@ -49,7 +49,7 @@ namespace controllers\publics;
foreach ($receiveds as $key => $received) foreach ($receiveds as $key => $received)
{ {
if ($received['status'] != 'read') if ('read' !== $received['status'])
{ {
$this->internal_received->mark_as_read_for_user($_SESSION['user']['id'], $received['id']); $this->internal_received->mark_as_read_for_user($_SESSION['user']['id'], $received['id']);
} }
@ -65,9 +65,9 @@ namespace controllers\publics;
$this->render('received/list', ['receiveds' => $receiveds, 'page' => $page, 'limit' => $limit, 'nb_results' => \count($receiveds)]); $this->render('received/list', ['receiveds' => $receiveds, 'page' => $page, 'limit' => $limit, 'nb_results' => \count($receiveds)]);
} }
/** /**
* Return all unread receiveds messages * Return all unread receiveds messages.
*
* @param mixed $page * @param mixed $page
*/ */
public function list_unread($page = 0) public function list_unread($page = 0)
@ -92,7 +92,8 @@ namespace controllers\publics;
} }
/** /**
* Delete Receiveds * Delete Receiveds.
*
* @param array int $_GET['ids'] : Ids of receiveds to delete * @param array int $_GET['ids'] : Ids of receiveds to delete
* @param mixed $csrf * @param mixed $csrf
* *
@ -103,6 +104,7 @@ namespace controllers\publics;
if (!$this->verify_csrf($csrf)) if (!$this->verify_csrf($csrf))
{ {
\FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !'); \FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !');
return $this->redirect(\descartes\Router::url('Received', 'list')); return $this->redirect(\descartes\Router::url('Received', 'list'));
} }

View File

@ -88,6 +88,7 @@ namespace controllers\publics;
/** /**
* Cette fonction retourne la page d'ajout d'un scheduled. * Cette fonction retourne la page d'ajout d'un scheduled.
*
* @param $prefilled : If we have prefilled some fields (possible values : 'contacts', 'groups', 'conditional_groups', false) * @param $prefilled : If we have prefilled some fields (possible values : 'contacts', 'groups', 'conditional_groups', false)
*/ */
public function add($prefilled = false) public function add($prefilled = false)
@ -110,21 +111,21 @@ namespace controllers\publics;
$ids = $_GET['ids'] ?? []; $ids = $_GET['ids'] ?? [];
} }
if ($prefilled === 'contacts') if ('contacts' === $prefilled)
{ {
foreach ($this->internal_contact->gets_in_for_user($id_user, $ids) as $contact) foreach ($this->internal_contact->gets_in_for_user($id_user, $ids) as $contact)
{ {
$prefilled_contacts[] = $contact['id']; $prefilled_contacts[] = $contact['id'];
} }
} }
elseif ($prefilled === 'groups') elseif ('groups' === $prefilled)
{ {
foreach ($this->internal_group->gets_in_for_user($id_user, $ids) as $group) foreach ($this->internal_group->gets_in_for_user($id_user, $ids) as $group)
{ {
$prefilled_groups[] = $group['id']; $prefilled_groups[] = $group['id'];
} }
} }
elseif ($prefilled === 'conditional_groups') elseif ('conditional_groups' === $prefilled)
{ {
foreach ($this->internal_conditional_group->gets_in_for_user($id_user, $ids) as $conditional_group) foreach ($this->internal_conditional_group->gets_in_for_user($id_user, $ids) as $conditional_group)
{ {
@ -154,6 +155,7 @@ namespace controllers\publics;
if (!$ids) if (!$ids)
{ {
\FlashMessage\FlashMessage::push('danger', 'Vous devez choisir des messages à mettre à jour !'); \FlashMessage\FlashMessage::push('danger', 'Vous devez choisir des messages à mettre à jour !');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
@ -272,30 +274,31 @@ namespace controllers\publics;
if (!$numbers && !$contacts && !$groups && !$conditional_groups) if (!$numbers && !$contacts && !$groups && !$conditional_groups)
{ {
\FlashMessage\FlashMessage::push('danger', 'Vous devez renseigner au moins un destinataire pour le Sms.'); \FlashMessage\FlashMessage::push('danger', 'Vous devez renseigner au moins un destinataire pour le Sms.');
return $this->redirect(\descartes\Router::url('Scheduled', 'add')); return $this->redirect(\descartes\Router::url('Scheduled', 'add'));
} }
if ($origin && !$this->internal_phone->get_by_number_and_user($id_user, $origin)) if ($origin && !$this->internal_phone->get_by_number_and_user($id_user, $origin))
{ {
\FlashMessage\FlashMessage::push('danger', 'Ce numéro n\'existe pas ou vous n\'en êtes pas propriétaire.'); \FlashMessage\FlashMessage::push('danger', 'Ce numéro n\'existe pas ou vous n\'en êtes pas propriétaire.');
return $this->redirect(\descartes\Router::url('Scheduled', 'add')); return $this->redirect(\descartes\Router::url('Scheduled', 'add'));
} }
$scheduled_id = $this->internal_scheduled->create($id_user, $at, $text, $origin, $flash, $numbers, $contacts, $groups, $conditional_groups); $scheduled_id = $this->internal_scheduled->create($id_user, $at, $text, $origin, $flash, $numbers, $contacts, $groups, $conditional_groups);
if (!$scheduled_id) if (!$scheduled_id)
{ {
\FlashMessage\FlashMessage::push('danger', 'Impossible de créer le Sms.'); \FlashMessage\FlashMessage::push('danger', 'Impossible de créer le Sms.');
return $this->redirect(\descartes\Router::url('Scheduled', 'add')); return $this->redirect(\descartes\Router::url('Scheduled', 'add'));
} }
//If mms is enabled, try to process a media to link to the scheduled //If mms is enabled, try to process a media to link to the scheduled
$media = $_FILES['media'] ?? false; $media = $_FILES['media'] ?? false;
if (!($_SESSION['user']['settings']['mms'] ?? false) || !$media) if (!($_SESSION['user']['settings']['mms'] ?? false) || !$media)
{ {
\FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.'); \FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
@ -303,10 +306,12 @@ namespace controllers\publics;
if (!$success) if (!$success)
{ {
\FlashMessage\FlashMessage::push('success', 'Le SMS a bien été créé mais le média n\'as pas pu être enregistré.'); \FlashMessage\FlashMessage::push('success', 'Le SMS a bien été créé mais le média n\'as pas pu être enregistré.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
\FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.'); \FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
@ -329,7 +334,6 @@ namespace controllers\publics;
$scheduleds = $_POST['scheduleds'] ?? []; $scheduleds = $_POST['scheduleds'] ?? [];
$nb_update = 0; $nb_update = 0;
foreach ($scheduleds as $id_scheduled => $scheduled) foreach ($scheduleds as $id_scheduled => $scheduled)
{ {
@ -349,7 +353,6 @@ namespace controllers\publics;
continue; continue;
} }
if (empty($text)) if (empty($text))
{ {
continue; continue;
@ -378,7 +381,6 @@ namespace controllers\publics;
continue; continue;
} }
if ($origin && !$this->internal_phone->get_by_number_and_user($id_user, $origin)) if ($origin && !$this->internal_phone->get_by_number_and_user($id_user, $origin))
{ {
continue; continue;
@ -408,17 +410,18 @@ namespace controllers\publics;
} }
*/ */
$nb_update += 1; ++$nb_update;
} }
if ($nb_update != count($scheduleds)) if ($nb_update !== \count($scheduleds))
{ {
\FlashMessage\FlashMessage::push('danger', 'Certains SMS n\'ont pas été mis à jour.'); \FlashMessage\FlashMessage::push('danger', 'Certains SMS n\'ont pas été mis à jour.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
\FlashMessage\FlashMessage::push('success', 'Tous les SMS ont été mis à jour.'); \FlashMessage\FlashMessage::push('success', 'Tous les SMS ont été mis à jour.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list')); return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
} }
} }

View File

@ -57,6 +57,7 @@ namespace controllers\publics;
if (false === $setting_value) if (false === $setting_value)
{ {
\FlashMessage\FlashMessage::push('danger', 'Vous devez renseigner une valeure pour le réglage.'); \FlashMessage\FlashMessage::push('danger', 'Vous devez renseigner une valeure pour le réglage.');
return $this->redirect(\descartes\Router::url('Setting', 'show')); return $this->redirect(\descartes\Router::url('Setting', 'show'));
} }
@ -72,6 +73,7 @@ namespace controllers\publics;
$_SESSION['user']['settings'] = $settings; $_SESSION['user']['settings'] = $settings;
\FlashMessage\FlashMessage::push('success', 'Le réglage a bien été mis à jour.'); \FlashMessage\FlashMessage::push('success', 'Le réglage a bien été mis à jour.');
return $this->redirect(\descartes\Router::url('Setting', 'show')); return $this->redirect(\descartes\Router::url('Setting', 'show'));
} }
} }

View File

@ -32,9 +32,11 @@ namespace controllers\publics;
} }
/** /**
* Try to render a template as a message for preview * Try to render a template as a message for preview.
*
* @param string $_POST['template'] : Template string * @param string $_POST['template'] : Template string
* @param int $_POST['id_contact'] : Id of the contact to render the template for * @param int $_POST['id_contact'] : Id of the contact to render the template for
*
* @return json string * @return json string
*/ */
public function render_preview() public function render_preview()
@ -51,6 +53,7 @@ namespace controllers\publics;
{ {
$return['result'] = 'Veuillez remplir un message.'; $return['result'] = 'Veuillez remplir un message.';
echo json_encode($return); echo json_encode($return);
return false; return false;
} }
@ -59,6 +62,7 @@ namespace controllers\publics;
{ {
$return['result'] = 'Ce contact n\'existe pas.'; $return['result'] = 'Ce contact n\'existe pas.';
echo json_encode($return); echo json_encode($return);
return false; return false;
} }
@ -76,6 +80,7 @@ namespace controllers\publics;
} }
echo json_encode($return); echo json_encode($return);
return true; return true;
} }
} }

View File

@ -30,7 +30,7 @@ namespace controllers\publics;
} }
/** /**
* List all webhooks * List all webhooks.
* *
* @param mixed $page * @param mixed $page
*/ */
@ -42,7 +42,7 @@ namespace controllers\publics;
} }
/** /**
* Delete a list of webhooks * Delete a list of webhooks.
* *
* @param array int $_GET['ids'] : Les id des webhooks à supprimer * @param array int $_GET['ids'] : Les id des webhooks à supprimer
* @param mixed $csrf * @param mixed $csrf
@ -77,7 +77,7 @@ namespace controllers\publics;
} }
/** /**
* Edit a list of webhooks * Edit a list of webhooks.
* *
* @param array int $_GET['ids'] : ids of webhooks to edit * @param array int $_GET['ids'] : ids of webhooks to edit
*/ */
@ -93,7 +93,7 @@ namespace controllers\publics;
} }
/** /**
* Insert a new webhook * Insert a new webhook.
* *
* @param $csrf : Le jeton CSRF * @param $csrf : Le jeton CSRF
* @param string $_POST['url'] : URL to call on webhook release * @param string $_POST['url'] : URL to call on webhook release

View File

@ -1,9 +1,18 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace daemons; namespace daemons;
/** /**
* Class defining the global structur of a Linux Daemon * Class defining the global structur of a Linux Daemon.
*/ */
abstract class AbstractDaemon abstract class AbstractDaemon
{ {
@ -12,15 +21,15 @@ abstract class AbstractDaemon
protected $logger; protected $logger;
protected $no_parent; protected $no_parent;
private $is_running = true; private $is_running = true;
private $signals = array ( private $signals = [
SIGTERM, SIGTERM,
SIGINT, SIGINT,
SIGCHLD, SIGCHLD,
SIGHUP SIGHUP,
); ];
/** /**
* Class used to handle POSIX signals and fork from the current process * Class used to handle POSIX signals and fork from the current process.
* *
* @param string $name : The name of the class * @param string $name : The name of the class
* @param object $logger : A PSR3 logger instance * @param object $logger : A PSR3 logger instance
@ -45,95 +54,83 @@ abstract class AbstractDaemon
$this->register_signals(); $this->register_signals();
} }
/** /**
* Used to register POSIX signals * True if the daemon is running.
*/ */
private function register_signals() public function is_running()
{ {
//Enable a tick at every 1 instruction, allowing us to run a function frequently, for exemple looking at signal status return $this->is_running;
declare(ticks = 1);
foreach ($this->signals as $signal)
{
//For each signal define the method handle_signal of the current class as the way to handle it
@pcntl_signal($signal, [
'self',
'handle_signal'
]);
}
} }
/** /**
* Used to handle properly SIGINT, SIGTERM, SIGCHLD and SIGHUP * Used to handle properly SIGINT, SIGTERM, SIGCHLD and SIGHUP.
* *
* @param int $signal * @param int $signal
* @param mixed $signinfo * @param mixed $signinfo
*/ */
protected function handle_signal(int $signal, $signinfo) protected function handle_signal(int $signal, $signinfo)
{ {
if ($signal == SIGTERM || $signal == SIGINT) //Stop the daemon if (SIGTERM === $signal || SIGINT === $signal)
{ { //Stop the daemon
$this->is_running = false; $this->is_running = false;
} }
else if ($signal == SIGHUP) //Restart the daemon elseif (SIGHUP === $signal)
{ { //Restart the daemon
$this->on_stop(); $this->on_stop();
$this->on_start(); $this->on_start();
} }
else if ($signal == SIGCHLD) //On daemon child stopping elseif (SIGCHLD === $signal)
{ { //On daemon child stopping
pcntl_waitpid(-1, $status, WNOHANG); pcntl_waitpid(-1, $status, WNOHANG);
} }
else //All the other signals else
{ { //All the other signals
$this->handle_other_signals($signal); $this->handle_other_signals($signal);
} }
} }
/** /**
* Launch the infinite loop executing the "run" abstract method * Launch the infinite loop executing the "run" abstract method.
*/ */
protected function start() protected function start()
{ {
//If process must be uniq and a process with the same pid file is already running //If process must be uniq and a process with the same pid file is already running
if (file_exists($this->pid_dir.'/'.$this->name.'.pid') && $this->uniq) if (file_exists($this->pid_dir.'/'.$this->name.'.pid') && $this->uniq)
{ {
$this->logger->info("Another process named " . $this->name . " is already running."); $this->logger->info('Another process named '.$this->name.' is already running.');
return false; return false;
} }
//If we must make the daemon independant from any parent, we do a fork and die operation //If we must make the daemon independant from any parent, we do a fork and die operation
if ($this->no_parent) if ($this->no_parent)
{ {
$pid = pcntl_fork(); //Fork current process into a child, so we can kill current process and keep only the child with parent PID = 1 $pid = pcntl_fork(); //Fork current process into a child, so we can kill current process and keep only the child with parent PID = 1
if ($pid == -1) //Impossible to run script if (-1 === $pid)
{ { //Impossible to run script
$this->logger->critical("Impossible to create a subprocess."); $this->logger->critical('Impossible to create a subprocess.');
return false; return false;
} }
elseif ($pid) //Current script if ($pid)
{ { //Current script
return true; return true;
} }
$this->logger->info("Process $this->name started as a child with pid " . getmypid() . "."); $this->logger->info("Process {$this->name} started as a child with pid ".getmypid().'.');
//Child script //Child script
$sid = posix_setsid(); //Try to make the child process a main process $sid = posix_setsid(); //Try to make the child process a main process
if ($sid == -1) //Error if (-1 === $sid)
{ { //Error
$this->logger->critical("Cannot make the child process with pid $pid independent."); $this->logger->critical("Cannot make the child process with pid {$pid} independent.");
exit(1); exit(1);
} }
$this->logger->info("The child process with pid " . getmypid() . " is now independent."); $this->logger->info('The child process with pid '.getmypid().' is now independent.');
} }
//Create pid dir if not exists //Create pid dir if not exists
if (!file_exists($this->pid_dir)) if (!file_exists($this->pid_dir))
{ {
@ -145,14 +142,12 @@ abstract class AbstractDaemon
} }
} }
//Set process name //Set process name
cli_set_process_title($this->name); cli_set_process_title($this->name);
//Write the pid of the process into a file //Write the pid of the process into a file
file_put_contents($this->pid_dir.'/'.$this->name.'.pid', getmypid()); file_put_contents($this->pid_dir.'/'.$this->name.'.pid', getmypid());
//Really start the daemon //Really start the daemon
$this->on_start(); $this->on_start();
@ -166,13 +161,12 @@ abstract class AbstractDaemon
} }
catch (\Exception $e) catch (\Exception $e)
{ {
$this->logger->critical('Exception : ' . $e->getMessage() . " in " . $e->getFile() . " line " . $e->getLine()); $this->logger->critical('Exception : '.$e->getMessage().' in '.$e->getFile().' line '.$e->getLine());
} }
//Stop the daemon //Stop the daemon
$this->on_stop(); $this->on_stop();
//Delete pid file //Delete pid file
if (file_exists($this->pid_dir.'/'.$this->name.'.pid')) if (file_exists($this->pid_dir.'/'.$this->name.'.pid'))
{ {
@ -180,37 +174,43 @@ abstract class AbstractDaemon
} }
} }
/** /**
* True if the daemon is running * Override to implement the code that run infinetly (actually, it run one time but repeat the operation infinetly.
*/ */
public function is_running() abstract protected function run();
{
return $this->is_running;
}
/** /**
* Override to implement the code that run infinetly (actually, it run one time but repeat the operation infinetly * Override to execute code before the ''run'' method on daemon start.
*/ */
protected abstract function run(); abstract protected function on_start();
/** /**
* Override to execute code before the ''run'' method on daemon start * Override to execute code after the ''run'' method on daemon shutdown.
*/ */
protected abstract function on_start(); abstract protected function on_stop();
/** /**
* Override to execute code after the ''run'' method on daemon shutdown * Override to handle additional POSIX signals.
*/
protected abstract function on_stop();
/**
* Override to handle additional POSIX signals
* *
* @param int $signal : Signal sent by interrupt * @param int $signal : Signal sent by interrupt
*/ */
protected abstract function handle_other_signals(int $signal); abstract protected function handle_other_signals(int $signal);
/**
* Used to register POSIX signals.
*/
private function register_signals()
{
//Enable a tick at every 1 instruction, allowing us to run a function frequently, for exemple looking at signal status
declare(ticks=1);
foreach ($this->signals as $signal)
{
//For each signal define the method handle_signal of the current class as the way to handle it
@pcntl_signal($signal, [
'self',
'handle_signal',
]);
}
}
} }

View File

@ -1,11 +1,21 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace daemons; namespace daemons;
use \Monolog\Logger; use Monolog\Handler\StreamHandler;
use \Monolog\Handler\StreamHandler; use Monolog\Logger;
/** /**
* Main daemon class * Main daemon class.
*/ */
class Launcher extends AbstractDaemon class Launcher extends AbstractDaemon
{ {
@ -16,7 +26,7 @@ class Launcher extends AbstractDaemon
public function __construct() public function __construct()
{ {
$name = "RaspiSMS Daemon Launcher"; $name = 'RaspiSMS Daemon Launcher';
$logger = new Logger($name); $logger = new Logger($name);
$logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG)); $logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG));
@ -31,14 +41,12 @@ class Launcher extends AbstractDaemon
parent::start(); parent::start();
} }
public function run() public function run()
{ {
//Create the internal controllers //Create the internal controllers
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8'); $this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$this->internal_phone = new \controllers\internals\Phone($this->bdd); $this->internal_phone = new \controllers\internals\Phone($this->bdd);
$this->start_sender_daemon(); $this->start_sender_daemon();
$this->start_webhook_daemon(); $this->start_webhook_daemon();
@ -49,10 +57,8 @@ class Launcher extends AbstractDaemon
sleep(1); sleep(1);
} }
/** /**
* Function to start sender daemon * Function to start sender daemon.
* @return void
*/ */
public function start_sender_daemon() public function start_sender_daemon()
{ {
@ -69,10 +75,8 @@ class Launcher extends AbstractDaemon
exec('php '.PWD.'/console.php controllers/internals/Console.php sender > /dev/null 2>&1 &'); exec('php '.PWD.'/console.php controllers/internals/Console.php sender > /dev/null 2>&1 &');
} }
/** /**
* Function to start webhook daemon * Function to start webhook daemon.
* @return void
*/ */
public function start_webhook_daemon() public function start_webhook_daemon()
{ {
@ -88,11 +92,10 @@ class Launcher extends AbstractDaemon
exec('php '.PWD.'/console.php controllers/internals/Console.php webhook > /dev/null 2>&1 &'); exec('php '.PWD.'/console.php controllers/internals/Console.php webhook > /dev/null 2>&1 &');
} }
/** /**
* Function to start phones daemons * Function to start phones daemons.
*
* @param array $phones : Phones to start daemon for if the daemon is not already started * @param array $phones : Phones to start daemon for if the daemon is not already started
* @return void
*/ */
public function start_phones_daemons(array $phones) public function start_phones_daemons(array $phones)
{ {
@ -111,21 +114,18 @@ class Launcher extends AbstractDaemon
} }
} }
public function on_start() public function on_start()
{ {
$this->logger->info("Starting Launcher with pid " . getmypid()); $this->logger->info('Starting Launcher with pid '.getmypid());
} }
public function on_stop() public function on_stop()
{ {
$this->logger->info("Stopping Launcher with pid " . getmypid ()); $this->logger->info('Stopping Launcher with pid '.getmypid());
} }
public function handle_other_signals($signal) public function handle_other_signals($signal)
{ {
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal); $this->logger->info('Signal not handled by '.$this->name.' Daemon : '.$signal);
} }
} }

View File

@ -1,11 +1,21 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace daemons; namespace daemons;
use \Monolog\Logger; use Monolog\Handler\StreamHandler;
use \Monolog\Handler\StreamHandler; use Monolog\Logger;
/** /**
* Phone daemon class * Phone daemon class.
*/ */
class Phone extends AbstractDaemon class Phone extends AbstractDaemon
{ {
@ -18,7 +28,8 @@ class Phone extends AbstractDaemon
private $bdd; private $bdd;
/** /**
* Constructor * Constructor.
*
* @param array $phone : A phone table entry * @param array $phone : A phone table entry
*/ */
public function __construct(array $phone) public function __construct(array $phone)
@ -40,7 +51,6 @@ class Phone extends AbstractDaemon
parent::start(); parent::start();
} }
public function run() public function run()
{ {
//Stop after 5 minutes of inactivity to avoid useless daemon //Stop after 5 minutes of inactivity to avoid useless daemon
@ -61,9 +71,37 @@ class Phone extends AbstractDaemon
usleep(0.5 * 1000000); usleep(0.5 * 1000000);
} }
public function on_start()
{
//Set last message at to construct time
$this->last_message_at = microtime(true);
$this->msg_queue = msg_get_queue($this->msg_queue_id);
$this->webhook_queue = msg_get_queue(QUEUE_ID_WEBHOOK);
//Instanciate adapter
$adapter_class = $this->phone['adapter'];
$this->adapter = new $adapter_class($this->phone['number'], $this->phone['adapter_datas']);
$this->logger->info('Starting Phone daemon with pid '.getmypid());
}
public function on_stop()
{
//Delete queue on daemon close
$this->logger->info('Closing queue : '.$this->msg_queue_id);
msg_remove_queue($this->msg_queue);
$this->logger->info('Stopping Phone daemon with pid '.getmypid());
}
public function handle_other_signals($signal)
{
$this->logger->info('Signal not handled by '.$this->name.' Daemon : '.$signal);
}
/** /**
* Send sms * Send sms.
*/ */
private function send_smss() private function send_smss()
{ {
@ -76,17 +114,19 @@ class Phone extends AbstractDaemon
$message = null; $message = null;
$error_code = null; $error_code = null;
$success = msg_receive($this->msg_queue, QUEUE_TYPE_SEND_MSG, $msgtype, $maxsize, $message, TRUE, MSG_IPC_NOWAIT, $error_code); //MSG_IPC_NOWAIT == dont wait if no message found $success = msg_receive($this->msg_queue, QUEUE_TYPE_SEND_MSG, $msgtype, $maxsize, $message, true, MSG_IPC_NOWAIT, $error_code); //MSG_IPC_NOWAIT == dont wait if no message found
if (!$success && $error_code !== MSG_ENOMSG) if (!$success && MSG_ENOMSG !== $error_code)
{ {
$this->logger->critical('Error reading MSG SEND Queue, error code : '.$error); $this->logger->critical('Error reading MSG SEND Queue, error code : '.$error);
return false; return false;
} }
if (!$message) if (!$message)
{ {
$find_message = false; $find_message = false;
continue; continue;
} }
@ -107,6 +147,7 @@ class Phone extends AbstractDaemon
{ {
$this->logger->error('Failed send message : '.json_encode($message)); $this->logger->error('Failed send message : '.json_encode($message));
$internal_sended->create($at, $message['text'], $message['origin'], $message['destination'], $sended_sms_uid, $this->phone['adapter'], $message['flash'], 'failed'); $internal_sended->create($at, $message['text'], $message['origin'], $message['destination'], $sended_sms_uid, $this->phone['adapter'], $message['flash'], 'failed');
continue; continue;
} }
@ -121,9 +162,8 @@ class Phone extends AbstractDaemon
} }
} }
/** /**
* Read smss for a number * Read smss for a number.
*/ */
private function read_smss() private function read_smss()
{ {
@ -157,10 +197,11 @@ class Phone extends AbstractDaemon
} }
} }
/** /**
* Process a sms to find if its a command and so execute it * Process a sms to find if its a command and so execute it.
*
* @param array $sms : The sms * @param array $sms : The sms
*
* @return array : ['text' => new sms text, 'is_command' => bool] * @return array : ['text' => new sms text, 'is_command' => bool]
*/ */
private function process_for_command(array $sms) private function process_for_command(array $sms)
@ -179,9 +220,9 @@ class Phone extends AbstractDaemon
return ['text' => $sms['text'], 'is_command' => $is_command]; return ['text' => $sms['text'], 'is_command' => $is_command];
} }
/** /**
* Process a sms to transmit a webhook query to webhook daemon if needed * Process a sms to transmit a webhook query to webhook daemon if needed.
*
* @param array $sms : The sms * @param array $sms : The sms
* @param string $webhook_type : Type of webhook to trigger * @param string $webhook_type : Type of webhook to trigger
* @param array $user_settings : Use settings * @param array $user_settings : Use settings
@ -210,17 +251,17 @@ class Phone extends AbstractDaemon
]; ];
$error_code = null; $error_code = null;
$success = msg_send($this->webhook_queue, QUEUE_TYPE_WEBHOOK, $message, TRUE, TRUE, $error_code); $success = msg_send($this->webhook_queue, QUEUE_TYPE_WEBHOOK, $message, true, true, $error_code);
if (!$success) if (!$success)
{ {
$this->logger->critical("Failed send webhook message in queue, error code : " . $error_code); $this->logger->critical('Failed send webhook message in queue, error code : '.$error_code);
} }
} }
} }
/** /**
* Process a sms to transfer it by mail * Process a sms to transfer it by mail.
*
* @param array $sms : The sms * @param array $sms : The sms
* @param array $user_settings : Use settings * @param array $user_settings : Use settings
*/ */
@ -243,36 +284,4 @@ class Phone extends AbstractDaemon
\controllers\internals\Tool::send_email($user['email'], EMAIL_TRANSFER_SMS, ['sms' => $sms]); \controllers\internals\Tool::send_email($user['email'], EMAIL_TRANSFER_SMS, ['sms' => $sms]);
} }
public function on_start()
{
//Set last message at to construct time
$this->last_message_at = microtime(true);
$this->msg_queue = msg_get_queue($this->msg_queue_id);
$this->webhook_queue = msg_get_queue(QUEUE_ID_WEBHOOK);
//Instanciate adapter
$adapter_class = $this->phone['adapter'];
$this->adapter = new $adapter_class($this->phone['number'], $this->phone['adapter_datas']);
$this->logger->info("Starting Phone daemon with pid " . getmypid());
}
public function on_stop()
{
//Delete queue on daemon close
$this->logger->info("Closing queue : " . $this->msg_queue_id);
msg_remove_queue($this->msg_queue);
$this->logger->info("Stopping Phone daemon with pid " . getmypid ());
}
public function handle_other_signals($signal)
{
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal);
}
} }

View File

@ -1,11 +1,21 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace daemons; namespace daemons;
use \Monolog\Logger; use Monolog\Handler\StreamHandler;
use \Monolog\Handler\StreamHandler; use Monolog\Logger;
/** /**
* Main daemon class * Main daemon class.
*/ */
class Sender extends AbstractDaemon class Sender extends AbstractDaemon
{ {
@ -17,7 +27,7 @@ class Sender extends AbstractDaemon
public function __construct() public function __construct()
{ {
$name = "RaspiSMS Daemon Sender"; $name = 'RaspiSMS Daemon Sender';
$logger = new Logger($name); $logger = new Logger($name);
$logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG)); $logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG));
$pid_dir = PWD_PID; $pid_dir = PWD_PID;
@ -31,7 +41,6 @@ class Sender extends AbstractDaemon
parent::start(); parent::start();
} }
public function run() public function run()
{ {
//Create the internal controllers //Create the internal controllers
@ -44,9 +53,9 @@ class Sender extends AbstractDaemon
usleep(0.5 * 1000000); usleep(0.5 * 1000000);
} }
/** /**
* Function to get messages to send and transfer theme to phones daemons * Function to get messages to send and transfer theme to phones daemons.
*
* @param array $smss : Smss to send * @param array $smss : Smss to send
*/ */
public function transmit_smss(array $smss): void public function transmit_smss(array $smss): void
@ -75,29 +84,26 @@ class Sender extends AbstractDaemon
} }
} }
public function on_start() public function on_start()
{ {
$this->logger->info("Starting Sender with pid " . getmypid()); $this->logger->info('Starting Sender with pid '.getmypid());
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8'); $this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
} }
public function on_stop() public function on_stop()
{ {
$this->logger->info("Stopping Sender with pid " . getmypid ()); $this->logger->info('Stopping Sender with pid '.getmypid());
//Delete queues on daemon close //Delete queues on daemon close
foreach ($this->queues as $queue_id => $queue) foreach ($this->queues as $queue_id => $queue)
{ {
$this->logger->info("Closing queue : " . $queue_id); $this->logger->info('Closing queue : '.$queue_id);
msg_remove_queue($queue); msg_remove_queue($queue);
} }
} }
public function handle_other_signals($signal) public function handle_other_signals($signal)
{ {
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal); $this->logger->info('Signal not handled by '.$this->name.' Daemon : '.$signal);
} }
} }

View File

@ -1,11 +1,21 @@
<?php <?php
/*
* This file is part of RaspiSMS.
*
* (c) Pierre-Lin Bonnemaison <plebwebsas@gmail.com>
*
* This source file is subject to the GPL-3.0 license that is bundled
* with this source code in the file LICENSE.
*/
namespace daemons; namespace daemons;
use \Monolog\Logger; use Monolog\Handler\StreamHandler;
use \Monolog\Handler\StreamHandler; use Monolog\Logger;
/** /**
* Phone daemon class * Phone daemon class.
*/ */
class Webhook extends AbstractDaemon class Webhook extends AbstractDaemon
{ {
@ -16,12 +26,13 @@ class Webhook extends AbstractDaemon
private $bdd; private $bdd;
/** /**
* Constructor * Constructor.
*
* @param array $phone : A phone table entry * @param array $phone : A phone table entry
*/ */
public function __construct() public function __construct()
{ {
$name = "RaspiSMS Daemon Webhook"; $name = 'RaspiSMS Daemon Webhook';
$logger = new Logger($name); $logger = new Logger($name);
$logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG)); $logger->pushHandler(new StreamHandler(PWD_LOGS.'/raspisms.log', Logger::DEBUG));
$pid_dir = PWD_PID; $pid_dir = PWD_PID;
@ -35,7 +46,6 @@ class Webhook extends AbstractDaemon
parent::start(); parent::start();
} }
public function run() public function run()
{ {
$find_message = true; $find_message = true;
@ -56,6 +66,7 @@ class Webhook extends AbstractDaemon
if (!$message) if (!$message)
{ {
$find_message = false; $find_message = false;
continue; continue;
} }
@ -74,7 +85,6 @@ class Webhook extends AbstractDaemon
usleep(0.5 * 1000000); usleep(0.5 * 1000000);
} }
public function on_start() public function on_start()
{ {
//Set last message at to construct time //Set last message at to construct time
@ -82,22 +92,20 @@ class Webhook extends AbstractDaemon
$this->webhook_queue = msg_get_queue(QUEUE_ID_WEBHOOK); $this->webhook_queue = msg_get_queue(QUEUE_ID_WEBHOOK);
$this->logger->info("Starting Webhook daemon with pid " . getmypid()); $this->logger->info('Starting Webhook daemon with pid '.getmypid());
} }
public function on_stop() public function on_stop()
{ {
//Delete queue on daemon close //Delete queue on daemon close
$this->logger->info("Closing queue : " . QUEUE_ID_WEBHOOK); $this->logger->info('Closing queue : '.QUEUE_ID_WEBHOOK);
msg_remove_queue($this->webhook_queue); msg_remove_queue($this->webhook_queue);
$this->logger->info("Stopping Webhook daemon with pid " . getmypid ()); $this->logger->info('Stopping Webhook daemon with pid '.getmypid());
} }
public function handle_other_signals($signal) public function handle_other_signals($signal)
{ {
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal); $this->logger->info('Signal not handled by '.$this->name.' Daemon : '.$signal);
} }
} }

View File

@ -14,8 +14,12 @@ namespace models;
class Command extends StandardModel class Command extends StandardModel
{ {
/** /**
* Return table name * Return table name.
*
* @return string * @return string
*/ */
protected function get_table_name() : string { return 'command'; } protected function get_table_name(): string
{
return 'command';
}
} }

View File

@ -14,20 +14,25 @@ namespace models;
class ConditionalGroup extends StandardModel class ConditionalGroup extends StandardModel
{ {
/** /**
* Return table name * Return a conditional group by his name for a user.
* @return string *
*/
protected function get_table_name() : string { return 'conditional_group'; }
/**
* Return a conditional group by his name for a user
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Group name * @param string $name : Group name
*
* @return array * @return array
*/ */
public function get_by_name_for_user(int $id_user, string $name) public function get_by_name_for_user(int $id_user, string $name)
{ {
return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]); return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'conditional_group';
}
} }

View File

@ -14,16 +14,11 @@ namespace models;
class Contact extends StandardModel class Contact extends StandardModel
{ {
/** /**
* Return table name * Return a contact by his number for a user.
* @return string *
*/
protected function get_table_name() : string { return 'contact'; }
/**
* Return a contact by his number for a user
* @param int $id_user : User id * @param int $id_user : User id
* @param string $number : Contact number * @param string $number : Contact number
*
* @return array * @return array
*/ */
public function get_by_number_and_user(int $id_user, string $number) public function get_by_number_and_user(int $id_user, string $number)
@ -31,15 +26,26 @@ namespace models;
return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'number' => $number]); return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'number' => $number]);
} }
/** /**
* Return a contact by his name for a user * Return a contact by his name for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Contact name * @param string $name : Contact name
*
* @return array * @return array
*/ */
public function get_by_name_and_user(int $id_user, string $name) public function get_by_name_and_user(int $id_user, string $name)
{ {
return $this->_select($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]); return $this->_select($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'contact';
}
} }

View File

@ -14,20 +14,25 @@ namespace models;
class Event extends StandardModel class Event extends StandardModel
{ {
/** /**
* Return table name * Gets lasts x events for a user order by date.
* @return string *
*/
protected function get_table_name() : string { return 'event'; }
/**
* Gets lasts x events for a user order by date
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of events to return * @param int $nb_entry : Number of events to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user(int $id_user, int $nb_entry) public function get_lasts_by_date_for_user(int $id_user, int $nb_entry)
{ {
return $this->_select('event', ['id_user' => $id_user], 'at', true, $nb_entry); return $this->_select('event', ['id_user' => $id_user], 'at', true, $nb_entry);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'event';
}
} }

View File

@ -14,16 +14,11 @@ namespace models;
class Group extends StandardModel class Group extends StandardModel
{ {
/** /**
* Return table name * Return a group by his name for a user.
* @return string *
*/
protected function get_table_name() : string { return 'group'; }
/**
* Return a group by his name for a user
* @param int $id_user : User id * @param int $id_user : User id
* @param string $name : Group name * @param string $name : Group name
*
* @return array * @return array
*/ */
public function get_by_name_for_user(int $id_user, string $name) public function get_by_name_for_user(int $id_user, string $name)
@ -31,10 +26,11 @@ namespace models;
return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]); return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'name' => $name]);
} }
/** /**
* Delete relations between group and contacts for a group * Delete relations between group and contacts for a group.
*
* @param int $id_group : Group id * @param int $id_group : Group id
*
* @return int : Number of deleted rows * @return int : Number of deleted rows
*/ */
public function delete_group_contact_relations(int $id_group) public function delete_group_contact_relations(int $id_group)
@ -42,23 +38,26 @@ namespace models;
return $this->_delete('group_contact', ['id_group' => $id_group]); return $this->_delete('group_contact', ['id_group' => $id_group]);
} }
/** /**
* Insert a relation between a group and a contact * Insert a relation between a group and a contact.
*
* @param int $id_group : Group id * @param int $id_group : Group id
* @param int $id_contact : Contact id * @param int $id_contact : Contact id
*
* @return mixed (bool|int) : False on error, new row id else * @return mixed (bool|int) : False on error, new row id else
*/ */
public function insert_group_contact_relation(int $id_group, int $id_contact) public function insert_group_contact_relation(int $id_group, int $id_contact)
{ {
$success = (bool) $this->_insert('group_contact', ['id_group' => $id_group, 'id_contact' => $id_contact]); $success = (bool) $this->_insert('group_contact', ['id_group' => $id_group, 'id_contact' => $id_contact]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Get groups contacts * Get groups contacts.
*
* @param int $id_group : Group id * @param int $id_group : Group id
*
* @return array : Contacts of the group * @return array : Contacts of the group
*/ */
public function get_contacts(int $id_group) public function get_contacts(int $id_group)
@ -73,4 +72,14 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'group';
}
} }

View File

@ -17,16 +17,11 @@ namespace models;
class Media extends StandardModel class Media extends StandardModel
{ {
/** /**
* Return table name * Return an entry by his id for a user.
* @return string *
*/
protected function get_table_name() : string { return 'media'; }
/**
* Return an entry by his id for a user
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id : entry id * @param int $id : entry id
*
* @return array * @return array
*/ */
public function get_for_user(int $id_user, int $id) public function get_for_user(int $id_user, int $id)
@ -43,13 +38,15 @@ namespace models;
]; ];
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? []; return $receiveds[0] ?? [];
} }
/** /**
* Return all entries for a user * Return all entries for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -66,11 +63,12 @@ namespace models;
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
} }
/** /**
* Return a media for a user and a scheduled * Return a media for a user and a scheduled.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id_scheduled : scheduled id * @param int $id_scheduled : scheduled id
*
* @return array * @return array
*/ */
public function get_for_scheduled_and_user(int $id_user, int $id_scheduled) public function get_for_scheduled_and_user(int $id_user, int $id_scheduled)
@ -83,7 +81,7 @@ namespace models;
$params = [ $params = [
'id_user' => $id_user, 'id_user' => $id_user,
'id_scheduled' => $id_scheduled 'id_scheduled' => $id_scheduled,
]; ];
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
@ -95,9 +93,9 @@ namespace models;
return $receiveds[0]; return $receiveds[0];
} }
/** /**
* Return a list of media for a user * Return a list of media for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $limit : Max results to return * @param int $limit : Max results to return
* @param int $offset : Number of results to ignore * @param int $offset : Number of results to ignore
@ -119,11 +117,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return a list of medias in a group of ids and for a user * Return a list of medias in a group of ids and for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param array $ids : ids of medias to find * @param array $ids : ids of medias to find
*
* @return array * @return array
*/ */
public function gets_in_for_user(int $id_user, $ids) public function gets_in_for_user(int $id_user, $ids)
@ -143,9 +142,11 @@ namespace models;
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id) public function delete_for_user(int $id_user, int $id)
@ -161,11 +162,12 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_scheduled_and_user(int $id_user, int $id_scheduled) public function delete_for_scheduled_and_user(int $id_user, int $id_scheduled)
@ -181,9 +183,9 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Update a media sms for a user * Update a media sms for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
* @param array $datas : datas to update * @param array $datas : datas to update
@ -215,10 +217,11 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Count number of media sms for user * Count number of media sms for user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return int : Number of media SMS for user * @return int : Number of media SMS for user
*/ */
public function count_for_user($id_user) public function count_for_user($id_user)
@ -235,4 +238,14 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0; return $this->_run_query($query, $params)[0]['nb'] ?? 0;
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'media';
}
} }

View File

@ -14,16 +14,11 @@ namespace models;
class Phone extends StandardModel class Phone extends StandardModel
{ {
/** /**
* Return table name * Return a phone by his number and user.
* @return string *
*/
protected function get_table_name() : string { return 'phone'; }
/**
* Return a phone by his number and user
* @param int $id_user : user id * @param int $id_user : user id
* @param string $number : phone number * @param string $number : phone number
*
* @return array * @return array
*/ */
public function get_by_number_and_user(int $id_user, string $number) public function get_by_number_and_user(int $id_user, string $number)
@ -31,14 +26,25 @@ namespace models;
return $this->_select_one('phone', ['number' => $number, 'id_user' => $id_user]); return $this->_select_one('phone', ['number' => $number, 'id_user' => $id_user]);
} }
/** /**
* Return a phone by his number * Return a phone by his number.
*
* @param string $number : phone number * @param string $number : phone number
*
* @return array * @return array
*/ */
public function get_by_number(string $number) public function get_by_number(string $number)
{ {
return $this->_select_one('phone', ['number' => $number]); return $this->_select_one('phone', ['number' => $number]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'phone';
}
} }

View File

@ -17,16 +17,11 @@ namespace models;
class Received extends StandardModel class Received extends StandardModel
{ {
/** /**
* Return table name * Return an entry by his id for a user.
* @return string *
*/
protected function get_table_name() : string { return 'received'; }
/**
* Return an entry by his id for a user
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id : entry id * @param int $id : entry id
*
* @return array * @return array
*/ */
public function get_for_user(int $id_user, int $id) public function get_for_user(int $id_user, int $id)
@ -43,13 +38,15 @@ namespace models;
]; ];
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? []; return $receiveds[0] ?? [];
} }
/** /**
* Return all entries for a user * Return all entries for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -66,9 +63,9 @@ namespace models;
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
} }
/** /**
* Return a list of received for a user * Return a list of received for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $limit : Max results to return * @param int $limit : Max results to return
* @param int $offset : Number of results to ignore * @param int $offset : Number of results to ignore
@ -90,9 +87,9 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return a list of unread received for a user * Return a list of unread received for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $limit : Max results to return * @param int $limit : Max results to return
* @param int $offset : Number of results to ignore * @param int $offset : Number of results to ignore
@ -115,11 +112,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return a list of receiveds in a group of ids and for a user * Return a list of receiveds in a group of ids and for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param array $ids : ids of receiveds to find * @param array $ids : ids of receiveds to find
*
* @return array * @return array
*/ */
public function gets_in_for_user(int $id_user, $ids) public function gets_in_for_user(int $id_user, $ids)
@ -139,9 +137,11 @@ namespace models;
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id) public function delete_for_user(int $id_user, int $id)
@ -157,9 +157,9 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Update a received sms for a user * Update a received sms for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
* @param array $datas : datas to update * @param array $datas : datas to update
@ -197,10 +197,11 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Count number of received sms for user * Count number of received sms for user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return int : Number of received SMS for user * @return int : Number of received SMS for user
*/ */
public function count_for_user(int $id_user) public function count_for_user(int $id_user)
@ -218,10 +219,11 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0; return $this->_run_query($query, $params)[0]['nb'] ?? 0;
} }
/** /**
* Count number of unread received sms for user * Count number of unread received sms for user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return int : Number of received SMS for user * @return int : Number of received SMS for user
*/ */
public function count_unread_for_user(int $id_user) public function count_unread_for_user(int $id_user)
@ -240,11 +242,12 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0; return $this->_run_query($query, $params)[0]['nb'] ?? 0;
} }
/** /**
* Return x last receiveds message for a user, order by date * Return x last receiveds message for a user, order by date.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of receiveds messages to return * @param int $nb_entry : Number of receiveds messages to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user(int $id_user, int $nb_entry) public function get_lasts_by_date_for_user(int $id_user, int $nb_entry)
@ -265,11 +268,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return receiveds for an origin and a user * Return receiveds for an origin and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $origin : Number who sent the message * @param string $origin : Number who sent the message
*
* @return array * @return array
*/ */
public function gets_by_origin_and_user(int $id_user, string $origin) public function gets_by_origin_and_user(int $id_user, string $origin)
@ -289,11 +293,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Get number of sended SMS for every date since a date for a specific user * Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages * @param \DateTime $date : Date since which we want the messages
*
* @return array * @return array
*/ */
public function count_by_day_since_for_user(int $id_user, $date) public function count_by_day_since_for_user(int $id_user, $date)
@ -315,8 +320,10 @@ namespace models;
} }
/** /**
* Return all discussions (ie : numbers we have a message received from or sended to) for a user * Return all discussions (ie : numbers we have a message received from or sended to) for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array * @return array
*/ */
public function get_discussions_for_user(int $id_user) public function get_discussions_for_user(int $id_user)
@ -336,13 +343,16 @@ namespace models;
'; ';
$params = ['id_user' => $id_user]; $params = ['id_user' => $id_user];
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Get SMS received since a date for a user * Get SMS received since a date for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05) * @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05)
*
* @return array : Tableau avec tous les SMS depuis la date * @return array : Tableau avec tous les SMS depuis la date
*/ */
public function get_since_by_date_for_user(int $id_user, $date) public function get_since_by_date_for_user(int $id_user, $date)
@ -363,10 +373,12 @@ namespace models;
} }
/** /**
* Find messages received since a date for a certain origin and user * Find messages received since a date for a certain origin and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : Date we want messages sinces * @param $date : Date we want messages sinces
* @param string $origin : Origin number * @param string $origin : Origin number
*
* @return array * @return array
*/ */
public function get_since_by_date_for_origin_and_user(int $id_user, $date, string $origin) public function get_since_by_date_for_origin_and_user(int $id_user, $date, string $origin)
@ -390,21 +402,23 @@ namespace models;
} }
/** /**
* Find destination of last received message for an origin and user * Find destination of last received message for an origin and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $origin : Origin number * @param string $origin : Origin number
*
* @return array * @return array
*/ */
public function get_last_for_origin_and_user(int $id_user, string $origin) public function get_last_for_origin_and_user(int $id_user, string $origin)
{ {
$query = " $query = '
SELECT * SELECT *
FROM received FROM received
WHERE origin = :origin WHERE origin = :origin
AND destination IN (SELECT number FROM phone WHERE id_user = :id_user) AND destination IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at DESC ORDER BY at DESC
LIMIT 0,1 LIMIT 0,1
"; ';
$params = [ $params = [
'origin' => $origin, 'origin' => $origin,
@ -413,6 +427,16 @@ namespace models;
$result = $this->_run_query($query, $params); $result = $this->_run_query($query, $params);
return ($result[0] ?? []); return $result[0] ?? [];
}
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'received';
} }
} }

View File

@ -14,15 +14,10 @@ namespace models;
class Scheduled extends StandardModel class Scheduled extends StandardModel
{ {
/** /**
* Return table name * Return numbers for a scheduled message.
* @return string *
*/
protected function get_table_name() : string { return 'scheduled'; }
/**
* Return numbers for a scheduled message
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_numbers(int $id_scheduled) public function get_numbers(int $id_scheduled)
@ -30,101 +25,116 @@ namespace models;
return $this->_select('scheduled_number', ['id_scheduled' => $id_scheduled]); return $this->_select('scheduled_number', ['id_scheduled' => $id_scheduled]);
} }
/** /**
* Return contacts for a scheduled message * Return contacts for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_contacts(int $id_scheduled) public function get_contacts(int $id_scheduled)
{ {
$query = 'SELECT * FROM contact WHERE id IN (SELECT id_contact FROM scheduled_contact WHERE id_scheduled = :id_scheduled)'; $query = 'SELECT * FROM contact WHERE id IN (SELECT id_contact FROM scheduled_contact WHERE id_scheduled = :id_scheduled)';
$params = ['id_scheduled' => $id_scheduled]; $params = ['id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return groups for a scheduled message * Return groups for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_groups(int $id_scheduled) public function get_groups(int $id_scheduled)
{ {
$query = 'SELECT * FROM `group` WHERE id IN (SELECT id_group FROM scheduled_group WHERE id_scheduled = :id_scheduled)'; $query = 'SELECT * FROM `group` WHERE id IN (SELECT id_group FROM scheduled_group WHERE id_scheduled = :id_scheduled)';
$params = ['id_scheduled' => $id_scheduled]; $params = ['id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return conitional groups for a scheduled message * Return conitional groups for a scheduled message.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return array * @return array
*/ */
public function get_conditional_groups(int $id_scheduled) public function get_conditional_groups(int $id_scheduled)
{ {
$query = 'SELECT * FROM `conditional_group` WHERE id IN (SELECT id_conditional_group FROM scheduled_conditional_group WHERE id_scheduled = :id_scheduled)'; $query = 'SELECT * FROM `conditional_group` WHERE id IN (SELECT id_conditional_group FROM scheduled_conditional_group WHERE id_scheduled = :id_scheduled)';
$params = ['id_scheduled' => $id_scheduled]; $params = ['id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Insert a number for a scheduled * Insert a number for a scheduled.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
* @param string $number : Number * @param string $number : Number
*
* @return mixed (bool|int) : False on error, new row id else * @return mixed (bool|int) : False on error, new row id else
*/ */
public function insert_scheduled_number(int $id_scheduled, string $number) public function insert_scheduled_number(int $id_scheduled, string $number)
{ {
$success = $this->_insert('scheduled_number', ['id_scheduled' => $id_scheduled, 'number' => $number]); $success = $this->_insert('scheduled_number', ['id_scheduled' => $id_scheduled, 'number' => $number]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Insert a relation between a scheduled and a contact * Insert a relation between a scheduled and a contact.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
* @param int $id_contact : Group id * @param int $id_contact : Group id
*
* @return mixed (bool|int) : False on error, new row id else * @return mixed (bool|int) : False on error, new row id else
*/ */
public function insert_scheduled_contact_relation(int $id_scheduled, int $id_contact) public function insert_scheduled_contact_relation(int $id_scheduled, int $id_contact)
{ {
$success = $this->_insert('scheduled_contact', ['id_scheduled' => $id_scheduled, 'id_contact' => $id_contact]); $success = $this->_insert('scheduled_contact', ['id_scheduled' => $id_scheduled, 'id_contact' => $id_contact]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Insert a relation between a scheduled and a group * Insert a relation between a scheduled and a group.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
* @param int $id_group : Group id * @param int $id_group : Group id
*
* @return mixed (bool|int) : False on error, new row id else * @return mixed (bool|int) : False on error, new row id else
*/ */
public function insert_scheduled_group_relation(int $id_scheduled, int $id_group) public function insert_scheduled_group_relation(int $id_scheduled, int $id_group)
{ {
$success = $this->_insert('scheduled_group', ['id_scheduled' => $id_scheduled, 'id_group' => $id_group]); $success = $this->_insert('scheduled_group', ['id_scheduled' => $id_scheduled, 'id_group' => $id_group]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Insert a relation between a scheduled and a conditional group * Insert a relation between a scheduled and a conditional group.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
* @param int $id_conditional_group : Group id * @param int $id_conditional_group : Group id
*
* @return mixed (bool|int) : False on error, new row id else * @return mixed (bool|int) : False on error, new row id else
*/ */
public function insert_scheduled_conditional_group_relation(int $id_scheduled, int $id_conditional_group) public function insert_scheduled_conditional_group_relation(int $id_scheduled, int $id_conditional_group)
{ {
$success = $this->_insert('scheduled_conditional_group', ['id_scheduled' => $id_scheduled, 'id_conditional_group' => $id_conditional_group]); $success = $this->_insert('scheduled_conditional_group', ['id_scheduled' => $id_scheduled, 'id_conditional_group' => $id_conditional_group]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Delete numbers for a scheduled * Delete numbers for a scheduled.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return mixed int : Number of deleted rows * @return mixed int : Number of deleted rows
*/ */
public function delete_scheduled_numbers(int $id_scheduled) public function delete_scheduled_numbers(int $id_scheduled)
@ -132,10 +142,11 @@ namespace models;
return $this->_delete('scheduled_number', ['id_scheduled' => $id_scheduled]); return $this->_delete('scheduled_number', ['id_scheduled' => $id_scheduled]);
} }
/** /**
* Delete contact scheduled relations for a scheduled * Delete contact scheduled relations for a scheduled.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return mixed int : Number of deleted rows * @return mixed int : Number of deleted rows
*/ */
public function delete_scheduled_contact_relations(int $id_scheduled) public function delete_scheduled_contact_relations(int $id_scheduled)
@ -143,10 +154,11 @@ namespace models;
return $this->_delete('scheduled_contact', ['id_scheduled' => $id_scheduled]); return $this->_delete('scheduled_contact', ['id_scheduled' => $id_scheduled]);
} }
/** /**
* Delete group scheduled relations for a scheduled * Delete group scheduled relations for a scheduled.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return mixed int : Number of deleted rows * @return mixed int : Number of deleted rows
*/ */
public function delete_scheduled_group_relations(int $id_scheduled) public function delete_scheduled_group_relations(int $id_scheduled)
@ -154,10 +166,11 @@ namespace models;
return $this->_delete('scheduled_group', ['id_scheduled' => $id_scheduled]); return $this->_delete('scheduled_group', ['id_scheduled' => $id_scheduled]);
} }
/** /**
* Delete conditional group scheduled relations for a scheduled * Delete conditional group scheduled relations for a scheduled.
*
* @param int $id_scheduled : Scheduled id * @param int $id_scheduled : Scheduled id
*
* @return mixed int : Number of deleted rows * @return mixed int : Number of deleted rows
*/ */
public function delete_scheduled_conditional_group_relations(int $id_scheduled) public function delete_scheduled_conditional_group_relations(int $id_scheduled)
@ -165,12 +178,13 @@ namespace models;
return $this->_delete('scheduled_conditional_group', ['id_scheduled' => $id_scheduled]); return $this->_delete('scheduled_conditional_group', ['id_scheduled' => $id_scheduled]);
} }
/** /**
* Get messages scheduled before a date for a number and a user * Get messages scheduled before a date for a number and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param $date : Date before which we want messages * @param $date : Date before which we want messages
* @param string $number : Number for which we want messages * @param string $number : Number for which we want messages
*
* @return array * @return array
*/ */
public function gets_before_date_for_number_and_user(int $id_user, $date, string $number) public function gets_before_date_for_number_and_user(int $id_user, $date, string $number)
@ -220,14 +234,25 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Get scheduleds before a date * Get scheduleds before a date.
*
* @param string $date : Date to get scheduleds before * @param string $date : Date to get scheduleds before
*
* @return array * @return array
*/ */
public function gets_before_date(string $date) public function gets_before_date(string $date)
{ {
return $this->_select($this->get_table_name(), ['<=at' => $date]); return $this->_select($this->get_table_name(), ['<=at' => $date]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'scheduled';
}
} }

View File

@ -17,16 +17,11 @@ namespace models;
class Sended extends StandardModel class Sended extends StandardModel
{ {
/** /**
* Return table name * Return an entry by his id for a user.
* @return string *
*/
protected function get_table_name() : string { return 'sended'; }
/**
* Return an entry by his id for a user
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id : entry id * @param int $id : entry id
*
* @return array * @return array
*/ */
public function get_for_user(int $id_user, int $id) public function get_for_user(int $id_user, int $id)
@ -43,13 +38,15 @@ namespace models;
]; ];
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? []; return $receiveds[0] ?? [];
} }
/** /**
* Return all entries for a user * Return all entries for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -66,9 +63,9 @@ namespace models;
$receiveds = $this->_run_query($query, $params); $receiveds = $this->_run_query($query, $params);
} }
/** /**
* Return a list of sended for a user * Return a list of sended for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $limit : Max results to return * @param int $limit : Max results to return
* @param int $offset : Number of results to ignore * @param int $offset : Number of results to ignore
@ -90,11 +87,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return a list of sendeds in a group of ids and for a user * Return a list of sendeds in a group of ids and for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param array $ids : ids of sendeds to find * @param array $ids : ids of sendeds to find
*
* @return array * @return array
*/ */
public function gets_in_for_user(int $id_user, $ids) public function gets_in_for_user(int $id_user, $ids)
@ -114,9 +112,11 @@ namespace models;
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id) public function delete_for_user(int $id_user, int $id)
@ -132,9 +132,9 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Update a sended sms for a user * Update a sended sms for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
* @param array $datas : datas to update * @param array $datas : datas to update
@ -172,10 +172,11 @@ namespace models;
return $this->_run_query($query, $params, self::ROWCOUNT); return $this->_run_query($query, $params, self::ROWCOUNT);
} }
/** /**
* Count number of sended sms for user * Count number of sended sms for user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return int : Number of sended SMS for user * @return int : Number of sended SMS for user
*/ */
public function count_for_user($id_user) public function count_for_user($id_user)
@ -193,11 +194,12 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0; return $this->_run_query($query, $params)[0]['nb'] ?? 0;
} }
/** /**
* Return x last sendeds message for a user, order by date * Return x last sendeds message for a user, order by date.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $nb_entry : Number of sendeds messages to return * @param int $nb_entry : Number of sendeds messages to return
*
* @return array * @return array
*/ */
public function get_lasts_by_date_for_user($id_user, $nb_entry) public function get_lasts_by_date_for_user($id_user, $nb_entry)
@ -218,11 +220,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return sendeds for an destination and a user * Return sendeds for an destination and a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $destination : Number who sent the message * @param string $destination : Number who sent the message
*
* @return array * @return array
*/ */
public function gets_by_destination_and_user(int $id_user, string $destination) public function gets_by_destination_and_user(int $id_user, string $destination)
@ -242,11 +245,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Return sended for an uid and an adapter * Return sended for an uid and an adapter.
*
* @param string $uid : Uid of the sended * @param string $uid : Uid of the sended
* @param string $adapter : Adapter used to send the message * @param string $adapter : Adapter used to send the message
*
* @return array * @return array
*/ */
public function get_by_uid_and_adapter(string $uid, string $adapter) public function get_by_uid_and_adapter(string $uid, string $adapter)
@ -255,9 +259,11 @@ namespace models;
} }
/** /**
* Get number of sended SMS for every date since a date for a specific user * Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages * @param \DateTime $date : Date since which we want the messages
*
* @return array * @return array
*/ */
public function count_by_day_since_for_user($id_user, $date) public function count_by_day_since_for_user($id_user, $date)
@ -279,9 +285,11 @@ namespace models;
} }
/** /**
* Get SMS sended since a date for a user * Get SMS sended since a date for a user.
*
* @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05) * @param $date : La date depuis laquelle on veux les SMS (au format 2014-10-25 20:10:05)
* @param int $id_user : User id * @param int $id_user : User id
*
* @return array : Tableau avec tous les SMS depuis la date * @return array : Tableau avec tous les SMS depuis la date
*/ */
public function get_since_by_date_for_user($date, $id_user) public function get_since_by_date_for_user($date, $id_user)
@ -301,23 +309,24 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Find last sended message for a destination and user * Find last sended message for a destination and user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param string $destination : Destination number * @param string $destination : Destination number
*
* @return array * @return array
*/ */
public function get_last_for_destination_and_user(int $id_user, string $destination) public function get_last_for_destination_and_user(int $id_user, string $destination)
{ {
$query = " $query = '
SELECT * SELECT *
FROM sended FROM sended
WHERE destination = :destination WHERE destination = :destination
AND origin IN (SELECT number FROM phone WHERE id_user = :id_user) AND origin IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at DESC ORDER BY at DESC
LIMIT 0,1 LIMIT 0,1
"; ';
$params = [ $params = [
'destination' => $destination, 'destination' => $destination,
@ -326,7 +335,16 @@ namespace models;
$result = $this->_run_query($query, $params); $result = $this->_run_query($query, $params);
return ($result[0] ?? []); return $result[0] ?? [];
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'sended';
}
} }

View File

@ -14,21 +14,26 @@ namespace models;
class Setting extends StandardModel class Setting extends StandardModel
{ {
/** /**
* Return table name * Update a setting for a user by his name.
* @return string *
*/
protected function get_table_name() : string { return 'setting'; }
/**
* Update a setting for a user by his name
* @param int $id_user : user id * @param int $id_user : user id
* @param string $name : setting name * @param string $name : setting name
* @param mixed $value : new value of the setting * @param mixed $value : new value of the setting
*
* @return int : number of modified settings * @return int : number of modified settings
*/ */
public function update_by_name_for_user(int $id_user, string $name, $value) public function update_by_name_for_user(int $id_user, string $name, $value)
{ {
return $this->_update($this->get_table_name(), ['value' => $value], ['id_user' => $id_user, 'name' => $name]); return $this->_update($this->get_table_name(), ['value' => $value], ['id_user' => $id_user, 'name' => $name]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'setting';
}
} }

View File

@ -14,20 +14,25 @@ namespace models;
class SmsStop extends StandardModel class SmsStop extends StandardModel
{ {
/** /**
* Return table name * Return a smsstop by his number and user.
* @return string *
*/
protected function get_table_name() : string { return 'smsstop'; }
/**
* Return a smsstop by his number and user
* @param int $id_user : user id * @param int $id_user : user id
* @param string $number : phone number * @param string $number : phone number
*
* @return array * @return array
*/ */
public function get_by_number_for_user(int $id_user, string $number) public function get_by_number_for_user(int $id_user, string $number)
{ {
return $this->_select_one($this->get_table_name(), ['number' => $number, 'id_user' => $id_user]); return $this->_select_one($this->get_table_name(), ['number' => $number, 'id_user' => $id_user]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'smsstop';
}
} }

View File

@ -13,18 +13,13 @@ namespace models;
/** /**
* Abstract class reprensenting the Standard Model * Abstract class reprensenting the Standard Model
* This class implement/define most common methods for models * This class implement/define most common methods for models.
*/ */
abstract class StandardModel extends \descartes\Model abstract class StandardModel extends \descartes\Model
{ {
/** /**
* Return table name * Return all the entries.
* @return string *
*/
abstract protected function get_table_name() : string;
/**
* Return all the entries
* @return array * @return array
*/ */
public function get_all() public function get_all()
@ -32,10 +27,11 @@ namespace models;
return $this->_select($this->get_table_name()); return $this->_select($this->get_table_name());
} }
/** /**
* Return an entry by his id * Return an entry by his id.
*
* @param int $id : entry id * @param int $id : entry id
*
* @return array * @return array
*/ */
public function get(int $id) public function get(int $id)
@ -43,11 +39,12 @@ namespace models;
return $this->_select_one($this->get_table_name(), ['id' => $id]); return $this->_select_one($this->get_table_name(), ['id' => $id]);
} }
/** /**
* Return an entry by his id for a user * Return an entry by his id for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $id : entry id * @param int $id : entry id
*
* @return array * @return array
*/ */
public function get_for_user(int $id_user, int $id) public function get_for_user(int $id_user, int $id)
@ -55,10 +52,11 @@ namespace models;
return $this->_select_one($this->get_table_name(), ['id' => $id, 'id_user' => $id_user]); return $this->_select_one($this->get_table_name(), ['id' => $id, 'id_user' => $id_user]);
} }
/** /**
* Return all entries for a user * Return all entries for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
*
* @return array * @return array
*/ */
public function gets_for_user(int $id_user) public function gets_for_user(int $id_user)
@ -66,12 +64,13 @@ namespace models;
return $this->_select($this->get_table_name(), ['id_user' => $id_user]); return $this->_select($this->get_table_name(), ['id_user' => $id_user]);
} }
/** /**
* Return a list of entries for a user * Return a list of entries for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param int $limit : Number of entry to return * @param int $limit : Number of entry to return
* @param int $offset : Number of entry to ignore * @param int $offset : Number of entry to ignore
*
* @return array * @return array
*/ */
public function list_for_user(int $id_user, $limit, $offset) public function list_for_user(int $id_user, $limit, $offset)
@ -79,11 +78,12 @@ namespace models;
return $this->_select($this->get_table_name(), ['id_user' => $id_user], null, false, $limit, $offset); return $this->_select($this->get_table_name(), ['id_user' => $id_user], null, false, $limit, $offset);
} }
/** /**
* Return a list of entries in a group of ids and for a user * Return a list of entries in a group of ids and for a user.
*
* @param int $id_user : user id * @param int $id_user : user id
* @param array $ids : ids of entries to find * @param array $ids : ids of entries to find
*
* @return array * @return array
*/ */
public function gets_in_for_user(int $id_user, $ids) public function gets_in_for_user(int $id_user, $ids)
@ -110,11 +110,12 @@ namespace models;
return $this->_run_query($query, $params); return $this->_run_query($query, $params);
} }
/** /**
* Delete a entry by his id for a user * Delete a entry by his id for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete_for_user(int $id_user, int $id) public function delete_for_user(int $id_user, int $id)
@ -122,10 +123,11 @@ namespace models;
return $this->_delete($this->get_table_name(), ['id_user' => $id_user, 'id' => $id]); return $this->_delete($this->get_table_name(), ['id_user' => $id_user, 'id' => $id]);
} }
/** /**
* Delete a entry by his id * Delete a entry by his id.
*
* @param int $id : Entry id * @param int $id : Entry id
*
* @return int : Number of removed rows * @return int : Number of removed rows
*/ */
public function delete(int $id) public function delete(int $id)
@ -133,21 +135,23 @@ namespace models;
return $this->_delete($this->get_table_name(), ['id' => $id]); return $this->_delete($this->get_table_name(), ['id' => $id]);
} }
/** /**
* Insert a entry * Insert a entry.
*
* @param array $entry : Entry to insert * @param array $entry : Entry to insert
*
* @return mixed bool|int : false on error, new entry id else * @return mixed bool|int : false on error, new entry id else
*/ */
public function insert($entry) public function insert($entry)
{ {
$result = $this->_insert($this->get_table_name(), $entry); $result = $this->_insert($this->get_table_name(), $entry);
return ($result ? $this->_last_id() : false);
return $result ? $this->_last_id() : false;
} }
/** /**
* Update a entry for a user * Update a entry for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
* @param int $id : Entry id * @param int $id : Entry id
* @param array $datas : datas to update * @param array $datas : datas to update
@ -159,9 +163,9 @@ namespace models;
return $this->_update($this->get_table_name(), $entry, ['id_user' => $id_user, 'id' => $id]); return $this->_update($this->get_table_name(), $entry, ['id_user' => $id_user, 'id' => $id]);
} }
/** /**
* Update a entry by his id * Update a entry by his id.
*
* @param int $id : Entry id * @param int $id : Entry id
* @param array $datas : datas to update * @param array $datas : datas to update
* *
@ -172,14 +176,22 @@ namespace models;
return $this->_update($this->get_table_name(), $entry, ['id' => $id]); return $this->_update($this->get_table_name(), $entry, ['id' => $id]);
} }
/** /**
* Count number of entry for a user * Count number of entry for a user.
*
* @param int $id_user : User id * @param int $id_user : User id
*
* @return int : number of entries * @return int : number of entries
*/ */
public function count_for_user(int $id_user) public function count_for_user(int $id_user)
{ {
return $this->_count($this->get_table_name(), ['id_user' => $id_user]); return $this->_count($this->get_table_name(), ['id_user' => $id_user]);
} }
/**
* Return table name.
*
* @return string
*/
abstract protected function get_table_name(): string;
} }

View File

@ -12,13 +12,15 @@
namespace models; namespace models;
/** /**
* Class for user table administration. Not a standard model because has absolutly no user based restrictions * Class for user table administration. Not a standard model because has absolutly no user based restrictions.
*/ */
class User extends \descartes\Model class User extends \descartes\Model
{ {
/** /**
* Find a user by his id * Find a user by his id.
*
* @param string $id : User id * @param string $id : User id
*
* @return mixed array * @return mixed array
*/ */
public function get($id) public function get($id)
@ -26,10 +28,11 @@ namespace models;
return $this->_select_one('user', ['id' => $id]); return $this->_select_one('user', ['id' => $id]);
} }
/** /**
* Find a user using his email * Find a user using his email.
*
* @param string $email : User email * @param string $email : User email
*
* @return mixed array * @return mixed array
*/ */
public function get_by_email($email) public function get_by_email($email)
@ -37,9 +40,9 @@ namespace models;
return $this->_select_one('user', ['email' => $email]); return $this->_select_one('user', ['email' => $email]);
} }
/** /**
* Get a user by his api_key address * Get a user by his api_key address.
*
* @param string $api_key : User api key * @param string $api_key : User api key
* *
* @return mixed boolean | array : false if cannot find user for this api key, the user else * @return mixed boolean | array : false if cannot find user for this api key, the user else
@ -49,7 +52,6 @@ namespace models;
return $this->_select_one('user', ['api_key' => $api_key]); return $this->_select_one('user', ['api_key' => $api_key]);
} }
/** /**
* Return list of user. * Return list of user.
* *
@ -61,7 +63,6 @@ namespace models;
return $this->_select('user', [], null, false, $limit, $offset); return $this->_select('user', [], null, false, $limit, $offset);
} }
/** /**
* Retourne une liste de useres sous forme d'un tableau. * Retourne une liste de useres sous forme d'un tableau.
* *
@ -75,23 +76,26 @@ namespace models;
return $this->_delete('user', ['id' => $id]); return $this->_delete('user', ['id' => $id]);
} }
/** /**
* Insert a new user * Insert a new user.
*
* @param array $user : User to insert * @param array $user : User to insert
*
* @return mixed bool|int : false if fail, new user id else * @return mixed bool|int : false if fail, new user id else
*/ */
public function insert($user) public function insert($user)
{ {
$success = $this->_insert('user', $user); $success = $this->_insert('user', $user);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
} }
/** /**
* Update a user using his is * Update a user using his is.
*
* @param int $id : User id * @param int $id : User id
* @param array $datas : Datas to update * @param array $datas : Datas to update
*
* @return int : number of modified rows * @return int : number of modified rows
*/ */
public function update($id, $datas) public function update($id, $datas)
@ -99,11 +103,12 @@ namespace models;
return $this->_update('user', $datas, ['id' => $id]); return $this->_update('user', $datas, ['id' => $id]);
} }
/** /**
* Update a user password by his id. * Update a user password by his id.
*
* @param int $id : User id * @param int $id : User id
* @param array $password : The new password of the user * @param array $password : The new password of the user
*
* @return int : Number of modified lines * @return int : Number of modified lines
*/ */
public function update_password($id, $password) public function update_password($id, $password)
@ -111,11 +116,12 @@ namespace models;
return $this->_update('user', ['password' => $password], ['id' => $id]); return $this->_update('user', ['password' => $password], ['id' => $id]);
} }
/** /**
* Update a user email by his id. * Update a user email by his id.
*
* @param int $id : User id * @param int $id : User id
* @param array $email : The new email * @param array $email : The new email
*
* @return int : Number of modified lines * @return int : Number of modified lines
*/ */
public function update_email($id, $email) public function update_email($id, $email)

View File

@ -14,20 +14,25 @@ namespace models;
class Webhook extends StandardModel class Webhook extends StandardModel
{ {
/** /**
* Return table name * Find all webhooks for a user and for a type of webhook.
* @return string *
*/
protected function get_table_name() : string { return 'webhook'; }
/**
* Find all webhooks for a user and for a type of webhook
* @param int $id_user : User id * @param int $id_user : User id
* @param string $type : Webhook type * @param string $type : Webhook type
*
* @return array * @return array
*/ */
public function gets_for_type_and_user(int $id_user, string $type) public function gets_for_type_and_user(int $id_user, string $type)
{ {
return $this->_select($this->get_table_name(), ['id_user' => $id_user, 'type' => $type]); return $this->_select($this->get_table_name(), ['id_user' => $id_user, 'type' => $type]);
} }
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'webhook';
}
} }

View File

@ -15,11 +15,15 @@
$lint_commands = [ $lint_commands = [
'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../controllers/', 'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../controllers/',
'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../models/', 'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../models/',
'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../daemons/',
'php ' . __DIR__ . '/php-cs-fixer.phar -v --dry-run --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../adapters/',
]; ];
$fix_commands = [ $fix_commands = [
'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../controllers/', 'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../controllers/',
'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../models/', 'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../models/',
'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../daemons/',
'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../adapters/',
]; ];