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,5 +1,15 @@
<?php
namespace adapters;
/*
* 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;
/**
* Interface for phones adapters
@ -11,80 +21,82 @@
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 static function meta_classname() : string;
public function __construct(string $number, string $datas);
/**
* Classname of the adapter.
*/
public static function meta_classname(): string;
/**
* 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;
/**
* Description of the adapter.
* A short description of the service the adapter implements.
*/
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
*/
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;
/**
* Does the implemented service support status change
*/
public static function meta_support_status_change() : bool;
public static function meta_support_flash(): bool;
/**
* 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
* Does the implemented service support status change.
*/
public function __construct (string $number, string $datas);
public static function meta_support_status_change(): bool;
/**
* 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 $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @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
*/
public function read () : array;
public function read(): array;
/**
* Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid
* @return boolean : False on error, true else
* should be use for exemple to verify that credentials and number are both valid.
*
* @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')]
*/
public static function status_change_callback ();
public static function status_change_callback();
}

View File

@ -1,5 +1,15 @@
<?php
namespace adapters;
/*
* 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;
/**
* Interface for phones adapters
@ -11,32 +21,67 @@
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.
* 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.
* 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
*/
public static function meta_datas_fields() : array
public static function meta_datas_fields(): array
{
return [
[
@ -55,53 +100,37 @@
}
/**
* Does the implemented service support flash smss
* Does the implemented service support flash smss.
*/
public static function meta_support_flash() : bool { return false ; }
/**
* 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)
public static function meta_support_flash(): bool
{
$this->number = $number;
$this->datas = json_decode($datas, true);
return false;
}
/**
* Method called to send a SMS to a number
* 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.
*
* @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @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)
{
if (!$this->unlock_sim())
{
return false;
}
$command_parts = [
'gammu',
'--config',
@ -123,7 +152,7 @@
}
$result = $this->exec_command($command_parts);
if ($result['return'] != 0)
if (0 !== $result['return'])
{
return false;
}
@ -139,15 +168,16 @@
{
$matches = [];
preg_match('#reference=([0-9]+)#u', $line, $matches);
if ($matches[1] ?? false)
{
$uid = $matches[1];
break;
}
}
if ($uid === false)
if (false === $uid)
{
return false;
}
@ -155,12 +185,12 @@
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
*/
public function read () : array
public function read(): array
{
if (!$this->unlock_sim())
{
@ -168,12 +198,12 @@
}
$command_parts = [
PWD . '/bin/gammu_get_unread_sms.py',
PWD.'/bin/gammu_get_unread_sms.py',
escapeshellarg($this->datas['config_file']),
];
$return = $this->exec_command($command_parts);
if ($return['return'] != 0)
if (0 !== $return['return'])
{
return [];
}
@ -182,7 +212,7 @@
foreach ($return['output'] as $line)
{
$decode = json_decode($line, true);
if ($decode === null)
if (null === $decode)
{
continue;
}
@ -198,34 +228,34 @@
return $smss;
}
/**
* Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid
* @return boolean : False on error, true else
* should be use for exemple to verify that credentials and number are both valid.
*
* @return bool : False on error, true else
*/
public function test () : bool
public function test(): bool
{
//Always return true as we cannot test because we would be needing a root account
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')]
*/
public static function status_change_callback ()
public static function status_change_callback()
{
return false;
}
/**
* Function to unlock pin
* Function to unlock pin.
*
* @return bool : False on error, true else
*/
private function unlock_sim () : bool
private function unlock_sim(): bool
{
if (!$this->datas['pin'])
{
@ -243,7 +273,6 @@
$result = $this->exec_command($command_parts);
//Check security status
$command_parts = [
'gammu',
@ -254,7 +283,7 @@
$result = $this->exec_command($command_parts);
if ($result['return'] != 0)
if (0 !== $result['return'])
{
return false;
}
@ -262,20 +291,20 @@
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
*
* @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
{
//Add redirect of error to stdout
$command_parts[] = '2>&1';
$command = implode(' ', $command_parts);
$output = [];
$return_var = null;
exec($command, $output, $return_var);
@ -283,20 +312,21 @@
return ['return' => (int) $return_var, 'output' => $output];
}
/**
* 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
* 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 string $search : Text to search for
*
* @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
{
$find = false;
foreach ($output as $line)
{
$find = mb_stristr($line, $search);
if ($find !== false)
if (false !== $find)
{
break;
}
@ -304,6 +334,4 @@
return (bool) $find;
}
}

View File

@ -1,6 +1,17 @@
<?php
namespace adapters;
use \Ovh\Api;
/*
* 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;
use Ovh\Api;
/**
* Interface for phones adapters
@ -12,32 +23,85 @@
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.
* 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.
* 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
*/
public static function meta_datas_fields() : array
public static function meta_datas_fields(): array
{
return [
[
@ -74,70 +138,37 @@
}
/**
* Does the implemented service support flash smss
* Does the implemented service support flash smss.
*/
public static function meta_support_flash() : bool { return false ; }
/**
* 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)
public static function meta_support_flash(): bool
{
$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']
);
return false;
}
/**
* Method called to send a SMS to a number
* 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 $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @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)
{
try
try
{
$success = true;
$endpoint = '/sms/' . $this->datas['service_name'] . '/virtualNumbers/' . $this->formatted_number . '/jobs';
$endpoint = '/sms/'.$this->datas['service_name'].'/virtualNumbers/'.$this->formatted_number.'/jobs';
$params = [
'message' => $text,
'receivers' => [$destination],
@ -145,14 +176,15 @@
$response = $this->api->post($endpoint, $params);
$nb_invalid_receivers = count(($response['invalidReceivers'] ?? []));
$nb_invalid_receivers = \count(($response['invalidReceivers'] ?? []));
if ($nb_invalid_receivers > 0)
{
return false;
}
$uids = $response['ids'] ?? [];
return ($uids[0] ?? false);
return $uids[0] ?? false;
}
catch (\Exception $e)
{
@ -160,21 +192,21 @@
}
}
/**
* Method called to read SMSs of the number
* Method called to read SMSs of the number.
*
* @return array : Array of the sms reads
*/
public function read () : array
public function read(): array
{
try
try
{
$success = true;
$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);
if (!is_array($uids) || !$uids)
if (!\is_array($uids) || !$uids)
{
return [];
}
@ -182,7 +214,7 @@
$received_smss = [];
foreach ($uids as $uid)
{
$endpoint = '/sms/' . $this->datas['service_name'] . '/virtualNumbers/' . $this->formatted_number . '/incoming/' . $uid;
$endpoint = '/sms/'.$this->datas['service_name'].'/virtualNumbers/'.$this->formatted_number.'/incoming/'.$uid;
$sms_details = $this->api->get($endpoint);
if (!isset($sms_details['creationDatetime'], $sms_details['message'], $sms_details['sender']))
@ -198,7 +230,7 @@
];
//Remove the sms to prevent double reading as ovh do not offer a filter for unread messages only
$endpoint = '/sms/' . $this->datas['service_name'] . '/virtualNumbers/' . $this->formatted_number . '/incoming/' . $uid;
$endpoint = '/sms/'.$this->datas['service_name'].'/virtualNumbers/'.$this->formatted_number.'/incoming/'.$uid;
$this->api->delete($endpoint);
}
@ -210,29 +242,28 @@
}
}
/**
* Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid
* @return boolean : False on error, true else
* should be use for exemple to verify that credentials and number are both valid.
*
* @return bool : False on error, true else
*/
public function test () : bool
public function test(): bool
{
try
try
{
$success = true;
//Check service name
$endpoint = '/sms/' . $this->datas['service_name'];
$response = $this->api->get($endpoint);
$success = $success && (bool) $response;
//Check virtualnumber
$endpoint = '/sms/virtualNumbers/' . $this->formatted_number;
$endpoint = '/sms/'.$this->datas['service_name'];
$response = $this->api->get($endpoint);
$success = $success && (bool) $response;
return $success;
//Check virtualnumber
$endpoint = '/sms/virtualNumbers/'.$this->formatted_number;
$response = $this->api->get($endpoint);
return $success && (bool) $response;
}
catch (\Exception $e)
{
@ -240,17 +271,17 @@
}
}
/**
* 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')]
*/
public static function status_change_callback ()
public static function status_change_callback()
{
$uid = $_GET['id'] ?? false;
$dlr = $_GET['dlr'] ?? false;
if ($uid === false || $dlr === false)
if (false === $uid || false === $dlr)
{
return false;
}
@ -259,15 +290,16 @@
{
case 1:
$status = 'delivered';
break;
break;
case 2:
case 16:
$status = 'failed';
break;
default:
$status = 'unknown';
break;
}

View File

@ -1,5 +1,15 @@
<?php
namespace adapters;
/*
* 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;
/**
* Interface for phones adapters
@ -11,46 +21,7 @@
class TestAdapter implements AdapterInterface
{
/**
* Classname of 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
* Phone number using the adapter.
*/
private $number;
@ -59,53 +30,113 @@
*/
private $datas;
/**
* Path for the file to read sms as a json from.
*/
private $test_file_read = PWD_DATAS.'/test_read_sms.json';
/**
* Path for the file to read sms as a json from
* Path for the file to write sms as a json in.
*/
private $test_file_read = PWD_DATAS . '/test_read_sms.json';
/**
* 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
* @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
* 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)
public function __construct(string $number, string $datas)
{
$this->number = $number;
$this->datas = $datas;
}
/**
* Method called to send a SMS to a number
* Classname of 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;
}
/**
* Method called to send a SMS to a number.
*
* @param string $destination : Phone number to send the sms to
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
* @param string $text : Text of the SMS to send
* @param bool $flash : Is the SMS a Flash SMS
*
* @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)
{
$uid = uniqid();
$at = (new \DateTime())->format('Y-m-d H:i:s');
file_put_contents($this->test_file_write, json_encode(['uid' => $uid, 'at' => $at, 'destination' => $destination, 'text' => $text, 'flash' => $flash]) . "\n", FILE_APPEND);
file_put_contents($this->test_file_write, json_encode(['uid' => $uid, 'at' => $at, 'destination' => $destination, 'text' => $text, 'flash' => $flash])."\n", FILE_APPEND);
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
*/
public function read () : array
public function read(): array
{
$file_contents = file_get_contents($this->test_file_read);
@ -119,7 +150,7 @@
foreach ($smss as $key => $sms)
{
$decode_sms = json_decode($sms, true);
if (NULL === $decode_sms)
if (null === $decode_sms)
{
continue;
}
@ -129,24 +160,24 @@
return $return;
}
/**
* Method called to verify if the adapter is working correctly
* should be use for exemple to verify that credentials and number are both valid
* @return boolean : False on error, true else
* should be use for exemple to verify that credentials and number are both valid.
*
* @return bool : False on error, true else
*/
public function test () : bool
public function test(): bool
{
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')]
*/
public static function status_change_callback ()
public static function status_change_callback()
{
$uid = $_GET['uid'] ?? false;
$status = $_GET['status'] ?? false;
@ -163,16 +194,17 @@
switch ($status)
{
case 'delivered' :
case 'delivered':
$return['status'] = 'delivered';
break;
case 'failed' :
$return['status'] = 'failed';
break;
default :
break;
case 'failed':
$return['status'] = 'failed';
break;
default:
$return['status'] = 'unknown';
break;
}

View File

@ -12,7 +12,7 @@
namespace controllers\internals;
/**
* Class to interact with adapters
* Class to interact with adapters.
*/
class Adapter extends \descartes\InternalController
{
@ -20,10 +20,11 @@ namespace controllers\internals;
private const ADAPTERS_META_START = 'meta_';
/**
* List adapters using internal metas
* List adapters using internal metas.
*
* @return array
*/
public function list_adapters ()
public function list_adapters()
{
$adapters = [];
@ -47,12 +48,12 @@ namespace controllers\internals;
return $adapters;
}
/**
* List Adapters files
* @return mixed (false|array) : array of adapters files path
*/
public function list_files ()
* List Adapters files.
*
* @return mixed (false|array) : array of adapters files path
*/
public function list_files()
{
if (!is_readable(PWD_ADAPTERS))
{
@ -66,32 +67,35 @@ namespace controllers\internals;
{
$len = mb_strlen(self::ADAPTERS_FILES_END);
$end = mb_substr($filename, -$len);
if ($end !== self::ADAPTERS_FILES_END)
if (self::ADAPTERS_FILES_END !== $end)
{
continue;
}
$adapters_files[] = PWD_ADAPTERS . '/' . $filename;
$adapters_files[] = PWD_ADAPTERS.'/'.$filename;
}
return $adapters_files;
}
/**
* 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
*/
public function read_adapter_metas ($adapter_file)
public function read_adapter_metas($adapter_file)
{
$metas = [];
if (!is_readable($adapter_file))
{
return false;
}
$adapter_classname = pathinfo($adapter_file, PATHINFO_FILENAME);
$reflection_class = new \ReflectionClass('\adapters\\' . $adapter_classname);
$reflection_class = new \ReflectionClass('\adapters\\'.$adapter_classname);
if (!$reflection_class)
{
return false;
@ -102,7 +106,7 @@ namespace controllers\internals;
{
$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;
}

View File

@ -13,25 +13,16 @@ namespace controllers\internals;
class Command 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\Command($this->bdd);
return $this->model;
}
/**
* Create a new command
* @param int $id_user : User id
* @param string $name : Command name
* @param string $script : Script file
* @param bool $admin : Is command admin only
* Create a new command.
*
* @param int $id_user : User id
* @param string $name : Command name
* @param string $script : Script file
* @param bool $admin : Is command admin only
*
* @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)
@ -50,19 +41,20 @@ namespace controllers\internals;
}
$internal_event = new Event($this->bdd);
$internal_event->create($id_user, 'COMMAND_ADD', 'Ajout commande : ' . $name . ' => ' . $script);
$internal_event->create($id_user, 'COMMAND_ADD', 'Ajout commande : '.$name.' => '.$script);
return $result;
}
/**
* Update a command
* @param int $id_user : User id
* @param int $id : Command id
* @param string $name : Command name
* @param string $script : Script file
* @param bool $admin : Is command admin only
* Update a command.
*
* @param int $id_user : User id
* @param int $id : Command id
* @param string $name : Command name
* @param string $script : Script file
* @param bool $admin : Is command admin only
*
* @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)
@ -76,38 +68,36 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id, $datas);
}
/**
* Analyse a message to check if it's a command and extract it
* @param int $id_user : User id to search a command for
* 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 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]
*/
public function check_for_command (int $id_user, string $message)
public function check_for_command(int $id_user, string $message)
{
$extracted_command = [];
$decode_message = json_decode(trim($message), true);
if ($decode_message === null)
if (null === $decode_message)
{
return false;
}
if (!isset($decode_message['login'], $decode_message['password'], $decode_message['command']))
{
return false;
}
//Check for user
$internal_user = new \controllers\internals\User($this->bdd);
$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;
}
//Find command
$commands = $this->gets_for_user($user['id']);
@ -117,6 +107,7 @@ namespace controllers\internals;
if ($decode_message['command'] === $command['name'])
{
$find_command = $command;
break;
}
}
@ -125,28 +116,36 @@ namespace controllers\internals;
{
return false;
}
//Check for admin rights
if ($find_command['admin'] && !$user['admin'])
{
return false;
}
//Forge command and return
$decode_message['password'] = '******';
$updated_text = json_encode($decode_message);
$generated_command = PWD_SCRIPTS . '/' . $find_command['script'];
$generated_command = PWD_SCRIPTS.'/'.$find_command['script'];
$args = $decode_message['args'] ?? '';
$generated_command .= ' ' . escapeshellcmd($args);
$generated_command .= ' '.escapeshellcmd($args);
return [
'updated_text' => $updated_text,
'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,27 +13,18 @@ namespace controllers\internals;
class ConditionalGroup 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\ConditionalGroup($this->bdd);
return $this->model;
}
/**
* Create a new group for a user
* @param int $id_user : user id
* @param string $name : Group name
* Create a new group for a user.
*
* @param int $id_user : user id
* @param string $name : Group name
* @param string $condition : Condition for forming group content
*
* @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)
{
$conditional_group = [
'id_user' => $id_user,
@ -47,7 +38,7 @@ namespace controllers\internals;
{
return false;
}
$id_group = $this->get_model()->insert($conditional_group);
if (!$id_group)
{
@ -55,18 +46,19 @@ namespace controllers\internals;
}
$internal_event = new Event($this->bdd);
$internal_event->create($id_user, 'CONDITIONAL_GROUP_ADD', 'Ajout du groupe conditionnel : ' . $name);
$internal_event->create($id_user, 'CONDITIONAL_GROUP_ADD', 'Ajout du groupe conditionnel : '.$name);
return $id_group;
}
/**
* Update a group for a user
* @param int $id_user : User id
* @param int $id_group : Group id
* @param string $name : Group name
* Update a group for a user.
*
* @param int $id_user : User id
* @param int $id_group : Group id
* @param string $name : Group name
* @param string $condition : Condition for forming group content
*
* @return bool : False on error, true on success
*/
public function update_for_user(int $id_user, int $id_group, string $name, string $condition)
@ -92,26 +84,28 @@ namespace controllers\internals;
return true;
}
/**
* Return a group by his name for a user
* @param int $id_user : User id
* @param string $name : Group name
* Return a group by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Group name
*
* @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->get_model()->get_by_name_for_user($id_user, $name);
}
/**
* Gets the user's contacts that respects a condition
* @param int $id_user : User id
* Gets the user's contacts that respects a condition.
*
* @param int $id_user : User id
* @param string $condition : Condition string to verify
*
* @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
{
$internal_contacts = new Contact($this->bdd);
$contacts = $internal_contacts->gets_for_user($id_user);
@ -122,7 +116,7 @@ namespace controllers\internals;
{
$contact['datas'] = json_decode($contact['datas']);
$contact = (object) $contact;
$datas = ['contact' => $contact];
$is_valid = $ruler->evaluate_condition($condition, $datas);
if (!$is_valid)
@ -130,7 +124,19 @@ namespace controllers\internals;
unset($contacts[$key]);
}
}
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,42 +12,40 @@
namespace controllers\internals;
/**
* Class to call the console scripts
* Class to call the console scripts.
*/
class Console extends \descartes\InternalController
{
/**
* Start launcher daemon
* Start launcher daemon.
*/
public function launcher ()
public function launcher()
{
new \daemons\Launcher();
}
/**
* Start sender daemon
* Start sender daemon.
*/
public function sender ()
public function sender()
{
new \daemons\Sender();
}
/**
* Start webhook daemon
* Start webhook daemon.
*/
public function webhook ()
public function webhook()
{
new \daemons\Webhook();
}
/**
* Start a phone daemon
* Start a phone daemon.
*
* @param $id_phone : Phone id
*/
public function phone ($id_phone)
public function phone($id_phone)
{
$bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$internal_phone = new \controllers\internals\Phone($bdd);
@ -60,9 +58,11 @@ namespace controllers\internals;
new \daemons\Phone($phone);
}
/**
* Cette fonction retourne la fenetre de connexion.
*
* @param mixed $id_phone
*/
public function test($id_phone)
{
@ -71,11 +71,12 @@ namespace controllers\internals;
$phone = $internal_phone->get($id_phone);
if (!$phone)
{
echo "No phone for id : $id_phone\n";
echo "No phone for id : {$id_phone}\n";
return false;
}
echo "Found phone for id : $id_phone\n";
echo "Found phone for id : {$id_phone}\n";
$adapter_classname = $phone['adapter'];
$adapter = new $adapter_classname($phone['number'], $phone['adapter_datas']);

View File

@ -13,22 +13,14 @@ namespace controllers\internals;
class Contact 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\Contact($this->bdd);
return $this->model;
}
/**
* Return a contact for a user by a number
* @param int $id_user : user id
* @param string $number : Contact number
* Return a contact for a user by a number.
*
* @param int $id_user : user id
* @param string $number : Contact number
*
* @return array
*/
public function get_by_number_and_user(int $id_user, string $number)
@ -36,36 +28,39 @@ namespace controllers\internals;
return $this->get_model()->get_by_number_and_user($id_user, $number);
}
/**
* Return a contact by his name for a user
* @param int $id_user : User id
* @param string $name : Contact name
* Return a contact by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Contact name
*
* @return array
*/
public function get_by_name_and_user(int $id_user, string $name)
{
return $this->get_model()->get_by_name_and_user($id_user, $name);
}
/**
* Return all contacts of a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user (int $id_user)
public function gets_for_user(int $id_user)
{
return $this->get_model()->gets_for_user($id_user);
}
/**
* Create a new contact
* @param int $id_user : User id
* @param string $number : Contact number
* @param string $name : Contact name
* @param string $datas : Contact datas
* Create a new contact.
*
* @param int $id_user : User id
* @param string $number : Contact number
* @param string $name : Contact name
* @param string $datas : Contact datas
*
* @return mixed bool|int : False if cannot create contact, id of the new contact else
*/
public function create($id_user, $number, $name, $datas)
@ -89,14 +84,15 @@ namespace controllers\internals;
return $result;
}
/**
* Update a contact
* @param int $id_user : User id
* @param int $id : Contact id
* @param string $number : Contact number
* @param string $name : Contact name
* @param ?string $datas : Contact datas
* Update a contact.
*
* @param int $id_user : User id
* @param int $id : Contact id
* @param string $number : Contact number
* @param string $name : Contact name
* @param ?string $datas : Contact datas
*
* @return int : number of modified rows
*/
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);
}
/**
* 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 int $id_user : User id
* @param int $id_user : User id
*
* @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;
}
@ -129,14 +126,15 @@ namespace controllers\internals;
$head = null;
while ($line = fgetcsv($file_handler))
{
if ($head === null)
if (null === $head)
{
$head = $line;
continue;
}
$line = array_combine($head, $line);
if ($line === false)
if (false === $line)
{
continue;
}
@ -149,12 +147,12 @@ namespace controllers\internals;
$datas = [];
foreach ($line as $key => $value)
{
if ($key == 'name' || $key == 'number')
if ('name' === $key || 'number' === $key)
{
continue;
}
if ($value === '')
if ('' === $value)
{
continue;
}
@ -167,23 +165,24 @@ namespace controllers\internals;
$success = $this->create($id_user, $line['number'], $line['name'], $datas);
if ($success)
{
$nb_insert ++;
++$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 int $id_user : User id
* @param int $id_user : User id
*
* @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;
}
@ -198,7 +197,7 @@ namespace controllers\internals;
{
$contacts = json_decode($file_content, true);
if (!is_array($contacts))
if (!\is_array($contacts))
{
return false;
}
@ -206,7 +205,7 @@ namespace controllers\internals;
$nb_insert = 0;
foreach ($contacts as $contact)
{
if (!is_array($contact))
if (!\is_array($contact))
{
continue;
}
@ -218,11 +217,11 @@ namespace controllers\internals;
$datas = $contact['datas'] ?? [];
$datas = json_encode($datas);
$success = $this->create($id_user, $contact['number'], $contact['name'], $datas);
if ($success)
{
$nb_insert ++;
++$nb_insert;
}
}
@ -233,14 +232,15 @@ namespace controllers\internals;
return false;
}
}
/**
* Export the contacts of a user as csv
* Export the contacts of a user as csv.
*
* @param int $id_user : User id
*
* @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
{
$contacts = $this->get_model()->gets_for_user($id_user);
@ -254,7 +254,7 @@ namespace controllers\internals;
$datas = json_decode($contact['datas'], true);
foreach ($datas as $key => $value)
{
$columns[] = $key;
$columns[] = $key;
}
}
$columns = array_unique($columns);
@ -270,12 +270,14 @@ namespace controllers\internals;
if (isset($contact[$column]))
{
$line[] = $contact[$column];
continue;
}
if (isset($datas[$column]))
{
$line[] = $datas[$column];
continue;
}
@ -286,7 +288,7 @@ namespace controllers\internals;
//Php only support csv formatting to file. To get it in string we need to create a tmp in memory file, write in it, and then read the file into a var
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv_tmp_file = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
$csv_tmp_file = fopen('php://temp/maxmemory:'.(5 * 1024 * 1024), 'r+');
fputcsv($csv_tmp_file, $columns);
foreach ($lines as $line)
{
@ -300,26 +302,27 @@ namespace controllers\internals;
'headers' => [
'Content-Disposition: attachment; filename=contacts.csv',
'Content-Type: text/csv',
'Content-Length: ' . strlen($csv_string),
'Content-Length: '.\mb_strlen($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
*
* @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
{
$contacts = $this->get_model()->gets_for_user($id_user);
foreach ($contacts as &$contact)
{
unset($contact['id']);
unset($contact['id_user']);
unset($contact['id'], $contact['id_user']);
$contact['datas'] = json_decode($contact['datas']);
}
$content = json_encode($contacts);
@ -328,10 +331,21 @@ namespace controllers\internals;
'headers' => [
'Content-Disposition: attachment; filename=contacts.json',
'Content-Type: application/json',
'Content-Length: ' . strlen($content),
'Content-Length: '.\mb_strlen($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,42 +13,36 @@ namespace controllers\internals;
class Event extends StandardController
{
protected $model = null;
protected $model;
/**
* Get the model for the Controller
* @return \descartes\Model
* Disabled methods.
*/
protected function get_model () : \descartes\Model
public function update_for_user()
{
$this->model = $this->model ?? new \models\Event($this->bdd);
return $this->model;
}
return false;
}
/**
* Disabled methods
*/
public function update_for_user() { return false; }
/**
* Gets lasts x events for a user order by date
* @param int $id_user : User id
* Gets lasts x events for a user order by date.
*
* @param int $id_user : User id
* @param int $nb_entry : Number of events to return
*
* @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->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
}
/**
* Create a new event
* @param int $id_user : user id
* Create a new event.
*
* @param int $id_user : user id
* @param mixed $type
* @param mixed $text
*
* @return mixed bool : false on fail, new event id else
*/
public function create($id_user, $type, $text)
@ -61,4 +55,16 @@ namespace controllers\internals;
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
/*
* 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;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;

View File

@ -16,34 +16,24 @@ namespace controllers\internals;
*/
class Group 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\Group($this->bdd);
return $this->model;
}
/**
* Create a new group for a user
* @param int $id_user : user id
* Create a new group for a user.
*
* @param int $id_user : user id
* @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
*/
public function create (int $id_user, string $name, array $contacts_ids)
public function create(int $id_user, string $name, array $contacts_ids)
{
$group = [
'id_user' => $id_user,
'name' => $name,
];
$id_group = $this->get_model()->insert($group);
if (!$id_group)
{
@ -63,18 +53,19 @@ namespace controllers\internals;
}
$internal_event = new Event($this->bdd);
$internal_event->create($id_user, 'GROUP_ADD', 'Ajout group : ' . $name);
$internal_event->create($id_user, 'GROUP_ADD', 'Ajout group : '.$name);
return $id_group;
}
/**
* Update a group for a user
* @param int $id_user : User id
* @param int $id_group : Group id
* Update a group for a user.
*
* @param int $id_user : User id
* @param int $id_group : Group id
* @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
*/
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))
{
$nb_contact_insert++;
++$nb_contact_insert;
}
}
@ -111,26 +102,40 @@ namespace controllers\internals;
return true;
}
/**
* Return a group by his name for a user
* @param int $id_user : User id
* @param string $name : Group name
* Return a group by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Group name
*
* @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->get_model()->get_by_name_for_user($id_user, $name);
}
/**
* Get groups contacts
* Get groups contacts.
*
* @param int $id_group : Group id
*
* @return array : Contacts of the group
*/
public function 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,26 +13,18 @@ namespace controllers\internals;
class Media 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\Media($this->bdd);
return $this->model;
}
/**
* Create a media
* @param int $id_user : Id of the user
* @param int $id_scheduled : Id of the scheduled
* @param array $media : $_FILES media array
* Create a media.
*
* @param int $id_user : Id of the user
* @param int $id_scheduled : Id of the scheduled
* @param array $media : $_FILES media array
*
* @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
{
$internal_scheduled = new Scheduled($this->bdd);
$scheduled = $internal_scheduled->get_for_user($id_user, $id_scheduled);
@ -40,14 +32,14 @@ namespace controllers\internals;
{
return false;
}
$result_upload_media = \controllers\internals\Tool::upload_file($media);
if ($result_upload_media['success'] == false)
if (false === $result_upload_media['success'])
{
return false;
}
$datas = [
$datas = [
'id_scheduled' => $id_scheduled,
'path' => $result_upload_media['content'],
];
@ -55,22 +47,23 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($datas);
}
/**
* Update a media for a user
* @param int $id_user : user id
* @param int $id_media : Media id
* @param int $id_scheduled : Id of the scheduled
* @param string $path : Path of the file
* Update a media for a user.
*
* @param int $id_user : user id
* @param int $id_media : Media id
* @param int $id_scheduled : Id of the scheduled
* @param string $path : Path of the file
*
* @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
{
$media = [
$media = [
'id_scheduled' => $id_scheduled,
'path' => $path,
];
$internal_scheduled = new Scheduled($this->bdd);
$scheduled = $this->get_for_user($id_user, $id_scheduled);
if (!$scheduled)
@ -80,15 +73,16 @@ namespace controllers\internals;
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 : Entry id
* @param int $id : Entry id
*
* @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
{
$media = $this->get_model()->get_for_user($id_user, $id_media);
if (!$media)
@ -100,15 +94,16 @@ namespace controllers\internals;
return $this->get_model()->delete_for_user($id_user, $id);
}
/**
* Delete a media for a scheduled and a user
* @param int $id_user : User id
* Delete a media for a scheduled and a user.
*
* @param int $id_user : User id
* @param int $id_scheduled : Scheduled id to delete medias for
*
* @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
{
$media = $this->get_model()->get_for_scheduled_and_user($id_user, $id_scheduled);
if ($media)
@ -119,15 +114,28 @@ namespace controllers\internals;
return $this->get_model()->delete_for_scheduled_and_user($id_user, $id_scheduled);
}
/**
* Find medias for a scheduled and a user
* @param int $id_user : User id
* Find medias for a scheduled and a user.
*
* @param int $id_user : User id
* @param int $id_scheduled : Scheduled id to delete medias for
*
* @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);
}
/**
* 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,33 +13,25 @@ namespace controllers\internals;
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.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user (int $id_user)
public function gets_for_user(int $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
*
* @return array
*/
public function get_by_number(string $number)
@ -47,11 +39,12 @@ namespace controllers\internals;
return $this->get_model()->get_by_number($number);
}
/**
* Return a phone for a user by a number
* @param int $id_user : user id
* @param string $number : Phone number
* Return a phone for a user by a number.
*
* @param int $id_user : user id
* @param string $number : Phone number
*
* @return array
*/
public function get_by_number_and_user(int $id_user, string $number)
@ -59,18 +52,19 @@ namespace controllers\internals;
return $this->get_model()->get_by_number_and_user($id_user, $number);
}
/**
* Create a phone
* @param int $id_user : User to insert phone for
* @param string $number : The number of the phone
* @param string $adapter : The adapter to use the phone
* Create a phone.
*
* @param int $id_user : User to insert phone for
* @param string $number : The number of 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)
*
* @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
{
$phone = [
$phone = [
'id_user' => $id_user,
'number' => $number,
'adapter' => $adapter,
@ -80,17 +74,18 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($phone);
}
/**
* Update a phone
* @param int $id_user : User to insert phone for
* @param int $id : Phone id
* @param string $number : The number of 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)
* Update a phone.
*
* @param int $id_user : User to insert phone for
* @param int $id : Phone id
* @param string $number : The number of 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)
*
* @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
{
$phone = [
'id_user' => $id_user,
@ -101,4 +96,16 @@ namespace controllers\internals;
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,47 +13,39 @@ namespace controllers\internals;
class Received 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\Received($this->bdd);
return $this->model;
}
/**
* Return the list of unread messages for a user
* @param int $id_user : User id
* Return the list of unread messages for a user.
*
* @param int $id_user : User id
* @param ?int $nb_entry : Number of entry to return
* @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page
*
* @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)
{
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 $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 $status : Status of the received message
* @param bool $command : Is the sms a command
* @param string $status : Status of the received message
* @param bool $command : Is the sms a command
*
* @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
{
$received = [
$received = [
'at' => $at,
'text' => $text,
'text' => $text,
'origin' => $origin,
'destination' => $destination,
'status' => $status,
@ -63,24 +55,25 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($received);
}
/**
* Update a received for a user
* @param int $id_user : user id
* Update a received for a user.
*
* @param int $id_user : user id
* @param int $id_received : received id
* @param $at : Reception date
* @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 $status : Status of the received message
* @param bool $command : Is the sms a command
* @param string $status : Status of the received message
* @param bool $command : Is the sms a command
*
* @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
{
$received = [
$received = [
'at' => $at,
'text' => $text,
'text' => $text,
'origin' => $origin,
'destination' => $destination,
'status' => $status,
@ -90,67 +83,71 @@ namespace controllers\internals;
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
* @param int $id_user : user id
* Update a received message for a user to mark the message as read.
*
* @param int $id_user : user id
* @param int $id_received : received id
*
* @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
{
$received = [
$received = [
'status' => 'read',
];
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
* @param int $id_user : user id
* Update a received message for a user to mark the message as unread.
*
* @param int $id_user : user id
* @param int $id_received : received id
*
* @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
{
$received = [
$received = [
'status' => 'unread',
];
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
* @return array
*
* @return array
*/
public function count_unread_for_user(int $id_user)
{
return $this->get_model()->count_unread_for_user($id_user);
}
/**
* Return x last receiveds message for a user, order by date
* @param int $id_user : User id
* Return x last receiveds message for a user, order by date.
*
* @param int $id_user : User id
* @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)
{
return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
}
/**
* Return receiveds for an origin and a user
* @param int $id_user : User id
* @param string $origin : Number who sent the message
* Return receiveds for an origin and a user.
*
* @param int $id_user : User id
* @param string $origin : Number who sent the message
*
* @return array
*/
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);
}
/**
* Get number of sended SMS for every date since a date for a specific user
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
* Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
*
* @return array
*/
public function count_by_day_since_for_user(int $id_user, $date)
@ -178,10 +176,11 @@ namespace controllers\internals;
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
*
* @return array
*/
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);
}
/**
* 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 $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
*/
public function get_since_by_date_for_user(int $id_user, $date)
@ -201,28 +201,42 @@ namespace controllers\internals;
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 $date : Date we want messages sinces
* @param string $origin : Origin number
*
* @return array
*/
public function get_since_by_date_for_origin_and_user(int $id_user, $date, string $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
* @param int $id_user : User id
* @param string $origin : Origin number
* Find destination of last received message for an origin and user.
*
* @param int $id_user : User id
* @param string $origin : Origin number
*
* @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);
}
/**
* 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,20 +10,20 @@
*/
namespace controllers\internals;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
/**
* Class to analyse rules used by conditional groups
*/
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
/**
* Class to analyse rules used by conditional groups.
*/
class Ruler extends \descartes\InternalController
{
private $expression_language;
/**
* Constructor
* Constructor.
*/
public function __construct ()
public function __construct()
{
$this->expression_language = new ExpressionLanguage();
@ -31,43 +31,47 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunction;
$this->expression_language->registerProvider(new ExpressionProvider());
}
/**
* Verify if a condition is valid. i.e we can evaluate it without error.
* @param string $condition : The condition to evaluate.
* @param array $datas : The datas to made available to condition
*
* @param string $condition : The condition to evaluate
* @param array $datas : The datas to made available to condition
*
* @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
{
try
try
{
$this->expression_language->evaluate($condition, $datas);
return true;
}
catch (\Exception $e)
{
return false;
}
}
}
/**
* Evaluate a condition
* @param string $condition : The condition to evaluate.
* @param array $datas : The datas to made available to condition
* Evaluate a condition.
*
* @param string $condition : The condition to evaluate
* @param array $datas : The datas to made available to condition
*
* @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
{
try
try
{
$result = $this->expression_language->evaluate($condition, $datas);
return (bool) $result;
}
catch (\Exception $e)
{
return null;
}
}
}
}

View File

@ -13,34 +13,26 @@ namespace controllers\internals;
class Scheduled 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\Scheduled($this->bdd);
return $this->model;
}
/**
* Create a scheduled
* Create a scheduled.
*
* @param int $id_user : User to insert scheduled for
* @param $at : Scheduled date to send
* @param string $text : Text of the message
* @param ?string $origin : Origin number of the message, null by default
* @param bool $flash : Is the sms a flash sms, by default false
* @param array $numbers : Numbers 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 $conditional_group_ids : Conditional Groups ids to send message to
* @param string $text : Text of the message
* @param ?string $origin : Origin number of the message, null by default
* @param bool $flash : Is the sms a flash sms, by default false
* @param array $numbers : Numbers 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 $conditional_group_ids : Conditional Groups ids to send message to
*
* @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 = [])
{
$scheduled = [
$scheduled = [
'id_user' => $id_user,
'at' => $at,
'text' => $text,
@ -58,14 +50,14 @@ namespace controllers\internals;
return false;
}
}
$id_scheduled = $this->get_model()->insert($scheduled);
if (!$id_scheduled)
{
$date = date('Y-m-d H:i:s');
$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;
}
@ -97,7 +89,7 @@ namespace controllers\internals;
$this->get_model()->insert_scheduled_group_relation($id_scheduled, $group_id);
}
$internal_conditional_group = new ConditionalGroup($this->bdd);
foreach ($conditional_group_ids as $conditional_group_id)
{
@ -113,24 +105,25 @@ namespace controllers\internals;
return $id_scheduled;
}
/**
* Update a scheduled
* @param int $id_user : User to insert scheduled for
* Update a scheduled.
*
* @param int $id_user : User to insert scheduled for
* @param int $id_scheduled : Scheduled id
* @param $at : Scheduled date to send
* @param string $text : Text of the message
* @param ?string $origin : Origin number of the message, null by default
* @param bool $flash : Is the sms a flash sms, by default false
* @param array $numbers : Numbers 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 $conditional_group_ids : Conditional Groups ids to send message to
* @param string $text : Text of the message
* @param ?string $origin : Origin number of the message, null by default
* @param bool $flash : Is the sms a flash sms, by default false
* @param array $numbers : Numbers 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 $conditional_group_ids : Conditional Groups ids to send message to
*
* @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 = [])
{
$scheduled = [
$scheduled = [
'id_user' => $id_user,
'at' => $at,
'text' => $text,
@ -138,7 +131,6 @@ namespace controllers\internals;
'flash' => $flash,
];
if ($origin)
{
$internal_phone = new Phone($this->bdd);
@ -161,7 +153,7 @@ namespace controllers\internals;
{
$this->get_model()->insert_scheduled_number($id_scheduled, $number);
}
$internal_contact = new Contact($this->bdd);
foreach ($contacts_ids as $contact_id)
{
@ -185,7 +177,7 @@ namespace controllers\internals;
$this->get_model()->insert_scheduled_group_relation($id_scheduled, $group_id);
}
$internal_conditional_group = new ConditionalGroup($this->bdd);
foreach ($conditional_group_ids as $conditional_group_id)
{
@ -201,28 +193,29 @@ namespace controllers\internals;
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 $date : Date before which we want messages
* @param string $number : Number for which we want messages
*
* @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)
{
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'], ...]
*/
public function get_smss_to_send ()
public function get_smss_to_send()
{
$smss_to_send = [];
$internal_templating = new \controllers\internals\Templating();
$internal_setting = new \controllers\internals\Setting($this->bdd);
$internal_group = new \controllers\internals\Group($this->bdd);
@ -240,7 +233,7 @@ namespace controllers\internals;
if (!isset($users_settings[$scheduled['id_user']]))
{
$users_settings[$scheduled['id_user']] = [];
$settings = $internal_setting->gets_for_user($scheduled['id_user']);
foreach ($settings as $name => $value)
{
@ -251,7 +244,7 @@ namespace controllers\internals;
if (!isset($users_phones[$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 = [];
@ -268,7 +261,7 @@ namespace controllers\internals;
'flash' => $scheduled['flash'],
];
if ($message['origin'] == null)
if (null === $message['origin'])
{
$k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k];
@ -294,7 +287,6 @@ namespace controllers\internals;
$messages[] = $message;
}
//Add messages for contacts
$contacts = $this->get_contacts($scheduled['id']);
@ -329,14 +321,14 @@ namespace controllers\internals;
'destination' => $number['number'],
'flash' => $scheduled['flash'],
];
if ($message['origin'] == null)
if (null === $message['origin'])
{
$k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k];
$message['origin'] = $rnd_phone['number'];
}
if ((int) ($users_settings[$scheduled['id_user']]['templating'] ?? false))
{
$contact['datas'] = json_decode($contact['datas'], true);
@ -361,7 +353,7 @@ namespace controllers\internals;
foreach ($messages as $message)
{
//Remove empty messages
if (trim($message['text']) == '')
if ('' === trim($message['text']))
{
continue;
}
@ -372,11 +364,12 @@ namespace controllers\internals;
return $smss_to_send;
}
/**
* Return numbers for a scheduled message
* Return numbers for a scheduled message.
*
* @param int $id_scheduled : Scheduled id
*
* @return array
*/
public function get_numbers(int $id_scheduled)
@ -384,10 +377,11 @@ namespace controllers\internals;
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
*
* @return array
*/
public function get_contacts(int $id_scheduled)
@ -395,25 +389,39 @@ namespace controllers\internals;
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
*
* @return array
*/
public function get_groups(int $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
*
* @return array
*/
public function get_conditional_groups(int $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,35 +13,27 @@ namespace controllers\internals;
class Sended 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\Sended($this->bdd);
return $this->model;
}
/**
* Create a sended
* Create a sended.
*
* @param $at : Reception date
* @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 $uid : Uid of the sms on the adapter service used
* @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash
* @param string $status : Status of a the sms. By default 'unknown'
* @param string $uid : Uid of the sms on the adapter service used
* @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash
* @param string $status : Status of a the sms. By default 'unknown'
*
* @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
{
$sended = [
$sended = [
'at' => $at,
'text' => $text,
'text' => $text,
'origin' => $origin,
'destination' => $destination,
'uid' => $uid,
@ -53,26 +45,27 @@ namespace controllers\internals;
return (bool) $this->get_model()->insert($sended);
}
/**
* Update a sended for a user
* @param int $id_user : user id
* Update a sended for a user.
*
* @param int $id_user : user id
* @param int $id_sended : Sended id
* @param $at : Reception date
* @param $text : Text of the message
* @param string $origin : Number of the sender
* @param string $destination : Number of the receiver
* @param string $uid : Uid of the sms on the adapter service used
* @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash
* @param ?string $status : Status of a the sms. By default null -> unknown
* @param string $origin : Number of the sender
* @param string $destination : Number of the receiver
* @param string $uid : Uid of the sms on the adapter service used
* @param string $adapter : Name of the adapter service used to send the message
* @param bool $flash : Is the sms a flash
* @param ?string $status : Status of a the sms. By default null -> unknown
*
* @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
{
$sended = [
$sended = [
'at' => $at,
'text' => $text,
'text' => $text,
'origin' => $origin,
'destination' => $destination,
'uid' => $uid,
@ -83,69 +76,74 @@ namespace controllers\internals;
return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended);
}
/**
* Update a sended status for a user
* @param int $id_user : user id
* @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed)
* Update a sended status for a user.
*
* @param int $id_user : user id
* @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed)
*
* @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
{
$sended = [
$sended = [
'status' => $status,
];
return (bool) $this->get_model()->update_for_user($id_user, $id_sended, $sended);
}
/**
* Update a sended status for a sended
* @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed)
* Update a sended status for a sended.
*
* @param int $id_sended : Sended id
* @param string $status : Status of a the sms (unknown, delivered, failed)
*
* @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
{
$sended = [
$sended = [
'status' => $status,
];
return (bool) $this->get_model()->update($id_sended, $sended);
}
/**
* Return x last sendeds message for a user, order by date
* @param int $id_user : User id
* Return x last sendeds message for a user, order by date.
*
* @param int $id_user : User id
* @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)
{
return $this->get_model()->get_lasts_by_date_for_user($id_user, $nb_entry);
}
/**
* Return sendeds for a destination and a user
* @param int $id_user : User id
* @param string $origin : Number who sent the message
* Return sendeds for a destination and a user.
*
* @param int $id_user : User id
* @param string $origin : Number who sent the message
*
* @return array
*/
public function gets_by_destination_and_user(int $id_user, string $origin)
{
return $this->get_model()->gets_by_destination_and_user($id_user, $origin);
}
/**
* Return sended for an uid and an adapter
* @param string $uid : Uid of the sended
* Return sended for an uid and an adapter.
*
* @param string $uid : Uid of the sended
* @param string $adapter : Adapter used to send the message
*
* @return array
*/
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);
}
/**
* Get number of sended SMS for every date since a date for a specific user
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
* Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
*
* @return array
*/
public function count_by_day_since_for_user(int $id_user, $date)
@ -172,16 +171,29 @@ namespace controllers\internals;
return $return;
}
/**
* Find last sended message for a destination and user
* @param int $id_user : User id
* Find last sended message for a destination and user.
*
* @param int $id_user : User id
* @param string $destination : Destination number
*
* @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);
}
/**
* 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,25 +13,16 @@ namespace controllers\internals;
class Setting extends StandardController
{
protected $model = null;
/**
* 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;
}
protected $model;
/**
* Return all settings of a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user (int $id_user)
public function gets_for_user(int $id_user)
{
$settings = $this->get_model()->gets_for_user($id_user);
$settings_array = [];
@ -44,28 +35,30 @@ namespace controllers\internals;
return $settings_array;
}
/**
* Update a setting by his name and user id.
* @param int $id_user : user id
* @param string $name : setting name
* @param mixed $value
*
* @param int $id_user : user id
* @param string $name : setting name
* @param mixed $value
*
* @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
{
return (bool) $this->get_model()->update_by_name_for_user($id_user, $name, $value);
}
/**
* Create a new setting
* @param int $id_user : user id
* @param string $name : setting name
* @param mixed $value : value of the setting
* @return bool
* Create a new setting.
*
* @param int $id_user : user id
* @param string $name : setting name
* @param mixed $value : value of the setting
*
* @return bool
*/
public function create (int $id_user, string $name, $value) : bool
public function create(int $id_user, string $name, $value): bool
{
$setting = [
'id_user' => $id_user,
@ -76,10 +69,11 @@ namespace controllers\internals;
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
*
* @return bool
*/
public function create_defaults_for_user(int $id_user)
@ -93,4 +87,16 @@ namespace controllers\internals;
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
{
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\SmsStop($this->bdd);
return $this->model;
}
/**
* Create a new smsstop
* @param int $id_user : User id
* @param string $number : Number to stop smss for
* Create a new smsstop.
*
* @param int $id_user : User id
* @param string $number : Number to stop smss for
*
* @return mixed bool|int : False if cannot create smsstop, id of the new smsstop else
*/
public function create(int $id_user, string $number)
@ -41,13 +32,14 @@ namespace controllers\internals;
return $this->get_model()->insert($smsstop);
}
/**
* Update a smsstop
* @param int $id_user : User id
* @param int $id_smsstop : SmsStop id
* @param string $number : Number to stop smss for
* Update a smsstop.
*
* @param int $id_user : User id
* @param int $id_smsstop : SmsStop id
* @param string $number : Number to stop smss for
*
* @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)
@ -59,15 +51,28 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id_smsstop, $datas);
}
/**
* Return a smsstop by his number and user
* @param int $id_user : user id
* @param string $number : phone number
* Return a smsstop by his number and user.
*
* @param int $id_user : user id
* @param string $number : phone number
*
* @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);
}
/**
* 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,111 +19,120 @@ namespace controllers\internals;
}
/**
* Get the model for the Controller
* @return \descartes\Model
*/
abstract protected function get_model () : \descartes\Model;
/**
* Return all the entries
* Return all the entries.
*
* @return array
*/
public function get_all ()
public function 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
*
* @return array
*/
public function get (int $id)
public function get(int $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 : Entry id
* @param int $id : Entry id
*
* @return array
*/
public function get_for_user (int $id_user, int $id)
public function get_for_user(int $id_user, int $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
*
* @return array
*/
public function gets_for_user (int $id_user)
public function gets_for_user(int $id_user)
{
return $this->get_model()->gets_for_user($id_user);
}
/**
* Return the list of entries for a user
* @param int $id_user : User id
* Return the list of entries for a user.
*
* @param int $id_user : User id
* @param ?int $nb_entry : Number of entry to return
* @param ?int $page : Pagination, used to calcul offset, $nb_entry * $page
*
* @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)
{
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
* @param int $id_user : user id
* @param array $ids : ids of entries to find
* Return a list of entries in a group of ids and for a user.
*
* @param int $id_user : user id
* @param array $ids : ids of entries to find
*
* @return array
*/
public function gets_in_for_user (int $id_user, array $ids)
public function gets_in_for_user(int $id_user, array $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 : Entry id
* @param int $id : Entry id
*
* @return int : Number of removed rows
*/
public function delete_for_user(int $id_user, int $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
*
* @return int : Number of removed rows
*/
public function delete (int $id)
public function delete(int $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
*
* @return int : number of entries
*/
public function count_for_user(int $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,16 +13,16 @@ namespace controllers\internals;
/**
* 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
{
/**
* Twig environment
* Twig environment.
*/
private $sandbox;
public function __construct ()
public function __construct()
{
$tags = [
'if',
@ -45,23 +45,24 @@ namespace controllers\internals;
$properties = [];
$functions = [
'date', 'max', 'min', 'random',
'range',
'range',
];
$policy = new \Twig\Sandbox\SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$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 array $datas : Datas to pass to the template
* @param array $datas : Datas to pass to the template
*
* @return array : keys, success, error, result
*/
public function render (string $template, array $datas = [])
public function render(string $template, array $datas = [])
{
try
try
{
$loader = new \Twig\Loader\ArrayLoader([
'template' => $template,
@ -69,7 +70,7 @@ namespace controllers\internals;
$twig = new \Twig\Environment($loader);
$result = $twig->render('template', $datas);
return [
'success' => true,
'result' => $result,
@ -83,5 +84,4 @@ namespace controllers\internals;
];
}
}
}

View File

@ -13,7 +13,7 @@ namespace controllers\internals;
/**
* 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
{
@ -40,7 +40,7 @@ namespace controllers\internals;
return $phone_number_util->format($phone_number_o, \libphonenumber\PhoneNumberFormat::E164);
}
catch(\Exception $e)
catch (\Exception $e)
{
return false;
}
@ -62,22 +62,25 @@ namespace controllers\internals;
return $phone_number_util->format($phone_number_o, \libphonenumber\PhoneNumberFormat::INTERNATIONAL);
}
catch(\Exception $e)
catch (\Exception $e)
{
return $number;
}
}
/**
* 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
*
* @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]);
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;
}
/**
* 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']
*
* @return array : ['success' => bool, 'content' => file handler | error message, 'error_code' => $file['error']]
*/
public static function read_uploaded_file(array $file)
@ -219,40 +223,41 @@ namespace controllers\internals;
'mime_type' => false,
];
if ($file['error'] !== UPLOAD_ERR_OK)
if (UPLOAD_ERR_OK !== $file['error'])
{
switch ($file['error'])
{
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.';
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.';
break;
case UPLOAD_ERR_FORM_SIZE :
case UPLOAD_ERR_FORM_SIZE:
$result['content'] = 'Le fichier dépasse la limite de taille.';
break;
case UPLOAD_ERR_PARTIAL :
case UPLOAD_ERR_PARTIAL:
$result['content'] = 'L\'envoi du fichier a été interrompu.';
break;
case UPLOAD_ERR_NO_FILE :
break;
case UPLOAD_ERR_NO_FILE:
$result['content'] = 'Aucun fichier n\'a été envoyé.';
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.';
break;
case UPLOAD_ERR_CANT_WRITE :
break;
case UPLOAD_ERR_CANT_WRITE:
$result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.';
break;
case UPLOAD_ERR_EXTENSION :
break;
case UPLOAD_ERR_EXTENSION:
$result['content'] = 'Le serveur a interrompu l\'envoi du fichier.';
break;
}
return $result;
return $result;
}
$tmp_filename = $file['tmp_name'] ?? false;
@ -261,7 +266,7 @@ namespace controllers\internals;
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');
$result['success'] = true;
@ -269,11 +274,12 @@ namespace controllers\internals;
return $result;
}
/**
* Allow to upload file
* Allow to upload file.
*
* @param array $file : The array extracted from $_FILES['file']
*
* @return array : ['success' => bool, 'content' => file path | error message, 'error_code' => $file['error']]
*/
public static function upload_file(array $file)
@ -284,40 +290,41 @@ namespace controllers\internals;
'error_code' => $file['error'] ?? 99,
];
if ($file['error'] !== UPLOAD_ERR_OK)
if (UPLOAD_ERR_OK !== $file['error'])
{
switch ($file['error'])
{
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.';
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.';
break;
case UPLOAD_ERR_FORM_SIZE :
case UPLOAD_ERR_FORM_SIZE:
$result['content'] = 'Le fichier dépasse la limite de taille.';
break;
case UPLOAD_ERR_PARTIAL :
case UPLOAD_ERR_PARTIAL:
$result['content'] = 'L\'envoi du fichier a été interrompu.';
break;
case UPLOAD_ERR_NO_FILE :
break;
case UPLOAD_ERR_NO_FILE:
$result['content'] = 'Aucun fichier n\'a été envoyé.';
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.';
break;
case UPLOAD_ERR_CANT_WRITE :
break;
case UPLOAD_ERR_CANT_WRITE:
$result['content'] = 'Impossible d\'envoyer le fichier car il n\'y a plus de place sur le serveur.';
break;
case UPLOAD_ERR_EXTENSION :
break;
case UPLOAD_ERR_EXTENSION:
$result['content'] = 'Le serveur a interrompu l\'envoi du fichier.';
break;
}
return $result;
return $result;
}
$tmp_filename = $file['tmp_name'] ?? false;
@ -332,13 +339,13 @@ namespace controllers\internals;
return $result;
}
$new_file_path = PWD_DATAS . '/' . $md5_filename;
$new_file_path = PWD_DATAS.'/'.$md5_filename;
if (file_exists($new_file_path))
{
$result['success'] = true;
$result['content'] = $new_file_path;
return $result;
}
@ -346,6 +353,7 @@ namespace controllers\internals;
if (!$success)
{
$result['content'] = 'Impossible d\'écrire le fichier sur le serveur.';
return $result;
}

View File

@ -12,7 +12,7 @@
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
{
@ -52,9 +52,8 @@ namespace controllers\internals;
return $this->model_user->remove($id);
}
/**
* Check user credentials
* Check user credentials.
*
* @param string $email : User email
* @param string $password : User password
@ -92,7 +91,6 @@ namespace controllers\internals;
return (bool) $this->model_user->update_password($id, $password);
}
/**
* Update user email.
*
@ -105,12 +103,11 @@ namespace controllers\internals;
{
return (bool) $this->model_user->update_email($id, $email);
}
/**
* Update user api key.
*
* @param string $id : user id
* @param string $id : user id
* @param ?string $api_key : new api key
*
* @return mixed : false on error, else new 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
*
* @return mixed boolean | array : false if cannot find user for this email, the user else
@ -138,21 +136,22 @@ namespace controllers\internals;
{
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
*
* @return mixed array
*/
public function get ($id)
public function 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
*
* @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 $email
* @param mixed $password
* @param mixed $admin
* @param mixed $api_key
*
* @return int : Number of modified user
*/
@ -184,12 +185,12 @@ namespace controllers\internals;
}
/**
* Create a new user
* Create a new user.
*
* @param mixed $email
* @param mixed $password
* @param mixed $admin
* @param ?string $api_key : The api key of the user, if null generate randomly
* @param mixed $email
* @param mixed $password
* @param mixed $admin
* @param ?string $api_key : The api key of the user, if null generate randomly
*
* @return mixed bool|int : false on error, id of the new user else
*/
@ -214,18 +215,19 @@ namespace controllers\internals;
if (!$success)
{
$this->delete($new_user_id);
return false;
}
return $new_user_id;
}
/**
* Generate a random api key
* Generate a random api key.
*
* @return string : The api key
*/
public function generate_random_api_key () : string
public function generate_random_api_key(): string
{
return bin2hex(random_bytes(16));
}

View File

@ -13,24 +13,15 @@ namespace controllers\internals;
class Webhook 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\Webhook($this->bdd);
return $this->model;
}
/**
* Create a new webhook
* @param int $id_user : User id
* @param string $url : Webhook url
* @param string $type : Webhook type
* Create a new webhook.
*
* @param int $id_user : User id
* @param string $url : Webhook url
* @param string $type : Webhook type
*
* @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)
@ -46,17 +37,18 @@ namespace controllers\internals;
{
return false;
}
return $result;
}
/**
* Update a webhook
* @param int $id_user : User id
* @param int $id : Webhook id
* @param string $url : Webhook url
* @param string $type : Webhook type
* Update a webhook.
*
* @param int $id_user : User id
* @param int $id : Webhook id
* @param string $url : Webhook url
* @param string $type : Webhook type
*
* @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)
@ -69,15 +61,28 @@ namespace controllers\internals;
return $this->get_model()->update_for_user($id_user, $id, $datas);
}
/**
* Find all webhooks for a user and for a type of webhook
* @param int $id_user : User id
* @param string $type : Webhook type
* Find all webhooks for a user and for a type of webhook.
*
* @param int $id_user : User id
* @param string $type : Webhook type
*
* @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);
}
/**
* 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'));
}
/**
* Update user email.
*
@ -117,8 +116,7 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Account', 'show'));
}
/**
* Update user api key.
*
@ -148,7 +146,6 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Account', 'show'));
}
/**
* Delete a user.
*

View File

@ -12,11 +12,11 @@
namespace controllers\publics;
/**
* Api to interact with raspisms
* Api to interact with raspisms.
*/
class Api extends \descartes\ApiController
{
CONST DEFAULT_RETURN = [
const DEFAULT_RETURN = [
'error' => 0, //Error code
'message' => null, //Any message to describe a potential error
'response' => null, //The content of the response
@ -24,7 +24,7 @@ namespace controllers\publics;
'prev' => null, //Link to the previous results
];
CONST ERROR_CODES = [
const ERROR_CODES = [
'NONE' => 0,
'INVALID_CREDENTIALS' => 1,
'INVALID_PARAMETER' => 2,
@ -32,13 +32,12 @@ namespace controllers\publics;
'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_PARAMETER' => 'You have specified an invalid parameter : ',
'MISSING_PARAMETER' => 'One require parameter is missing : ',
'CANNOT_CREATE' => 'Cannot create a new entry.',
];
private $internal_user;
private $internal_phone;
@ -49,13 +48,14 @@ namespace controllers\publics;
private $user;
/**
* Construct the object and quit if failed authentication
* Construct the object and quit if failed authentication.
*
* @return void;
*/
public function __construct()
{
parent::__construct();
$bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD);
$this->internal_user = new \controllers\internals\User($bdd);
$this->internal_phone = new \controllers\internals\Phone($bdd);
@ -71,7 +71,7 @@ namespace controllers\publics;
$api_key = $_GET['api_key'] ?? false;
if ($api_key)
{
$this->user = $this->internal_user->get_by_api_key($api_key);
$this->user = $this->internal_user->get_by_api_key($api_key);
}
if (!$this->user)
@ -86,37 +86,38 @@ namespace controllers\publics;
}
}
/**
* 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 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
*/
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'];
if (!in_array($entry_type, $entry_types))
if (!\in_array($entry_type, $entry_types, true))
{
$return = self::DEFAULT_RETURN;
$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->json($return);
return false;
}
$controller_str = 'internal_' . $entry_type;
$controller = $this->$controller_str;
$controller_str = 'internal_'.$entry_type;
$controller = $this->{$controller_str};
$page = (int) $page;
$limit = 25;
$entries = $controller->list_for_user($this->user['id'], $limit, $page);
//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)
{
@ -127,7 +128,7 @@ namespace controllers\publics;
}
}
//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)
{
@ -135,11 +136,10 @@ namespace controllers\publics;
}
}
$return = self::DEFAULT_RETURN;
$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']]);
}
@ -153,35 +153,36 @@ namespace controllers\publics;
$this->json($return);
}
/**
* 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['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['flash'] : Default false. Is the sms a flash sms.
* @param string $_POST['numbers'] : Array of numbers 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
* 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['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['flash'] : Default false. Is the sms a flash sms.
* @param string $_POST['numbers'] : Array of numbers 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['conditional_groups'] : Array of ids of conditional groups to send message to
*
* @return Id of scheduled created
*/
public function post_scheduled ()
public function post_scheduled()
{
$at = $_POST['at'] ?? false;
$text = $_POST['text'] ?? false;
$origin = empty($_POST['origin']) ? null : $_POST['origin'];
$flash = (bool) ($_POST['flash'] ?? false);
$numbers = $_POST['numbers'] ?? [];
$contacts = $_POST['contacts'] ?? [];
$groups = $_POST['groups'] ?? [];
$numbers = $_POST['numbers'] ?? [];
$contacts = $_POST['contacts'] ?? [];
$groups = $_POST['groups'] ?? [];
$conditional_groups = $_POST['conditional_groups'] ?? [];
if (!$at || !$text)
{
$return = self::DEFAULT_RETURN;
$return['error'] = self::ERROR_CODES['MISSING_PARAMETER'];
$return['message'] = self::ERROR_MESSAGES['MISSING_PARAMETER'] . ($at ? '' : 'at ') . ($text ? '' : 'text');
$return['message'] = self::ERROR_MESSAGES['MISSING_PARAMETER'].($at ? '' : 'at ').($text ? '' : 'text');
$this->auto_http_code(false);
$this->json($return);
@ -192,7 +193,7 @@ namespace controllers\publics;
{
$return = self::DEFAULT_RETURN;
$return['error'] = self::ERROR_CODES['INVALID_PARAMETER'];
$return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'] . 'at must be a date of format "Y-m-d H:i:s".';
$return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'].'at must be a date of format "Y-m-d H:i:s".';
$this->auto_http_code(false);
$this->json($return);
@ -206,6 +207,7 @@ namespace controllers\publics;
if (!$number)
{
unset($numbers[$key]);
continue;
}
@ -216,7 +218,7 @@ namespace controllers\publics;
{
$return = self::DEFAULT_RETURN;
$return['error'] = self::ERROR_CODES['MISSING_PARAMETER'];
$return['message'] = self::ERROR_MESSAGES['MISSING_PARAMETER'] . 'You must specify at least one valid number, contact, group or conditional_group.';
$return['message'] = self::ERROR_MESSAGES['MISSING_PARAMETER'].'You must specify at least one valid number, contact, group or conditional_group.';
$this->auto_http_code(false);
$this->json($return);
@ -227,7 +229,7 @@ namespace controllers\publics;
{
$return = self::DEFAULT_RETURN;
$return['error'] = self::ERROR_CODES['INVALID_PARAMETER'];
$return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'] . 'origin : You must specify an origin number among thoses of user phones.';
$return['message'] = self::ERROR_MESSAGES['INVALID_PARAMETER'].'origin : You must specify an origin number among thoses of user phones.';
$this->auto_http_code(false);
$this->json($return);
@ -252,23 +254,22 @@ namespace controllers\publics;
$this->json($return);
}
/**
* Delete a scheduled message
* Delete a scheduled message.
*
* @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)
{
$success = $this->internal_scheduled->delete_for_user($this->user['id'], $id);
if (!$success)
{
$this->auto_http_code(false);
return false;
return false;
}
$this->auto_http_code(true);
}
}

View File

@ -12,7 +12,7 @@
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
{
@ -30,16 +30,17 @@ 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
*
* @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
*/
public function update_sended_status (string $adapter_name)
public function update_sended_status(string $adapter_name)
{
//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
$find_adapter = false;

View File

@ -40,7 +40,7 @@ namespace controllers\publics;
}
/**
* Return all conditionnals groups for administration
* Return all conditionnals groups for administration.
*
* @param mixed $page
*/
@ -48,7 +48,6 @@ namespace controllers\publics;
{
$page = (int) $page;
$groups = $this->internal_conditional_group->list_for_user($_SESSION['user']['id'], 25, $page);
$this->render('conditional_group/list', ['groups' => $groups]);
}
@ -107,7 +106,7 @@ namespace controllers\publics;
* Cette fonction insert un nouveau group.
*
* @param $csrf : Le jeton CSRF
* @param string $_POST['name'] : Le nom du group
* @param string $_POST['name'] : Le nom du group
* @param array $_POST['condition'] : The condition to used
*/
public function create($csrf)
@ -178,14 +177,15 @@ namespace controllers\publics;
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
*
* @return json string
*/
public function contacts_preview ()
public function contacts_preview()
{
$return = [
'success' => false,
@ -193,21 +193,22 @@ namespace controllers\publics;
];
$condition = $_POST['condition'] ?? false;
if (!$condition)
{
$return['result'] = 'Vous devez renseigner une condition.';
echo json_encode($return);
return false;
}
$internal_ruler = new \controllers\internals\Ruler();
$valid_condition = $internal_ruler->validate_condition($condition, ['contact' => (object) ['datas' => (object) null]]);
if (!$valid_condition)
{
$return['result'] = 'Syntaxe de la condition invalide.';
echo json_encode($return);
return false;
}
@ -216,6 +217,7 @@ namespace controllers\publics;
{
$return['result'] = 'Aucun contact dans le groupe.';
echo json_encode($return);
return false;
}
@ -225,16 +227,15 @@ namespace controllers\publics;
$contacts_name[] = $contact['name'];
}
$return['result'] = "Contacts du groupe : " . implode(', ', $contacts_name);
$return['result'] = 'Contacts du groupe : '.implode(', ', $contacts_name);
$return['success'] = true;
echo json_encode($return);
return true;
}
/**
* Return the list of groups as JSON
* Return the list of groups as JSON.
*/
public function json_list()
{

View File

@ -151,7 +151,7 @@ namespace controllers\publics;
$clean_datas = [];
foreach ($datas as $key => $value)
{
if ($value === "")
if ('' === $value)
{
continue;
}
@ -159,7 +159,7 @@ namespace controllers\publics;
$key = mb_ereg_replace('[\W]', '', $key);
$clean_datas[$key] = (string) $value;
}
$clean_datas = json_encode($clean_datas);
if (!$this->internal_contact->create($id_user, $number, $name, $clean_datas))
@ -191,7 +191,7 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
if (!array($_POST['contacts']))
if (![$_POST['contacts']])
{
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
@ -203,22 +203,22 @@ namespace controllers\publics;
$number = $contact['number'] ?? false;
$id_user = $_SESSION['user']['id'];
$datas = $contact['datas'] ?? [];
if (!$name || !$number)
{
continue;
}
$number = \controllers\internals\Tool::parse_phone($number);
if (!$number)
{
continue;
}
$clean_datas = [];
foreach ($datas as $key => $value)
{
if ($value === "")
if ('' === $value)
{
continue;
}
@ -227,7 +227,7 @@ namespace controllers\publics;
$clean_datas[$key] = (string) $value;
}
$clean_datas = json_encode($clean_datas);
$nb_contacts_update += (int) $this->internal_contact->update_for_user($id_user, $id_contact, $number, $name, $clean_datas);
}
@ -243,17 +243,18 @@ namespace controllers\publics;
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 $_FILES['contacts_list_file'] : A csv file of the contacts to import
*/
public function import (string $csrf)
public function import(string $csrf)
{
if (!$this->verify_csrf($csrf))
{
\FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !');
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
@ -263,6 +264,7 @@ namespace controllers\publics;
if (!$upload_array)
{
\FlashMessage\FlashMessage::push('danger', 'Vous devez fournir un fichier de contacts à importer.');
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
@ -270,6 +272,7 @@ namespace controllers\publics;
if (!$read_file['success'])
{
\FlashMessage\FlashMessage::push('danger', $read_file['content']);
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
@ -277,46 +280,49 @@ namespace controllers\publics;
$invalid_type = false;
switch ($read_file['mime_type'])
{
case 'text/csv' :
case 'text/csv':
$result = $this->internal_contact->import_csv($id_user, $read_file['content']);
break;
case 'application/json' :
case 'application/json':
$result = $this->internal_contact->import_json($id_user, $read_file['content']);
break;
default :
default:
$invalid_type = true;
}
if ($invalid_type)
{
\FlashMessage\FlashMessage::push('danger', 'Le type de fichier n\'est pas valide.');
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.');
return $this->redirect(\descartes\Router::url('Contact', 'list'));
}
$msg = $result . ' nouveau contact a été inséré.';
$msg = $result.' nouveau contact a été inséré.';
if ($result > 1)
{
$msg = $result . ' nouveaux contacts ont été insérés.';
$msg = $result.' nouveaux contacts ont été insérés.';
}
\FlashMessage\FlashMessage::push('success', $msg);
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
*/
public function export (string $format)
public function export(string $format)
{
$id_user = $_SESSION['user']['id'];
@ -324,27 +330,29 @@ namespace controllers\publics;
$invalid_type = false;
switch ($format)
{
case 'csv' :
case 'csv':
$result = $this->internal_contact->export_csv($id_user);
break;
case 'json' :
case 'json':
$result = $this->internal_contact->export_json($id_user);
break;
default :
default:
$invalid_type = true;
}
if ($invalid_type)
{
\FlashMessage\FlashMessage::push('danger', 'Le format demandé n\'est pas supporté.');
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.');
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);
$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
$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);

View File

@ -113,7 +113,7 @@ namespace controllers\publics;
foreach ($receiveds as $received)
{
if ($received['status'] != 'read')
if ('read' !== $received['status'])
{
$this->internal_received->mark_as_read_for_user($id_user, $received['id']);
}
@ -152,10 +152,10 @@ namespace controllers\publics;
/**
* Cette fonction permet d'envoyer facilement un sms à un numéro donné.
*
* @param string $csrf : Le jeton csrf
* @param string $_POST['text'] : Le contenu du Sms
* @param string $csrf : Le jeton csrf
* @param string $_POST['text'] : Le contenu du Sms
* @param string $_POST['destination'] : Number to send sms to
* @param string $_POST['origin'] : Number to send sms with
* @param string $_POST['origin'] : Number to send sms with
*
* @return string : json string Le statut de l'envoi
*/

View File

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

View File

@ -49,7 +49,7 @@ namespace controllers\publics;
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']);
}
@ -64,10 +64,10 @@ namespace controllers\publics;
$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
*/
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 mixed $csrf
*
@ -103,6 +104,7 @@ namespace controllers\publics;
if (!$this->verify_csrf($csrf))
{
\FlashMessage\FlashMessage::push('danger', 'Jeton CSRF invalid !');
return $this->redirect(\descartes\Router::url('Received', 'list'));
}
@ -132,7 +134,7 @@ namespace controllers\publics;
continue;
}
$receiveds[$key]['origin'] = $this->s($contact['name'], false, true, false) . ' (' . \controllers\internals\Tool::phone_link($received['origin']) . ')';
$receiveds[$key]['origin'] = $this->s($contact['name'], false, true, false).' ('.\controllers\internals\Tool::phone_link($received['origin']).')';
}
$nb_received = \count($receiveds);

View File

@ -88,6 +88,7 @@ namespace controllers\publics;
/**
* 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)
*/
public function add($prefilled = false)
@ -100,7 +101,7 @@ namespace controllers\publics;
$contacts = $this->internal_contact->gets_for_user($id_user);
$phones = $this->internal_phone->gets_for_user($id_user);
$prefilled_contacts = [];
$prefilled_groups = [];
$prefilled_conditional_groups = [];
@ -110,21 +111,21 @@ namespace controllers\publics;
$ids = $_GET['ids'] ?? [];
}
if ($prefilled === 'contacts')
if ('contacts' === $prefilled)
{
foreach ($this->internal_contact->gets_in_for_user($id_user, $ids) as $contact)
{
$prefilled_contacts[] = $contact['id'];
}
}
elseif ($prefilled === 'groups')
elseif ('groups' === $prefilled)
{
foreach ($this->internal_group->gets_in_for_user($id_user, $ids) as $group)
{
$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)
{
@ -154,6 +155,7 @@ namespace controllers\publics;
if (!$ids)
{
\FlashMessage\FlashMessage::push('danger', 'Vous devez choisir des messages à mettre à jour !');
return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
}
@ -195,7 +197,7 @@ namespace controllers\publics;
}
$media = $this->internal_media->get_for_scheduled_and_user($id_user, $scheduled['id']);
$scheduleds[$key]['media'] = $media;
$scheduleds[$key]['media'] = $media;
$conditional_groups = $this->internal_scheduled->get_conditional_groups($scheduled['id']);
foreach ($conditional_groups as $conditional_group)
@ -220,7 +222,7 @@ namespace controllers\publics;
* @param string $_POST['numbers'] : Les numeros de téléphone du scheduled
* @param string $_POST['contacts'] : Les contacts du scheduled
* @param string $_POST['groups'] : Les groups du scheduled
* @param array $_FILES['media'] : The media to link to a scheduled
* @param array $_FILES['media'] : The media to link to a scheduled
*/
public function create($csrf)
{
@ -272,30 +274,31 @@ namespace controllers\publics;
if (!$numbers && !$contacts && !$groups && !$conditional_groups)
{
\FlashMessage\FlashMessage::push('danger', 'Vous devez renseigner au moins un destinataire pour le Sms.');
return $this->redirect(\descartes\Router::url('Scheduled', 'add'));
}
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.');
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);
if (!$scheduled_id)
{
\FlashMessage\FlashMessage::push('danger', 'Impossible de créer le Sms.');
return $this->redirect(\descartes\Router::url('Scheduled', 'add'));
}
//If mms is enabled, try to process a media to link to the scheduled
$media = $_FILES['media'] ?? false;
if (!($_SESSION['user']['settings']['mms'] ?? false) || !$media)
{
\FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
}
@ -303,10 +306,12 @@ namespace controllers\publics;
if (!$success)
{
\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'));
}
\FlashMessage\FlashMessage::push('success', 'Le Sms a bien été créé pour le '.$at.'.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
}
@ -329,7 +334,6 @@ namespace controllers\publics;
$scheduleds = $_POST['scheduleds'] ?? [];
$nb_update = 0;
foreach ($scheduleds as $id_scheduled => $scheduled)
{
@ -348,8 +352,7 @@ namespace controllers\publics;
{
continue;
}
if (empty($text))
{
continue;
@ -377,8 +380,7 @@ namespace controllers\publics;
{
continue;
}
if ($origin && !$this->internal_phone->get_by_number_and_user($id_user, $origin))
{
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.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
}
\FlashMessage\FlashMessage::push('success', 'Tous les SMS ont été mis à jour.');
return $this->redirect(\descartes\Router::url('Scheduled', 'list'));
}
}

View File

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

View File

@ -32,12 +32,14 @@ namespace controllers\publics;
}
/**
* Try to render a template as a message for preview
* @param string $_POST['template'] : Template string
* @param int $_POST['id_contact'] : Id of the contact to render the template for
* Try to render a template as a message for preview.
*
* @param string $_POST['template'] : Template string
* @param int $_POST['id_contact'] : Id of the contact to render the template for
*
* @return json string
*/
public function render_preview ()
public function render_preview()
{
$return = [
'success' => false,
@ -46,19 +48,21 @@ namespace controllers\publics;
$template = $_POST['template'] ?? false;
$id_contact = $_POST['id_contact'] ?? false;
if (!$template || !$id_contact)
{
$return['result'] = 'Veuillez remplir un message.';
echo json_encode($return);
return false;
}
$contact = $this->internal_contact->get_for_user($_SESSION['user']['id'], $id_contact);
if (!$contact)
{
$return['result'] = 'Ce contact n\'existe pas.';
echo json_encode($return);
return false;
}
@ -76,6 +80,7 @@ namespace controllers\publics;
}
echo json_encode($return);
return true;
}
}

View File

@ -30,7 +30,7 @@ namespace controllers\publics;
}
/**
* List all webhooks
* List all webhooks.
*
* @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 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
*/
@ -93,10 +93,10 @@ namespace controllers\publics;
}
/**
* Insert a new webhook
* Insert a new webhook.
*
* @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
* @param string $_POST['type'] : Type of webhook, either 'send_sms' or 'receive_sms'
*
* @return boolean;

View File

@ -1,35 +1,44 @@
<?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;
/**
* Class defining the global structur of a Linux Daemon
* Class defining the global structur of a Linux Daemon.
*/
abstract class AbstractDaemon
{
protected $name;
protected $uniq;
protected $name;
protected $uniq;
protected $logger;
protected $no_parent;
private $is_running = true;
private $signals = array (
private $is_running = true;
private $signals = [
SIGTERM,
SIGINT,
SIGCHLD,
SIGHUP
);
SIGHUP,
];
/**
* Class used to handle POSIX signals and fork from the current process
*
* @param string $name : The name of the class
* @param object $logger : A PSR3 logger instance
* @param string $pid_dir : Directory for the pid files
* @param bool $no_parent : Should the daemon be disconnected from his parent process
* @param array $signals :An array containing additional POSIX signals to handle [optionel]
* @param bool $uniq : Must the process be uniq ?
*/
protected function __construct (string $name, object $logger, string $pid_dir = '/var/run', $no_parent = false, array $signals = [], bool $uniq = false)
/**
* Class used to handle POSIX signals and fork from the current process.
*
* @param string $name : The name of the class
* @param object $logger : A PSR3 logger instance
* @param string $pid_dir : Directory for the pid files
* @param bool $no_parent : Should the daemon be disconnected from his parent process
* @param array $signals :An array containing additional POSIX signals to handle [optionel]
* @param bool $uniq : Must the process be uniq ?
*/
protected function __construct(string $name, object $logger, string $pid_dir = '/var/run', $no_parent = false, array $signals = [], bool $uniq = false)
{
$this->name = $name;
$this->logger = $logger;
@ -42,97 +51,85 @@ abstract class AbstractDaemon
set_time_limit(0);
//Register signals
$this->register_signals();
$this->register_signals();
}
/**
* Used to register POSIX signals
*/
private function register_signals()
/**
* True if the daemon is running.
*/
public function is_running()
{
//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'
]);
}
return $this->is_running;
}
/**
* Used to handle properly SIGINT, SIGTERM, SIGCHLD and SIGHUP
*
* @param int $signal
/**
* Used to handle properly SIGINT, SIGTERM, SIGCHLD and SIGHUP.
*
* @param int $signal
* @param mixed $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;
}
else if ($signal == SIGHUP) //Restart the daemon
{
$this->on_stop();
$this->on_start();
elseif (SIGHUP === $signal)
{ //Restart the daemon
$this->on_stop();
$this->on_start();
}
else if ($signal == SIGCHLD) //On daemon child stopping
{
elseif (SIGCHLD === $signal)
{ //On daemon child stopping
pcntl_waitpid(-1, $status, WNOHANG);
}
else //All the other signals
{
$this->handle_other_signals($signal);
}
else
{ //All the other signals
$this->handle_other_signals($signal);
}
}
/**
* Launch the infinite loop executing the "run" abstract method
*/
protected function start ()
/**
* Launch the infinite loop executing the "run" abstract method.
*/
protected function start()
{
//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;
}
//If we must make the daemon independant from any parent, we do a fork and die operation
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
if ($pid == -1) //Impossible to run script
{
$this->logger->critical("Impossible to create a subprocess.");
if (-1 === $pid)
{ //Impossible to run script
$this->logger->critical('Impossible to create a subprocess.');
return false;
}
elseif ($pid) //Current script
{
if ($pid)
{ //Current script
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
$sid = posix_setsid(); //Try to make the child process a main process
if ($sid == -1) //Error
{
$this->logger->critical("Cannot make the child process with pid $pid independent.");
if (-1 === $sid)
{ //Error
$this->logger->critical("Cannot make the child process with pid {$pid} independent.");
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
if (!file_exists($this->pid_dir))
@ -140,23 +137,21 @@ abstract class AbstractDaemon
$success = mkdir($this->pid_dir, 0777, true);
if (!$success)
{
$this->logger->critical('Cannot create PID directory : ' . $this->pid_dir);
$this->logger->critical('Cannot create PID directory : '.$this->pid_dir);
exit(2);
}
}
//Set process name
cli_set_process_title($this->name);
//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
$this->on_start();
try
try
{
while ($this->is_running)
{
@ -166,51 +161,56 @@ abstract class AbstractDaemon
}
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();
//Delete pid file
if (file_exists($this->pid_dir . '/' . $this->name . '.pid'))
if (file_exists($this->pid_dir.'/'.$this->name.'.pid'))
{
unlink($this->pid_dir . '/' . $this->name . '.pid');
unlink($this->pid_dir.'/'.$this->name.'.pid');
}
}
/**
* True if the daemon is running
*/
public function is_running()
{
return $this->is_running;
}
/**
* Override to implement the code that run infinetly (actually, it run one time but repeat the operation infinetly
*/
protected abstract function run();
/**
* Override to execute code before the ''run'' method on daemon start
*/
protected abstract function on_start();
/**
* Override to execute code after the ''run'' method on daemon shutdown
*/
protected abstract function on_stop();
/**
* Override to handle additional POSIX signals
*
* @param int $signal : Signal sent by interrupt
*/
protected abstract function handle_other_signals(int $signal);
* Override to implement the code that run infinetly (actually, it run one time but repeat the operation infinetly.
*/
abstract protected function run();
/**
* Override to execute code before the ''run'' method on daemon start.
*/
abstract protected function on_start();
/**
* Override to execute code after the ''run'' method on daemon shutdown.
*/
abstract protected function on_stop();
/**
* Override to handle additional POSIX signals.
*
* @param int $signal : Signal sent by interrupt
*/
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
/*
* 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;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Main daemon class
* Main daemon class.
*/
class Launcher extends AbstractDaemon
{
@ -16,10 +26,10 @@ class Launcher extends AbstractDaemon
public function __construct()
{
$name = "RaspiSMS Daemon Launcher";
$name = 'RaspiSMS Daemon Launcher';
$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;
$no_parent = true; //Launcher should be rattach to PID 1
$additional_signals = [];
@ -31,14 +41,12 @@ class Launcher extends AbstractDaemon
parent::start();
}
public function run()
{
//Create the internal controllers
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$this->internal_phone = new \controllers\internals\Phone($this->bdd);
$this->start_sender_daemon();
$this->start_webhook_daemon();
@ -48,17 +56,15 @@ class Launcher extends AbstractDaemon
sleep(1);
}
/**
* Function to start sender daemon
* @return void
* Function to start sender daemon.
*/
public function start_sender_daemon ()
public function start_sender_daemon()
{
$name = 'RaspiSMS Daemon Sender';
$pid_file = PWD_PID . '/' . $name . '.pid';
$pid_file = PWD_PID.'/'.$name.'.pid';
if (file_exists($pid_file))
{
return false;
@ -66,66 +72,60 @@ class Launcher extends AbstractDaemon
//Create a new daemon for sender
$pid = null;
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
* @return void
* Function to start webhook daemon.
*/
public function start_webhook_daemon ()
public function start_webhook_daemon()
{
$name = 'RaspiSMS Daemon Webhook';
$pid_file = PWD_PID . '/' . $name . '.pid';
$pid_file = PWD_PID.'/'.$name.'.pid';
if (file_exists($pid_file))
{
return false;
}
//Create a new daemon for webhook
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
* @return void
*/
public function start_phones_daemons (array $phones)
public function start_phones_daemons(array $phones)
{
foreach ($phones as $phone)
{
$phone_name = 'RaspiSMS Daemon Phone ' . $phone['number'];
$pid_file = PWD_PID . '/' . $phone_name . '.pid';
$phone_name = 'RaspiSMS Daemon Phone '.$phone['number'];
$pid_file = PWD_PID.'/'.$phone_name.'.pid';
if (file_exists($pid_file))
{
continue;
}
//Create a new daemon for the phone
exec('php ' . PWD . '/console.php controllers/internals/Console.php phone --id_phone=\'' . $phone['id'] . '\' > /dev/null 2>&1 &');
exec('php '.PWD.'/console.php controllers/internals/Console.php phone --id_phone=\''.$phone['id'].'\' > /dev/null 2>&1 &');
}
}
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)
{
$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
/*
* 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;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Phone daemon class
* Phone daemon class.
*/
class Phone extends AbstractDaemon
{
@ -18,17 +28,18 @@ class Phone extends AbstractDaemon
private $bdd;
/**
* Constructor
* Constructor.
*
* @param array $phone : A phone table entry
*/
public function __construct(array $phone)
{
$this->phone = $phone;
$this->msg_queue_id = (int) mb_substr($this->phone['number'], 1);
$name = 'RaspiSMS Daemon Phone ' . $this->phone['number'];
$name = 'RaspiSMS Daemon Phone '.$this->phone['number'];
$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;
$no_parent = false; //Phone should be rattach to manager, so manager can stop him easily
$additional_signals = [];
@ -36,22 +47,21 @@ class Phone extends AbstractDaemon
//Construct the daemon
parent::__construct($name, $logger, $pid_dir, $no_parent, $additional_signals, $uniq);
parent::start();
}
public function run()
{
//Stop after 5 minutes of inactivity to avoid useless daemon
if ( (microtime(true) - $this->last_message_at) > 5 * 60 )
if ((microtime(true) - $this->last_message_at) > 5 * 60)
{
posix_kill(getmypid(), SIGTERM); //Send exit signal to the current process
return false;
}
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
//Send smss in queue
$this->send_smss();
@ -61,37 +71,67 @@ class Phone extends AbstractDaemon
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()
{
$find_message = true;
while ($find_message)
{
//Call message
//Call message
$msgtype = null;
$maxsize = 409600;
$message = 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;
}
if (!$message)
{
$find_message = false;
continue;
}
$internal_sended = new \controllers\internals\Sended($this->bdd);
//Update last message time
$this->last_message_at = microtime(true);
@ -99,14 +139,15 @@ class Phone extends AbstractDaemon
$at = $now->format('Y-m-d H:i:s');
$message['at'] = $at;
$this->logger->info('Try send message : ' . json_encode($message));
$this->logger->info('Try send message : '.json_encode($message));
$sended_sms_uid = $this->adapter->send($message['destination'], $message['text'], $message['flash']);
if (!$sended_sms_uid)
{
$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');
continue;
}
@ -115,21 +156,20 @@ class Phone extends AbstractDaemon
$user_settings = $internal_setting->gets_for_user($this->phone['id_user']);
$this->process_for_webhook($message, 'send_sms', $user_settings);
$this->logger->info('Successfully send message : ' . json_encode($message));
$this->logger->info('Successfully send message : '.json_encode($message));
$internal_sended->create($at, $message['text'], $message['origin'], $message['destination'], $sended_sms_uid, $this->phone['adapter'], $message['flash']);
}
}
/**
* Read smss for a number
* Read smss for a number.
*/
private function read_smss ()
private function read_smss()
{
$internal_received = new \controllers\internals\Received($this->bdd);
$internal_setting = new \controllers\internals\Setting($this->bdd);
$smss = $this->adapter->read();
if (!$smss)
{
@ -142,7 +182,7 @@ class Phone extends AbstractDaemon
//Process smss
foreach ($smss as $sms)
{
$this->logger->info('Receive message : ' . json_encode($sms));
$this->logger->info('Receive message : '.json_encode($sms));
$command_result = $this->process_for_command($sms);
$this->logger->info('after command');
@ -156,17 +196,18 @@ class Phone extends AbstractDaemon
$internal_received->create($sms['at'], $sms['text'], $sms['origin'], $sms['destination'], 'unread', $is_command);
}
}
/**
* 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
*
* @return array : ['text' => new sms text, 'is_command' => bool]
*/
private function process_for_command (array $sms)
private function process_for_command(array $sms)
{
$internal_command = new \controllers\internals\Command($this->bdd);
$is_command = false;
$command = $internal_command->check_for_command($this->phone['id_user'], $sms['text']);
if ($command)
@ -179,22 +220,22 @@ class Phone extends AbstractDaemon
return ['text' => $sms['text'], 'is_command' => $is_command];
}
/**
* Process a sms to transmit a webhook query to webhook daemon if needed
* @param array $sms : The sms
* @param string $webhook_type : Type of webhook to trigger
* @param array $user_settings : Use settings
* Process a sms to transmit a webhook query to webhook daemon if needed.
*
* @param array $sms : The sms
* @param string $webhook_type : Type of webhook to trigger
* @param array $user_settings : Use settings
*/
private function process_for_webhook (array $sms, string $webhook_type, array $user_settings)
private function process_for_webhook(array $sms, string $webhook_type, array $user_settings)
{
if (!$user_settings['webhook'])
{
return false;
}
$internal_webhook = new \controllers\internals\Webhook($this->bdd);
$webhooks = $internal_webhook->gets_for_type_and_user($this->phone['id_user'], $webhook_type);
foreach ($webhooks as $webhook)
{
@ -210,21 +251,21 @@ class Phone extends AbstractDaemon
];
$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)
{
$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
* @param array $sms : The sms
* Process a sms to transfer it by mail.
*
* @param array $sms : The sms
* @param array $user_settings : Use settings
*/
private function process_for_transfer (array $sms, array $user_settings)
private function process_for_transfer(array $sms, array $user_settings)
{
if (!$user_settings['transfer'])
{
@ -238,41 +279,9 @@ class Phone extends AbstractDaemon
{
return false;
}
$this->logger->info('Transfer sms to ' . $user['email'] . ' : ' . json_encode($sms));
$this->logger->info('Transfer sms to '.$user['email'].' : '.json_encode($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
/*
* 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;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Main daemon class
* Main daemon class.
*/
class Sender extends AbstractDaemon
{
@ -17,9 +27,9 @@ class Sender extends AbstractDaemon
public function __construct()
{
$name = "RaspiSMS Daemon Sender";
$name = 'RaspiSMS Daemon Sender';
$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;
$no_parent = false; //Webhook should be rattach to manager, so manager can stop him easily
$additional_signals = [];
@ -31,7 +41,6 @@ class Sender extends AbstractDaemon
parent::start();
}
public function run()
{
//Create the internal controllers
@ -44,12 +53,12 @@ class Sender extends AbstractDaemon
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
*/
public function transmit_smss (array $smss) : void
public function transmit_smss(array $smss): void
{
foreach ($smss as $sms)
{
@ -75,29 +84,26 @@ class Sender extends AbstractDaemon
}
}
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');
}
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
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);
}
}
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
/*
* 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;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Phone daemon class
* Phone daemon class.
*/
class Webhook extends AbstractDaemon
{
@ -16,14 +26,15 @@ class Webhook extends AbstractDaemon
private $bdd;
/**
* Constructor
* Constructor.
*
* @param array $phone : A phone table entry
*/
public function __construct()
{
$name = "RaspiSMS Daemon Webhook";
$name = 'RaspiSMS Daemon Webhook';
$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;
$no_parent = false; //Sended should be rattach to manager, so manager can stop him easily
$additional_signals = [];
@ -35,13 +46,12 @@ class Webhook extends AbstractDaemon
parent::start();
}
public function run()
{
$find_message = true;
while ($find_message)
{
//Call message
//Call message
$msgtype = null;
$maxsize = 409600;
$message = null;
@ -50,16 +60,17 @@ class Webhook extends AbstractDaemon
$success = msg_receive($this->webhook_queue, QUEUE_TYPE_WEBHOOK, $msgtype, $maxsize, $message, true, 0, $error_code);
if (!$success)
{
$this->logger->critical('Error for webhook queue reading, error code : ' . $error_code);
$this->logger->critical('Error for webhook queue reading, error code : '.$error_code);
}
if (!$message)
{
$find_message = false;
continue;
}
$this->logger->info('Trigger webhook : ' . json_encode($message));
$this->logger->info('Trigger webhook : '.json_encode($message));
//Do the webhook http query
$curl = curl_init();
@ -74,30 +85,27 @@ class Webhook extends AbstractDaemon
usleep(0.5 * 1000000);
}
public function on_start()
{
//Set last message at to construct time
$this->last_message_at = microtime(true);
$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
$this->logger->info("Closing queue : " . QUEUE_ID_WEBHOOK);
$this->logger->info('Closing queue : '.QUEUE_ID_WEBHOOK);
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)
{
$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
{
/**
* Return table name
* @return string
* Return table name.
*
* @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
{
/**
* Return table name
* @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 string $name : Group name
* Return a conditional group by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Group name
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'conditional_group';
}
}

View File

@ -14,32 +14,38 @@ namespace models;
class Contact extends StandardModel
{
/**
* Return table name
* @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 string $number : Contact number
* Return a contact by his number for a user.
*
* @param int $id_user : User id
* @param string $number : Contact number
*
* @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)
{
return $this->_select_one($this->get_table_name(), ['id_user' => $id_user, 'number' => $number]);
}
/**
* Return a contact by his name for a user
* @param int $id_user : User id
* @param string $name : Contact name
* Return a contact by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Contact name
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'contact';
}
}

View File

@ -14,20 +14,25 @@ namespace models;
class Event extends StandardModel
{
/**
* Return table name
* @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
* Gets lasts x events for a user order by date.
*
* @param int $id_user : User id
* @param int $nb_entry : Number of events to return
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'event';
}
}

View File

@ -14,54 +14,53 @@ namespace models;
class Group extends StandardModel
{
/**
* Return table name
* @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 string $name : Group name
* Return a group by his name for a user.
*
* @param int $id_user : User id
* @param string $name : Group name
*
* @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]);
}
/**
* Delete relations between group and contacts for a group
* Delete relations between group and contacts for a group.
*
* @param int $id_group : Group id
*
* @return int : Number of deleted rows
*/
public function delete_group_contact_relations (int $id_group)
public function delete_group_contact_relations(int $id_group)
{
return $this->_delete('group_contact', ['id_group' => $id_group]);
}
/**
* Insert a relation between a group and a contact
* @param int $id_group : Group id
* Insert a relation between a group and a contact.
*
* @param int $id_group : Group id
* @param int $id_contact : Contact id
*
* @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]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
}
/**
* Get groups contacts
* Get groups contacts.
*
* @param int $id_group : Group id
*
* @return array : Contacts of the group
*/
public function get_contacts (int $id_group)
public function get_contacts(int $id_group)
{
$query = '
SELECT *
@ -73,4 +72,14 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'group';
}
}

View File

@ -17,22 +17,17 @@ namespace models;
class Media extends StandardModel
{
/**
* Return table name
* @return string
*/
protected function get_table_name() : string { return 'media'; }
/**
* 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 : entry id
* @param int $id : entry id
*
* @return array
*/
public function get_for_user(int $id_user, int $id)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE id_scheduled IN (SELECT id FROM scheduled WHERE id_user = :id_user)
AND id = :id
';
@ -43,19 +38,21 @@ namespace models;
];
$receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? [];
}
/**
* Return all entries for a user
* Return all entries for a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user(int $id_user)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE id_scheduled IN (SELECT id FROM scheduled WHERE id_user = :id_user)
';
@ -65,25 +62,26 @@ namespace models;
$receiveds = $this->_run_query($query, $params);
}
/**
* Return a media for a user and a scheduled
* @param int $id_user : user id
* Return a media for a user and a scheduled.
*
* @param int $id_user : user id
* @param int $id_scheduled : scheduled id
*
* @return array
*/
public function get_for_scheduled_and_user(int $id_user, int $id_scheduled)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE id_scheduled IN (SELECT id FROM scheduled WHERE id_user = :id_user)
AND id_scheduled = :id_scheduled
';
$params = [
'id_user' => $id_user,
'id_scheduled' => $id_scheduled
'id_scheduled' => $id_scheduled,
];
$receiveds = $this->_run_query($query, $params);
@ -94,13 +92,13 @@ namespace models;
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 $limit : Max results to return
* @param int $offset : Number of results to ignore
* @param int $limit : Max results to return
* @param int $offset : Number of results to ignore
*/
public function list_for_user($id_user, $limit, $offset)
{
@ -110,7 +108,7 @@ namespace models;
$query = '
SELECT * FROM media
WHERE id_scheduled IN (SELECT id FROM scheduled WHERE id_user = :id_user)
LIMIT ' . $limit . ' OFFSET ' . $offset;
LIMIT '.$limit.' OFFSET '.$offset;
$params = [
'id_user' => $id_user,
@ -119,12 +117,13 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return a list of medias in a group of ids and for a user
* @param int $id_user : user id
* @param array $ids : ids of medias to find
* @return array
* Return a list of medias in a group of ids and for a user.
*
* @param int $id_user : user id
* @param array $ids : ids of medias to find
*
* @return array
*/
public function gets_in_for_user(int $id_user, $ids)
{
@ -137,15 +136,17 @@ namespace models;
$generated_in = $this->_generate_in_from_array($ids);
$query .= $generated_in['QUERY'];
$params = $generated_in['PARAMS'];
$params['id_user'] = $id_user;
$params['id_user'] = $id_user;
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 : Entry id
* @param int $id : Entry id
*
* @return int : Number of removed rows
*/
public function delete_for_user(int $id_user, int $id)
@ -157,15 +158,16 @@ namespace models;
';
$params = ['id_user' => $id_user, 'id' => $id];
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
* Delete a entry by his id for a user
* @param int $id_user : User id
* Delete a entry by his id for a user.
*
* @param int $id_user : User id
* @param int $id_scheduled : Scheduled id
*
* @return int : Number of removed rows
*/
public function delete_for_scheduled_and_user(int $id_user, int $id_scheduled)
@ -177,20 +179,20 @@ namespace models;
';
$params = ['id_user' => $id_user, 'id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
* Update a media sms for a user
* @param int $id_user : User id
* Update a media sms for a user.
*
* @param int $id_user : User id
* @param int $id : Entry id
* @param array $datas : datas to update
* @param array $datas : datas to update
*
* @return int : number of modified rows
*/
public function update_for_user (int $id_user, int $id, array $datas)
public function update_for_user(int $id_user, int $id, array $datas)
{
$params = [];
$sets = [];
@ -198,13 +200,13 @@ namespace models;
foreach ($datas as $label => $value)
{
$label = preg_replace('#[^a-zA-Z0-9_]#', '', $label);
$params['set_' . $label] = $value;
$sets[] = '`' . $label . '` = :set_' . $label . ' ';
$params['set_'.$label] = $value;
$sets[] = '`'.$label.'` = :set_'.$label.' ';
}
$query = '
UPDATE `media`
SET ' . implode(', ', $sets) . '
SET '.implode(', ', $sets).'
WHERE id = :id
AND id_scheduled IN (SELECT id FROM scheduled WHERE id_user = :id_user)
';
@ -214,11 +216,12 @@ namespace models;
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
*
* @return int : Number of media SMS for user
*/
public function count_for_user($id_user)
@ -235,4 +238,14 @@ namespace models;
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,31 +14,37 @@ namespace models;
class Phone extends StandardModel
{
/**
* Return table name
* @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 string $number : phone number
* Return a phone by his number and user.
*
* @param int $id_user : user id
* @param string $number : phone number
*
* @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)
{
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
*
* @return array
*/
public function get_by_number (string $number)
public function get_by_number(string $number)
{
return $this->_select_one('phone', ['number' => $number]);
}
/**
* Return table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'phone';
}
}

View File

@ -17,22 +17,17 @@ namespace models;
class Received extends StandardModel
{
/**
* Return table name
* @return string
*/
protected function get_table_name() : string { return 'received'; }
/**
* 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 : entry id
* @param int $id : entry id
*
* @return array
*/
public function get_for_user(int $id_user, int $id)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE destination IN (SELECT number FROM phone WHERE id_user = :id_user)
AND id = :id
';
@ -43,19 +38,21 @@ namespace models;
];
$receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? [];
}
/**
* Return all entries for a user
* Return all entries for a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user(int $id_user)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE destination IN (SELECT number FROM phone WHERE id_user = :id_user)
';
@ -66,12 +63,12 @@ namespace models;
$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 $limit : Max results to return
* @param int $offset : Number of results to ignore
* @param int $limit : Max results to return
* @param int $offset : Number of results to ignore
*/
public function list_for_user($id_user, $limit, $offset)
{
@ -81,7 +78,7 @@ namespace models;
$query = '
SELECT * FROM received
WHERE destination IN (SELECT number FROM phone WHERE id_user = :id_user)
LIMIT ' . $limit . ' OFFSET ' . $offset;
LIMIT '.$limit.' OFFSET '.$offset;
$params = [
'id_user' => $id_user,
@ -89,13 +86,13 @@ namespace models;
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 $limit : Max results to return
* @param int $offset : Number of results to ignore
* @param int $limit : Max results to return
* @param int $offset : Number of results to ignore
*/
public function list_unread_for_user($id_user, $limit, $offset)
{
@ -106,7 +103,7 @@ namespace models;
SELECT * FROM received
WHERE destination IN (SELECT number FROM phone WHERE id_user = :id_user)
AND status = \'unread\'
LIMIT ' . $limit . ' OFFSET ' . $offset;
LIMIT '.$limit.' OFFSET '.$offset;
$params = [
'id_user' => $id_user,
@ -115,12 +112,13 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return a list of receiveds in a group of ids and for a user
* @param int $id_user : user id
* @param array $ids : ids of receiveds to find
* @return array
* Return a list of receiveds in a group of ids and for a user.
*
* @param int $id_user : user id
* @param array $ids : ids of receiveds to find
*
* @return array
*/
public function gets_in_for_user(int $id_user, $ids)
{
@ -133,15 +131,17 @@ namespace models;
$generated_in = $this->_generate_in_from_array($ids);
$query .= $generated_in['QUERY'];
$params = $generated_in['PARAMS'];
$params['id_user'] = $id_user;
$params['id_user'] = $id_user;
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 : Entry id
* @param int $id : Entry id
*
* @return int : Number of removed rows
*/
public function delete_for_user(int $id_user, int $id)
@ -153,20 +153,20 @@ namespace models;
';
$params = ['id_user' => $id_user, 'id' => $id];
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
* Update a received sms for a user
* @param int $id_user : User id
* Update a received sms for a user.
*
* @param int $id_user : User id
* @param int $id : Entry id
* @param array $datas : datas to update
* @param array $datas : datas to update
*
* @return int : number of modified rows
*/
public function update_for_user (int $id_user, int $id, array $datas)
public function update_for_user(int $id_user, int $id, array $datas)
{
$params = [];
$sets = [];
@ -174,13 +174,13 @@ namespace models;
foreach ($datas as $label => $value)
{
$label = preg_replace('#[^a-zA-Z0-9_]#', '', $label);
$params['set_' . $label] = $value;
$sets[] = '`' . $label . '` = :set_' . $label . ' ';
$params['set_'.$label] = $value;
$sets[] = '`'.$label.'` = :set_'.$label.' ';
}
$query = '
UPDATE `received`
SET ' . implode(', ', $sets) . '
SET '.implode(', ', $sets).'
WHERE id = :id
AND destination IN (SELECT number FROM phone WHERE id_user = :id_user)
';
@ -196,11 +196,12 @@ namespace models;
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
*
* @return int : Number of received SMS for user
*/
public function count_for_user(int $id_user)
@ -217,11 +218,12 @@ namespace models;
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
*
* @return int : Number of received SMS for user
*/
public function count_unread_for_user(int $id_user)
@ -240,12 +242,13 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0;
}
/**
* Return x last receiveds message for a user, order by date
* @param int $id_user : User id
* Return x last receiveds message for a user, order by date.
*
* @param int $id_user : User id
* @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)
{
@ -256,7 +259,7 @@ namespace models;
FROM received
WHERE destination IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at ASC
LIMIT ' . $nb_entry;
LIMIT '.$nb_entry;
$params = [
'id_user' => $id_user,
@ -265,11 +268,12 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return receiveds for an origin and a user
* @param int $id_user : User id
* @param string $origin : Number who sent the message
* Return receiveds for an origin and a user.
*
* @param int $id_user : User id
* @param string $origin : Number who sent the message
*
* @return array
*/
public function gets_by_origin_and_user(int $id_user, string $origin)
@ -289,11 +293,12 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Get number of sended SMS for every date since a date for a specific user
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
* Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
*
* @return array
*/
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
*
* @return array
*/
public function get_discussions_for_user(int $id_user)
@ -336,13 +343,16 @@ namespace models;
';
$params = ['id_user' => $id_user];
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 $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
*/
public function get_since_by_date_for_user(int $id_user, $date)
@ -353,7 +363,7 @@ namespace models;
WHERE at > STR_TO_DATE(:date, '%Y-%m-%d %h:%i:%s')
AND destination IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at ASC";
$params = [
'date' => $date,
'id_user' => $id_user,
@ -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 $date : Date we want messages sinces
* @param string $origin : Origin number
*
* @return array
*/
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
* @param int $id_user : User id
* @param string $origin : Origin number
* Find destination of last received message for an origin and user.
*
* @param int $id_user : User id
* @param string $origin : Origin number
*
* @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 *
FROM received
WHERE origin = :origin
AND destination IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at DESC
LIMIT 0,1
";
';
$params = [
'origin' => $origin,
@ -413,6 +427,16 @@ namespace models;
$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
{
/**
* Return table name
* @return string
*/
protected function get_table_name() : string { return 'scheduled'; }
/**
* Return numbers for a scheduled message
* Return numbers for a scheduled message.
*
* @param int $id_scheduled : Scheduled id
*
* @return array
*/
public function get_numbers(int $id_scheduled)
@ -30,134 +25,152 @@ namespace models;
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
*
* @return array
*/
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)';
$params = ['id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params);
}
/**
* Return groups for a scheduled message
* Return groups for a scheduled message.
*
* @param int $id_scheduled : Scheduled id
*
* @return array
*/
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)';
$params = ['id_scheduled' => $id_scheduled];
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
*
* @return array
*/
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)';
$params = ['id_scheduled' => $id_scheduled];
return $this->_run_query($query, $params);
}
/**
* Insert a number for a scheduled
* @param int $id_scheduled : Scheduled id
* @param string $number : Number
* Insert a number for a scheduled.
*
* @param int $id_scheduled : Scheduled id
* @param string $number : Number
*
* @return mixed (bool|int) : False on error, new row id else
*/
public function insert_scheduled_number(int $id_scheduled, string $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_contact : Group id
* @param int $id_contact : Group id
*
* @return mixed (bool|int) : False on error, new row id else
*/
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]);
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_group : Group id
* @param int $id_group : Group id
*
* @return mixed (bool|int) : False on error, new row id else
*/
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]);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
}
/**
* Insert a relation between a scheduled and a conditional group
* @param int $id_scheduled : Scheduled id
* Insert a relation between a scheduled and a conditional group.
*
* @param int $id_scheduled : Scheduled id
* @param int $id_conditional_group : Group id
*
* @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)
{
$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
*
* @return mixed int : Number of deleted rows
*/
public function delete_scheduled_numbers(int $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
*
* @return mixed int : Number of deleted rows
*/
public function delete_scheduled_contact_relations(int $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
*
* @return mixed int : Number of deleted rows
*/
public function delete_scheduled_group_relations(int $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
*
* @return mixed int : Number of deleted rows
*/
public function delete_scheduled_conditional_group_relations(int $id_scheduled)
@ -165,15 +178,16 @@ namespace models;
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 $date : Date before which we want messages
* @param string $number : Number for which we want messages
*
* @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)
{
$query = '
SELECT *
@ -220,14 +234,25 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Get scheduleds before a date
* Get scheduleds before a date.
*
* @param string $date : Date to get scheduleds before
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'scheduled';
}
}

View File

@ -17,22 +17,17 @@ namespace models;
class Sended extends StandardModel
{
/**
* Return table name
* @return string
*/
protected function get_table_name() : string { return 'sended'; }
/**
* 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 : entry id
* @param int $id : entry id
*
* @return array
*/
public function get_for_user(int $id_user, int $id)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE origin IN (SELECT number FROM phone WHERE id_user = :id_user)
AND id = :id
';
@ -43,19 +38,21 @@ namespace models;
];
$receiveds = $this->_run_query($query, $params);
return $receiveds[0] ?? [];
}
/**
* Return all entries for a user
* Return all entries for a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function gets_for_user(int $id_user)
{
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE origin IN (SELECT number FROM phone WHERE id_user = :id_user)
';
@ -65,13 +62,13 @@ namespace models;
$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 $limit : Max results to return
* @param int $offset : Number of results to ignore
* @param int $limit : Max results to return
* @param int $offset : Number of results to ignore
*/
public function list_for_user($id_user, $limit, $offset)
{
@ -81,7 +78,7 @@ namespace models;
$query = '
SELECT * FROM sended
WHERE origin IN (SELECT number FROM phone WHERE id_user = :id_user)
LIMIT ' . $limit . ' OFFSET ' . $offset;
LIMIT '.$limit.' OFFSET '.$offset;
$params = [
'id_user' => $id_user,
@ -90,12 +87,13 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return a list of sendeds in a group of ids and for a user
* @param int $id_user : user id
* @param array $ids : ids of sendeds to find
* @return array
* Return a list of sendeds in a group of ids and for a user.
*
* @param int $id_user : user id
* @param array $ids : ids of sendeds to find
*
* @return array
*/
public function gets_in_for_user(int $id_user, $ids)
{
@ -108,15 +106,17 @@ namespace models;
$generated_in = $this->_generate_in_from_array($ids);
$query .= $generated_in['QUERY'];
$params = $generated_in['PARAMS'];
$params['id_user'] = $id_user;
$params['id_user'] = $id_user;
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 : Entry id
* @param int $id : Entry id
*
* @return int : Number of removed rows
*/
public function delete_for_user(int $id_user, int $id)
@ -128,20 +128,20 @@ namespace models;
';
$params = ['id_user' => $id_user, 'id' => $id];
return $this->_run_query($query, $params, self::ROWCOUNT);
}
/**
* Update a sended sms for a user
* @param int $id_user : User id
* Update a sended sms for a user.
*
* @param int $id_user : User id
* @param int $id : Entry id
* @param array $datas : datas to update
* @param array $datas : datas to update
*
* @return int : number of modified rows
*/
public function update_for_user (int $id_user, int $id, array $datas)
public function update_for_user(int $id_user, int $id, array $datas)
{
$params = [];
$sets = [];
@ -149,13 +149,13 @@ namespace models;
foreach ($datas as $label => $value)
{
$label = preg_replace('#[^a-zA-Z0-9_]#', '', $label);
$params['set_' . $label] = $value;
$sets[] = '`' . $label . '` = :set_' . $label . ' ';
$params['set_'.$label] = $value;
$sets[] = '`'.$label.'` = :set_'.$label.' ';
}
$query = '
UPDATE `sended`
SET ' . implode(', ', $sets) . '
SET '.implode(', ', $sets).'
WHERE id = :id
AND origin IN (SELECT number FROM phone WHERE id_user = :id_user)
';
@ -171,11 +171,12 @@ namespace models;
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
*
* @return int : Number of sended SMS for user
*/
public function count_for_user($id_user)
@ -193,12 +194,13 @@ namespace models;
return $this->_run_query($query, $params)[0]['nb'] ?? 0;
}
/**
* Return x last sendeds message for a user, order by date
* @param int $id_user : User id
* Return x last sendeds message for a user, order by date.
*
* @param int $id_user : User id
* @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)
{
@ -209,7 +211,7 @@ namespace models;
FROM sended
WHERE origin IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at ASC
LIMIT ' . $nb_entry;
LIMIT '.$nb_entry;
$params = [
'id_user' => $id_user,
@ -218,11 +220,12 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return sendeds for an destination and a user
* @param int $id_user : User id
* Return sendeds for an destination and a user.
*
* @param int $id_user : User id
* @param string $destination : Number who sent the message
*
* @return array
*/
public function gets_by_destination_and_user(int $id_user, string $destination)
@ -241,12 +244,13 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Return sended for an uid and an adapter
* @param string $uid : Uid of the sended
* Return sended for an uid and an adapter.
*
* @param string $uid : Uid of the sended
* @param string $adapter : Adapter used to send the message
*
* @return array
*/
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
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
* Get number of sended SMS for every date since a date for a specific user.
*
* @param int $id_user : user id
* @param \DateTime $date : Date since which we want the messages
*
* @return array
*/
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 int $id_user : User id
*
* @return array : Tableau avec tous les SMS depuis la date
*/
public function get_since_by_date_for_user($date, $id_user)
@ -292,7 +300,7 @@ namespace models;
WHERE at > STR_TO_DATE(:date, '%Y-%m-%d %h:%i:%s')
AND origin IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at ASC";
$params = [
'date' => $date,
'id_user' => $id_user,
@ -300,24 +308,25 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Find last sended message for a destination and user
* @param int $id_user : User id
* Find last sended message for a destination and user.
*
* @param int $id_user : User id
* @param string $destination : Destination number
*
* @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 *
FROM sended
WHERE destination = :destination
AND origin IN (SELECT number FROM phone WHERE id_user = :id_user)
ORDER BY at DESC
LIMIT 0,1
";
';
$params = [
'destination' => $destination,
@ -326,7 +335,16 @@ namespace models;
$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
{
/**
* Return table 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 string $name : setting name
* @param mixed $value : new value of the setting
* Update a setting for a user by his name.
*
* @param int $id_user : user id
* @param string $name : setting name
* @param mixed $value : new value of the setting
*
* @return int : number of modified settings
*/
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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'setting';
}
}

View File

@ -14,20 +14,25 @@ namespace models;
class SmsStop extends StandardModel
{
/**
* Return table name
* @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 string $number : phone number
* Return a smsstop by his number and user.
*
* @param int $id_user : user id
* @param string $number : phone number
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'smsstop';
}
}

View File

@ -13,52 +13,50 @@ namespace models;
/**
* 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
{
/**
* Return table name
* @return string
*/
abstract protected function get_table_name() : string;
/**
* Return all the entries
* Return all the entries.
*
* @return array
*/
public function get_all ()
public function get_all()
{
return $this->_select($this->get_table_name());
}
/**
* Return an entry by his id
* Return an entry by his id.
*
* @param int $id : entry id
*
* @return array
*/
public function get(int $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 : entry id
* @param int $id : entry id
*
* @return array
*/
public function get_for_user(int $id_user, int $id)
{
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
*
* @return array
*/
public function gets_for_user(int $id_user)
@ -66,25 +64,27 @@ namespace models;
return $this->_select($this->get_table_name(), ['id_user' => $id_user]);
}
/**
* Return a list of entries for a user
* @param int $id_user : user id
* @param int $limit : Number of entry to return
* @param int $offset : Number of entry to ignore
* Return a list of entries for a user.
*
* @param int $id_user : user id
* @param int $limit : Number of entry to return
* @param int $offset : Number of entry to ignore
*
* @return array
*/
public function list_for_user (int $id_user, $limit, $offset)
public function list_for_user(int $id_user, $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
* @param int $id_user : user id
* @param array $ids : ids of entries to find
* @return array
* Return a list of entries in a group of ids and for a user.
*
* @param int $id_user : user id
* @param array $ids : ids of entries to find
*
* @return array
*/
public function gets_in_for_user(int $id_user, $ids)
{
@ -92,9 +92,9 @@ namespace models;
{
return [];
}
$query = '
SELECT * FROM `' . $this->get_table_name() . '`
SELECT * FROM `'.$this->get_table_name().'`
WHERE id_user = :id_user
AND id ';
@ -110,22 +110,24 @@ namespace models;
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 : Entry id
* @param int $id : Entry id
*
* @return int : Number of removed rows
*/
public function delete_for_user(int $id_user, int $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
*
* @return int : Number of removed rows
*/
public function delete(int $id)
@ -133,24 +135,26 @@ namespace models;
return $this->_delete($this->get_table_name(), ['id' => $id]);
}
/**
* Insert a entry
* Insert a entry.
*
* @param array $entry : Entry to insert
*
* @return mixed bool|int : false on error, new entry id else
*/
public function insert($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
* @param int $id_user : User id
* Update a entry for a user.
*
* @param int $id_user : User id
* @param int $id : Entry id
* @param array $datas : datas to update
* @param array $datas : datas to update
*
* @return int : number of modified rows
*/
@ -158,11 +162,11 @@ namespace models;
{
return $this->_update($this->get_table_name(), $entry, ['id_user' => $id_user, 'id' => $id]);
}
/**
* Update a entry by his id
* @param int $id : Entry id
* Update a entry by his id.
*
* @param int $id : Entry id
* @param array $datas : datas to update
*
* @return int : number of modified rows
@ -172,14 +176,22 @@ namespace models;
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
*
* @return int : number of entries
*/
public function count_for_user(int $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,34 +12,37 @@
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
{
/**
* Find a user by his id
* Find a user by his id.
*
* @param string $id : User id
*
* @return mixed array
*/
public function get ($id)
public function get($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
*
* @return mixed array
*/
public function get_by_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
*
* @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 list of user.
*
@ -61,7 +63,6 @@ namespace models;
return $this->_select('user', [], null, false, $limit, $offset);
}
/**
* Retourne une liste de useres sous forme d'un tableau.
*
@ -75,23 +76,26 @@ namespace models;
return $this->_delete('user', ['id' => $id]);
}
/**
* Insert a new user
* Insert a new user.
*
* @param array $user : User to insert
*
* @return mixed bool|int : false if fail, new user id else
*/
public function insert($user)
{
$success = $this->_insert('user', $user);
return ($success ? $this->_last_id() : false);
return $success ? $this->_last_id() : false;
}
/**
* Update a user using his is
* @param int $id : User id
* Update a user using his is.
*
* @param int $id : User id
* @param array $datas : Datas to update
*
* @return int : number of modified rows
*/
public function update($id, $datas)
@ -99,11 +103,12 @@ namespace models;
return $this->_update('user', $datas, ['id' => $id]);
}
/**
* Update a user password by his id.
*
* @param int $id : User id
* @param array $password : The new password of the user
*
* @return int : Number of modified lines
*/
public function update_password($id, $password)
@ -111,11 +116,12 @@ namespace models;
return $this->_update('user', ['password' => $password], ['id' => $id]);
}
/**
* Update a user email by his id.
*
* @param int $id : User id
* @param array $email : The new email
*
* @return int : Number of modified lines
*/
public function update_email($id, $email)

View File

@ -14,20 +14,25 @@ namespace models;
class Webhook extends StandardModel
{
/**
* Return table name
* @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 string $type : Webhook type
* Find all webhooks for a user and for a type of webhook.
*
* @param int $id_user : User id
* @param string $type : Webhook type
*
* @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 table name.
*
* @return string
*/
protected function get_table_name(): string
{
return 'webhook';
}
}

View File

@ -15,11 +15,15 @@
$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__ . '/../../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 = [
'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__ . '/../../daemons/',
'php ' . __DIR__ . '/php-cs-fixer.phar --config="' . __DIR__ . '/php_cs.config" fix ' . __DIR__ . '/../../adapters/',
];