Add files via upload

This commit is contained in:
Giandonato Inverso
2020-09-08 18:09:19 +02:00
committed by GitHub
parent 97df13f3f0
commit 86f32b6327
83 changed files with 12716 additions and 0 deletions
@@ -0,0 +1,294 @@
<?php
/**
* PHP Dynamic Qr code
*
* @author Giandonato Inverso <info@giandonatoinverso.it>
* @copyright Copyright (c) 2020-2021
* @license https://opensource.org/licenses/MIT MIT License
* @link https://github.com/giandonatoinverso/PHP-Dynamic-Qr-code
* @version 1.0
*/
require_once 'config/config.php';
class Dynamic_Qrcode
{
/**
*
*/
public function __construct()
{
}
/**
*
*/
public function __destruct()
{
}
/**
* Set friendly columns\' names to order tables\' entries
* N.B. This function is called to generate the "list all" table
*/
public function setOrderingValues()
{
$ordering = [
'id' => 'ID',
'filename' => 'File Name',
'identifier' => 'Identifier',
'link' => 'Link',
'qrcode' => 'Qr Code',
'created_at' => 'Created at',
'updated_at' => 'Updated at'
];
return $ordering;
}
/**
* This private function is used by both add () and edit () of this class to initially store in the array that will be sent to the database the:
* filename, created_at, link
*/
private function collect()
{
$data_to_db['filename'] = htmlspecialchars($_POST['filename'], ENT_QUOTES, 'UTF-8');
$data_to_db['created_at'] = date('Y-m-d H:i:s');
$data_to_db['link'] = htmlspecialchars($_POST['link'], ENT_QUOTES, 'UTF-8');
return $data_to_db;
}
/**
* Set option for qr code like:
* Error Correction Level, size (default = 100), foreground, background
* return array of values
*/
private function setOptions()
{
$errorCorrectionLevel = 'L';
if (isset($_POST['level']) && in_array($_POST['level'], array('L','M','Q','H')))
$errorCorrectionLevel = $_POST['level'];
$size = 100;
if (isset($_POST['size']))
$size = min(max((int)$_POST['size'], 100), 1000);
$foreground = substr($_POST['foreground'], 1); // We eliminate the character "#" for the hexadecimal color
$background = substr($_POST['background'], 1);
//$logo = $_POST['optionlogo'];
return array(
"errorCorrectionLevel" => $errorCorrectionLevel,
"size" => $size,
"foreground" => $foreground,
"background" => $background,
//"optionlogo" => $logo,
);
}
/**
* Add qr code
* Check out http://goqr.me/api/ for more information
* We save the file obtained with the chosen name and in the selected folder
* We save into db the url of qrcode image
*/
public function add()
{
$data_to_db['created_by'] = $_SESSION['user_id'];
$data_to_db = $this->collect();
$data_to_db['format'] = $_POST['format'];
// for the identifier we create a random alphanumeric string through the function "randomString" in helpers.php > config.php
$data_to_db['identifier'] = randomString(rand(5,8));
$data_to_db['qrcode'] = $data_to_db['filename'].'.'.$data_to_db['format'];
$options = $this->setOptions();
if(!file_exists(DIRECTORY.$data_to_db['filename'].'.'.$data_to_db['format'])){
$content = file_get_contents('https://api.qrserver.com/v1/create-qr-code/?data='.READ_PATH.$data_to_db['identifier'].'&amp;&size='.$options['size'].'x'.$options['size'].'&ecc='.$options['errorCorrectionLevel'].'&margin=0&color='.$options['foreground'].'&bgcolor='.$options['background'].'&qzone=2'.'&format='.$data_to_db['format']);
$filename = DIRECTORY.$data_to_db['filename'].'.'.$data_to_db['format'];
try{
file_put_contents($filename, $content);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
// If you want you can customide qr code with logo
//$this->addLogo($data_to_db['qrcode'], $options['optionlogo']);
$db = getDbInstance();
$last_id = $db->insert('dynamic_qrcodes', $data_to_db);
}
else
$this->failure('You cannot create a new qr code with an existing name on the server!');
if ($last_id){
$this->success('Qr code added successfully!');
}
else{
echo 'Insert failed: ' . $db->getLastError();
exit();
}
}
/**
* Edit qr code
*
*/
public function edit()
{
$db = getDbInstance();
$dynamic_id = htmlspecialchars($_GET['dynamic_id'], ENT_QUOTES, 'UTF-8'); // get dynamic id
$old_filename = htmlspecialchars($_GET['filename'], ENT_QUOTES, 'UTF-8'); // get filename
$query = $db->query("SELECT format FROM dynamic_qrcodes WHERE id=$dynamic_id"); // get format
$format = $query[0]['format'];
$data_to_db = $this->collect();
$data_to_db['state'] = $_POST['state']; // update link state
$data_to_db['qrcode'] = $data_to_db['filename'].'.'.$format; // update qrcode in db
if(!file_exists(DIRECTORY.$data_to_db['filename'].'.'.$format) || $data_to_db['filename'] == $old_filename){
$db->where('id', $dynamic_id);
$stat = $db->update('dynamic_qrcodes', $data_to_db);
try{
rename(DIRECTORY.$old_filename.'.'.$format, DIRECTORY.$data_to_db['filename'].'.'.$format);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
}
else
$this->failure('You cannot edit a qr code with an existing name on the server!');
if ($stat){
$this->success('Qr code updated successfully!');
}
else{
echo 'Insert failed: ' . $db->getLastError();
exit();
}
}
/**
* Delete qr code
*
*/
public function cancel($dynamic_id, $filename)
{
if($_SESSION['admin_type']!='super')
$this->failure('You don\'t have permission to perform this action');
$db = getDbInstance();
$query = $db->query("SELECT format FROM dynamic_qrcodes WHERE id=$dynamic_id");
$format = $query[0]['format'];
$db->where('id', $dynamic_id);
$status = $db->delete('dynamic_qrcodes');
try{
unlink(DIRECTORY.$filename.'.'.$format);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
if ($status)
$this->info('Qr code deleted successfully!');
else
$this->failure('Unable to delete qr code');
}
/**
* Add logo
* IMPORTANT: I do not recommend to use this option because there may be problems with the scanning of the qr code as some readers may not recognize the code
*/
private function addLogo($src, $logo = 'none')
{
try
{
if($logo != 'none')
{
$logo = imagecreatefrompng($_SERVER['HTTP_HOST'].'/admin'.$logo);
$QR = imagecreatefrompng(BASE_PATH.$src);
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
// You can try also with imagecopymerge() with same arguments
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
//$output = Set directory for saving image;
header('Content-Type: image/png');
imagepng($QR /*, $output*/);
imagedestroy($QR);
}
}
catch(Exception $e)
{
$this->failure($e->getMessage());
}
}
/* FLASH MESSAGE */
/* 3 functions for 3 types of messages with different styles defined in the flash_message.php file
Each function takes a string as input and after a redirection it prints the desired message
*/
/**
* Flash message Failure process
*/
private function failure($message)
{
$_SESSION['failure'] = $message;
// Redirect to the listing page
header('Location: dynamic_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Success process
*/
private function success($message)
{
$_SESSION['success'] = $message;
// Redirect to the listing page
header('Location: dynamic_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Info process
*/
private function info($message)
{
$_SESSION['info'] = $message;
// Redirect to the listing page
header('Location: dynamic_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
}
?>
+157
View File
@@ -0,0 +1,157 @@
<?php
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*
* ICS.php
* =============================================================================
* Use this class to create an .ics file.
*
*
* Usage
* -----------------------------------------------------------------------------
* Basic usage - generate ics file contents (see below for available properties):
* $ics = new ICS($props);
* $ics_file_contents = $ics->to_string();
*
* Setting properties after instantiation
* $ics = new ICS();
* $ics->set('summary', 'My awesome event');
*
* You can also set multiple properties at the same time by using an array:
* $ics->set(array(
* 'dtstart' => 'now + 30 minutes',
* 'dtend' => 'now + 1 hour'
* ));
*
* Available properties
* -----------------------------------------------------------------------------
* description
* String description of the event.
* dtend
* A date/time stamp designating the end of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* dtstart
* A date/time stamp designating the start of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* location
* String address or description of the location of the event.
* summary
* String short summary of the event - usually used as the title.
* url
* A url to attach to the the event. Make sure to add the protocol (http://
* or https://).
*/
class ICS {
const DT_FORMAT = 'Ymd\THis\Z';
protected $properties = array();
private $available_properties = array(
'description',
'dtend',
'dtstart',
'location',
'summary',
'url'
);
public function __construct($props) {
$this->set($props);
}
public function set($key, $val = false) {
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($k, $v);
}
} else {
if (in_array($key, $this->available_properties)) {
$this->properties[$key] = $this->sanitize_val($val, $key);
}
}
}
public function to_string() {
$rows = $this->build_props();
return implode("\r\n", $rows);
}
private function build_props() {
// Build ICS properties - add header
$ics_props = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN',
'CALSCALE:GREGORIAN',
'BEGIN:VEVENT'
);
// Build ICS properties - add header
$props = array();
foreach($this->properties as $k => $v) {
$props[strtoupper($k . ($k === 'url' ? ';VALUE=URI' : ''))] = $v;
}
// Set some default values
$props['DTSTAMP'] = $this->format_timestamp('now');
$props['UID'] = uniqid();
// Append properties
foreach ($props as $k => $v) {
$ics_props[] = "$k:$v";
}
// Build ICS properties - add footer
$ics_props[] = 'END:VEVENT';
$ics_props[] = 'END:VCALENDAR';
return $ics_props;
}
private function sanitize_val($val, $key = false) {
switch($key) {
case 'dtend':
case 'dtstamp':
case 'dtstart':
$val = $this->format_timestamp($val);
break;
default:
$val = $this->escape_string($val);
}
return $val;
}
private function format_timestamp($timestamp) {
$dt = new DateTime($timestamp);
return $dt->format(self::DT_FORMAT);
}
private function escape_string($str) {
return preg_replace('/([\,;])/','\\\$1', $str);
}
}
File diff suppressed because it is too large Load Diff
+593
View File
@@ -0,0 +1,593 @@
<?php
/**
* PHP Dynamic Qr code
*
* @author Giandonato Inverso <info@giandonatoinverso.it>
* @copyright Copyright (c) 2020-2021
* @license https://opensource.org/licenses/MIT MIT License
* @link https://github.com/giandonatoinverso/PHP-Dynamic-Qr-code
* @version 1.0
*/
require_once 'config/config.php';
require_once BASE_PATH . '/lib/ICS/ICS.php';
require_once BASE_PATH . '/lib/vCard/vCard.php';
class Static_Qrcode
{
private $sData; // Data for the qr code
private $sContent; // Content to be stored in the database
/**
*
*/
public function __construct()
{
}
/**
*
*/
public function __destruct()
{
}
/**
* Set friendly columns\' names to order tables\' entries
*/
public function setOrderingValues()
{
$ordering = [
'id' => 'ID',
'filename' => 'File Name',
'type' => 'Type',
'content' => 'Content',
'qrcode' => 'Qr Code',
'created_at' => 'Created at',
'updated_at' => 'Updated at'
];
return $ordering;
}
/**
* create a qr code of type "text"
* @string text -> required
*/
public function textQrcode($text)
{
if($text != NULL){
$this->sData = $text;
$this->sContent = '<strong>Text:</strong> '.$text;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "emai"
* @string email -> required
* @string subject
* @string message -> required
*/
public function emailQrcode($email, $subject, $message)
{
if($email != NULL && $message != NULL){
$this->sData = 'MATMSG:TO:'.$email.';SUB:'.$subject.';BODY:'.$message.';';
$this->sContent = '<strong>Email:</strong> '.$email.'<br>'.'<strong>Subject:</strong> '.$subject.'<br>'.'<strong>Message:</strong> '.$message;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "phone"
* @int country code -> required
* @string phone number -> required
*/
public function phoneQrcode($country_code, $phone_number)
{
if($phone_number != NULL){
$this->sData = 'TEL:'.$country_code.$phone_number;
$this->sContent = '<strong>Phone number:</strong> '.$country_code.$phone_number;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "sms"
* @int country code -> required
* @string phone number -> required
* @string message -> required
*/
public function smsQrcode($country_code, $phone_number, $message)
{
if($phone_number != NULL && $message != NULL){
$this->sData = 'SMSTO:'.$country_code.$phone_number.':'.$message;
$this->sContent = '<strong>Phone number:</strong> '.$country_code.$phone_number.'<br>'.'<strong>Message:</strong> '.$message;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "whatsapp"
* @int country code -> required
* @string phone number -> required
* @string message
*/
public function whatsappQrcode($country_code, $phone_number, $message)
{
if($phone_number != NULL){
$this->sData = 'https://wa.me/'.$country_code.$phone_number.'?text='.$message;
$this->sContent = '<strong>Phone number:</strong> '.$country_code.$phone_number.'<br>'.'<strong>Message:</strong> '.$message;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "skype"
* @string skype username -> required
*/
public function skypeQrcode($skype_username)
{
if($skype_username != NULL){
$this->sData = 'skype:'.$skype_username.'?call';
$this->sContent = '<strong>Skype username:</strong> '.$skype_username;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "location"
* @int latitude -> required
* @int longitude -> required
*/
public function locationQrcode($latitude, $longitude)
{
if($latitude != NULL && $longitude != NULL){
$this->sData = 'GEO:'.$latitude.','.$longitude.';';
$this->sContent = '<strong>Latitude:</strong> '.$latitude.'<br>'.'<strong>Longitude:</strong> '.$longitude;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "vcard"
*
*/
public function vcardQrcode($fullname, $nickname, $email, $website, $phone, $home_phone, $work_phone, $company, $role, $categories, $note, $photo, $address, $city, $postcode, $state)
{
if($fullname != NULL && $phone != NULL){
$vcard = new vCard;
$vcard->name($fullname);
$vcard->nickName($nickname);
$vcard->email($email);
$vcard->url($website);
$vcard->cellPhone($phone);
$vcard->homePhone($home_phone);
$vcard->workPhone($work_phone);
$vcard->organization($company);
$vcard->role($role);
$vcard->categories($categories);
$vcard->note($note);
$vcard->photo($photo);
$vcard->address($address, $city, $postcode, $state);
$vcard->create();
$this->sData = $vcard->get();
$this->sContent = '<div class="row"><div class="col-sm-4">';
$this->sContent .= '<strong>Full name:</strong> '.$fullname.'<br>'.'<strong>Nickname:</strong> '.$nickname.'<br>'.'<strong>Email:</strong> '.$email.'<br>'.'<strong>Website:</strong> '.$website.'</div>';
$this->sContent .= '<div class="col-sm-4">';
$this->sContent .= '<strong>Company:</strong> '.$company.'<br>'.'<strong>Role:</strong> '.$role.'<br>'.'<strong>Categories:</strong> '.$categories.'<br>'.'<strong>Note:</strong> '.$note.'</div>';
$this->sContent .= '<div class="col-sm-4">';
$this->sContent .= '<strong>Phone:</strong> '.$phone.'<br>'.'<strong>Home Phone:</strong> '.$home_phone.'<br>'.'<strong>Work phone:</strong> '.$work_phone.'<br>'.'<strong>Address:</strong> '.$address.'&nbsp;'.$city.'&nbsp;'.$postcode.'&nbsp;'.$state.'</div>';
$this->sContent .= '</div>';
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "event"
* @string description -> required
* @string start event -> required
* @string end event -> required
* @string location
* @string summary
* @string url
*/
public function eventQrcode($title, $start, $end, $location, $description, $url)
{
if($description != NULL && $start != NULL && $end != NULL){
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=invite.ics');
$ics = new ICS(array(
'location' => $location,
'description' => $description,
'dtstart' => $start,
'dtend' => $end,
'summary' => $title,
'url' => $url
));
$this->sData = $ics->to_string();
$this->sContent = '<div class="row"><div class="col-sm-4">';
$this->sContent .= '<strong>Title:</strong> '.$title.'<br>'.'<strong>Start event:</strong> '.$start.'<br>'.'<strong>End event:</strong> '.$end.'<br></div>';
$this->sContent .= '<div class="col-sm-4">';
$this->sContent .= '<strong>Location:</strong> '.$location.'<br>'.'<strong>Description:</strong> '.$description.'<br>'.'<strong>URL:</strong> '.$url.'</div>';
$this->sContent .= '</div>';
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "bookmark"
* @string title
* @string url -> required
*/
public function bookmarkQrcode($url, $title)
{
if($url != NULL){
$this->sData = 'MEBKM:TITLE:'.$title.';URL:'.$url.';';
$this->sContent = '<strong>Title:</strong> '.$title.'<br>'.'<strong>Url:</strong> '.$url;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "wifi"
* @string encryption -> required
* @string ssid -> required
* @string password
*/
public function wifiQrcode($encryption, $ssid, $password)
{
if($ssid != NULL){
$this->sData = 'WIFI:T:'.$encryption.';S:'.$ssid.';P:'.$password.';';
$this->sContent = '<strong>Encryption:</strong> '.$encryption.'<br>'.'<strong>SSID:</strong> '.$ssid.'<br>'.'<strong>Password:</strong> '.$password;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "paypal"
* @string payment type -> required
* @string email -> required
* @string item_name -> required
* @int item_id
* @int amount -> required
* @string currency -> required
* @int shipping
* @int tax_rate
*/
public function paypalQrcode($payment_type, $email, $item_name, $item_id, $amount, $currency, $shipping, $tax_rate)
{
if($email != NULL && $item_name != NULL && $amount != NULL){
$this->sData = 'https://www.paypal.com/webapps/xorouter?cmd='.$payment_type.'&business='.$email.'&item_name='.$item_name.'&item_number='.$item_id.'&amount='.$amount.'&currency_code='.$currency.'&shipping='.$shipping.'&tax_rate='.$tax_rate;
$this->sContent = '<div class="row"><div class="col-sm-4">';
$this->sContent .= '<strong>Payment type:</strong> '.$payment_type.'<br>'.'<strong>Email:</strong> '.$email.'<br>'.'<strong>Item name:</strong> '.$item_name.'<br>'.'<strong>Item id:</strong> '.$item_id.'</div>';
$this->sContent .= '<div class="col-sm-4">';
$this->sContent .= '<strong>Amount:</strong> '.$amount.'<br>'.'<strong>Currency:</strong> '.$currency.'<br>'.'<strong>Shipping:</strong> '.$shipping.'<br>'.'<strong>Tax rate:</strong> '.$tax_rate.'</div>';
$this->sContent .= '</div>';
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
* create a qr code of type "bitcoin"
* @string address -> required
* @int amount -> required
* @string label
* @string message
*/
public function bitcoinQrcode($address, $amount, $label, $message)
{
if($address != NULL && $amount != NULL){
$this->sData = 'bitcoin:'.$address.'?amount='.$amount.'&label='.$label.'&message='.$message;
$this->sContent = '<strong>BTC address:</strong> '.$address.'<br>'.'<strong>Amount:</strong> '.$amount.'<br>';
$this->sContent .= '<strong>Label:</strong> '.$label.'<br>'.'<strong>Message:</strong> '.$message;
$this->add($this->sData, $this->sContent);
}
else
$this->requiredFieldsError();
}
/**
This private function is used by both add () and edit () of this class to initially store in the array that will be sent to the database the:
* filename, created_at, type of qr code
* N.B. If the function is called from edit () the "type" field will not be taken as it cannot be modified
*/
private function collect()
{
$data_to_db['filename'] = htmlspecialchars($_POST['filename'], ENT_QUOTES, 'UTF-8');
$data_to_db['created_at'] = date('Y-m-d H:i:s');
if($_GET['type'] != NULL)
$data_to_db['type'] = htmlspecialchars($_GET['type']);
return $data_to_db;
}
/**
* Set option for qr code like:
* Error Correction Level, size (default = 100), foreground, background
* return array of values
*/
private function setOptions()
{
$errorCorrectionLevel = 'L';
if (isset($_POST['level']) && in_array($_POST['level'], array('L','M','Q','H')))
$errorCorrectionLevel = $_POST['level'];
$size = 100;
if (isset($_POST['size']))
$size = min(max((int)$_POST['size'], 100), 1000);
$foreground = substr($_POST['foreground'], 1); // We eliminate the character "#" for the hexadecimal color
$background = substr($_POST['background'], 1);
//$logo = $_POST['optionlogo'];
return array(
"errorCorrectionLevel" => $errorCorrectionLevel,
"size" => $size,
"foreground" => $foreground,
"background" => $background,
//"optionlogo" => $logo,
);
}
/**
* Add qr code
* Check out http://goqr.me/api/ for more information
* We save the file obtained with the chosen name and in the selected folder
* We save into db the url of qrcode image
*/
private function add($sData, $sContent)
{
$sData = urlencode($sData);
$data_to_db['created_by'] = $_SESSION['user_id'];
$data_to_db = $this->collect();
$data_to_db['format'] = $_POST['format'];
$data_to_db['qrcode'] = $data_to_db['filename'].'.'.$data_to_db['format'];
$data_to_db['content'] = $sContent;
$options = $this->setOptions();
if(!file_exists(DIRECTORY.$data_to_db['filename'].'.'.$data_to_db['format'])){
$content = file_get_contents('https://api.qrserver.com/v1/create-qr-code/?data='.$sData.'&amp;&size='.$options['size'].'x'.$options['size'].'&ecc='.$options['errorCorrectionLevel'].'&margin=0&color='.$options['foreground'].'&bgcolor='.$options['background'].'&qzone=2'.'&format='.$data_to_db['format']);
$filename = DIRECTORY.$data_to_db['filename'].'.'.$data_to_db['format'];
try{
file_put_contents($filename, $content);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
// If you want you can customide qr code with logo
//$this->addLogo($data_to_db['qrcode'], $options['optionlogo']);
$db = getDbInstance();
$last_id = $db->insert('static_qrcodes', $data_to_db);
}
else
$this->failure('You cannot create a new qr code with an existing name on the server!');
if ($last_id){
$this->success('Qr code added successfully!');
}
else{
echo 'Insert failed: ' . $db->getLastError();
exit();
}
}
/**
* Edit qr code
*
*/
public function edit()
{
$db = getDbInstance();
$static_id = htmlspecialchars($_GET['static_id'], ENT_QUOTES, 'UTF-8');
$old_filename = htmlspecialchars($_GET['filename'], ENT_QUOTES, 'UTF-8');
$query = $db->query("SELECT format FROM static_qrcodes WHERE id=$static_id"); // get format
$format = $query[0]['format'];
$data_to_db = $this->collect();
$data_to_db['qrcode'] = $data_to_db['filename'].'.'.$format; // update qrcode in db
if(!file_exists(DIRECTORY.$data_to_db['filename'].'.'.$format) || $data_to_db['filename'] == $old_filename){
$db->where('id', $static_id);
$stat = $db->update('static_qrcodes', $data_to_db);
try{
rename(DIRECTORY.$old_filename.'.'.$format, DIRECTORY.$data_to_db['filename'].'.'.$format);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
}
else
$this->failure('You cannot edit a qr code with an existing name on the server!');
if ($stat){
$this->success('Qr code updated successfully!');
}
else{
echo 'Insert failed: ' . $db->getLastError();
exit();
}
}
/**
* Delete qr code
*
*/
public function cancel($static_id, $filename)
{
if($_SESSION['admin_type']!='super')
$this->failure('You don\'t have permission to perform this action');
$db = getDbInstance();
$query = $db->query("SELECT format FROM static_qrcodes WHERE id=$static_id"); // get format
$format = $query[0]['format'];
$db->where('id', $static_id);
$status = $db->delete('static_qrcodes');
try{
unlink(DIRECTORY.$filename.'.'.$format);
}
catch(Exception $e){
$this->failure($e->getMessage());
}
if ($status)
$this->info('Qr code deleted successfully!');
else
$this->failure('Unable to delete qr code');
}
/**
* Add logo
* IMPORTANT: I do not recommend to use this option because there may be problems with the scanning of the qr code as some readers may not recognize the code
*/
private function addLogo($src, $logo = 'none')
{
try
{
if($logo != 'none')
{
$logo = imagecreatefrompng($_SERVER['HTTP_HOST'].'/admin'.$logo);
$QR = imagecreatefrompng(BASE_PATH.$src);
$QR_width = imagesx($QR);
$QR_height = imagesy($QR);
$logo_width = imagesx($logo);
$logo_height = imagesy($logo);
// Scale logo to fit in the QR Code
$logo_qr_width = $QR_width/3;
$scale = $logo_width/$logo_qr_width;
$logo_qr_height = $logo_height/$scale;
// You can try also with imagecopymerge() with same arguments
imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
//$output = Set directory for saving image;
header('Content-Type: image/png');
imagepng($QR /*, $output*/);
imagedestroy($QR);
}
}
catch(Exception $e)
{
$this->failure($e->getMessage());
}
}
/**
* Flash message Failure process
*/
private function failure($message)
{
$_SESSION['failure'] = $message;
// Redirect to the listing page
header('Location: static_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Success process
*/
private function success($message)
{
$_SESSION['success'] = $message;
// Redirect to the listing page
header('Location: static_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Info process
*/
private function info($message)
{
$_SESSION['info'] = $message;
// Redirect to the listing page
header('Location: static_qrcodes.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Error message if not filled in all the fields required by the type of the qr code
*/
private function requiredFieldsError()
{
$this->failure('The qr code cannot be created if you do not fill in all the required fields (*)');
}
}
?>
+185
View File
@@ -0,0 +1,185 @@
<?php
/**
* PHP Dynamic Qr code
*
* @author Giandonato Inverso <info@giandonatoinverso.it>
* @copyright Copyright (c) 2020-2021
* @license https://opensource.org/licenses/MIT MIT License
* @link https://github.com/giandonatoinverso/PHP-Dynamic-Qr-code
* @version 1.0
*/
require_once 'config/config.php';
class Users
{
/**
*
*/
public function __construct()
{
// Only super admin is allowed to access this page
if ($_SESSION['admin_type'] !== 'super')
$this->failure('Only a "super admin" account can access the admin listing page', 'Location: index.php');
}
/**
*
*/
public function __destruct()
{
}
/**
* Set friendly columns\' names to order tables\' entries
*/
public function setOrderingValues()
{
$ordering = [
'id' => 'ID',
'user_name' => 'Username',
'admin_type' => 'Admin Type'
];
return $ordering;
}
/**
* Collect input
*/
public function collect()
{
// Sanitize input post if we want
$data_to_db = filter_input_array(INPUT_POST);
return $data_to_db;
}
/**
* Check username
*/
public function check($data_to_db)
{
// Check whether the user name already exists
$db = getDbInstance();
$db->where('user_name', $data_to_db['user_name']);
$db->get('admin_accounts');
if ($db->count >= 1)
$this->failure('Username already exists');
}
/**
* Add user
*/
public function add()
{
$data_to_db = $this->collect();
$this->check($data_to_db);
// Encrypting the password
$data_to_db['password'] = password_hash($data_to_db['password'], PASSWORD_DEFAULT);
// Reset db instance
$db = getDbInstance();
$last_id = $db->insert('admin_accounts', $data_to_db);
if ($last_id)
$this->success('Admin user added successfully');
}
/**
* Edit user
*
*/
public function edit()
{
$data_to_db = $this->collect();
// Check whether the user name already exists
$db = getDbInstance();
$db->where('user_name', $data_to_db['user_name']);
$db->where('id', $admin_user_id, '!=');
$row = $db->getOne('admin_accounts');
if (!empty($row['user_name']))
{
$query_string = http_build_query(array(
'admin_user_id' => $admin_user_id,
'operation' => $operation,
));
$this->failure('Username already exists', 'Location: edit_admin.php?'.$query_string);
}
$admin_user_id = filter_input(INPUT_GET, 'admin_user_id', FILTER_VALIDATE_INT);
// Encrypting the password
$data_to_db['password'] = password_hash($data_to_db['password'], PASSWORD_DEFAULT);
// Reset db instance
$db = getDbInstance();
$db->where('id', $admin_user_id);
$stat = $db->update('admin_accounts', $data_to_db);
if ($stat)
$this->success('User updated successfully!');
else
$this->failure('Failed to update Admin user: ' . $db->getLastError());
}
/**
* Delete user
*
*/
public function cancel($del_id)
{
if($_SESSION['admin_type']!='super'){
header('HTTP/1.1 401 Unauthorized', true, 401);
exit("401 Unauthorized");
}
$db = getDbInstance();
$db->where('id', $del_id);
$stat = $db->delete('admin_accounts');
if ($stat)
$this->info('User deleted successfully!');
else
$this->failure('Unable to delete user');
}
/**
* Flash message Failure process
*/
public function failure($message, $location = 'Location: admin_users.php')
{
$_SESSION['failure'] = $message;
// Redirect to the listing page
header($location);
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Success process
*/
public function success($message)
{
$_SESSION['success'] = $message;
// Redirect to the listing page
header('Location: admin_users.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
/**
* Flash message Info process
*/
public function info($message)
{
$_SESSION['info'] = $message;
// Redirect to the listing page
header('Location: admin_users.php');
// Important! Don't execute the rest put the exit/die.
exit();
}
}
?>
+220
View File
@@ -0,0 +1,220 @@
<?php
/**
* @title QR Code
* @desc Compatible to vCard 4.0 or higher.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License <http://www.gnu.org/licenses/gpl.html>
* @version 1.2
*/
class vCard
{
private $sData;
/**
* Constructor.
*/
public function __construct()
{
$this->sData = 'BEGIN:VCARD'."\n";
$this->sData .= 'VERSION:4.0'."\n";
}
/**
* The name of the person.
*
* @param string $sName
*
* @return self
*/
public function name($sName)
{
$this->sData .= 'N:'.$sName."\n";
return $this;
}
/**
* @param string $sAddress
*
* @return self
*/
public function address($sAddress, $sCity, $sPostcode, $sState)
{
$this->sData .= 'ADR:;;'.$sAddress.';';
$this->sData .= $sCity.';'.$sPostcode.';'.$sState."\n";
return $this;
}
/**
* @param string $sNickname
*
* @return self
*/
public function nickName($sNickname)
{
$this->sData .= 'NICKNAME:'.$sNickname."\n";
return $this;
}
/**
* @param string $sMail
*
* @return self
*/
public function email($sMail)
{
$this->sData .= 'EMAIL;TYPE=PREF,INTERNET:'.$sMail."\n";
return $this;
}
/**
* @param string $sVal
*
* @return self
*/
public function workPhone($sVal)
{
$this->sData .= 'TEL;;TYPE=work:'.$sVal."\n";
return $this;
}
/**
* @param string $sVal
*
* @return self
*/
public function homePhone($sVal)
{
$this->sData .= 'TEL;;TYPE=home:'.$sVal."\n";
return $this;
}
/**
* @param string $sVal
*
* @return self
*/
public function cellPhone($sVal)
{
$this->sData .= 'TEL:'.$sVal."\n";
return $this;
}
/**
* @param string $sUrl
*
* @return self
*/
public function url($sUrl)
{
$sUrl = (substr($sUrl, 0, 4) != 'http') ? 'http://'.$sUrl : $sUrl;
$this->sData .= 'URL:'.$sUrl."\n";
return $this;
}
/**
* A list of "tags" that can be used to describe the object represented by this vCard.
*
* @param string $sCategories
*
* @return self
*/
public function categories($sCategories)
{
$this->sData .= 'CATEGORIES:'.$sCategories."\n";
return $this;
}
/**
* Photo (avatar).
*
* @param string $sImgUrl URL of the image.
*
* @return self
*
* @throws InvalidArgumentException If the image format is invalid.
*/
public function photo($sImgUrl)
{
if($sImgUrl != NULL){
$bIsImgExt = strtolower(substr(strrchr($sImgUrl, '.'), 1)); // Get the file extension.
if ($bIsImgExt == 'jpeg' || $bIsImgExt == 'jpg' || $bIsImgExt == 'png' || $bIsImgExt == 'gif') {
$sExt = strtoupper($bIsImgExt);
} else {
throw new InvalidArgumentException('Invalid format Image!');
}
$this->sData .= 'PHOTO;VALUE=URL;TYPE='.$sExt.':'.$sImgUrl."\n";
return $this;
}
}
/**
* The role, occupation, or business category of the vCard object within an organization.
*
* @param string $sRole e.g., Executive
*
* @return self
*/
public function role($sRole)
{
$this->sData .= 'ROLE:'.$sRole."\n";
return $this;
}
/**
* The organization / company.
*
* The name and optionally the unit(s) of the organization
* associated with the vCard object. This property is based on the X.520 Organization Name
* attribute and the X.520 Organization Unit attribute.
*
* @param string $sOrg e.g., Google;GMail Team;Spam Detection Squad
*
* @return self
*/
public function organization($sOrg)
{
$this->sData .= 'ORG:'.$sOrg."\n";
return $this;
}
/**
* The supplemental information or a comment that is associated with the vCard.
*
* @param string $sText
*
* @return self
*/
public function note($sText)
{
$this->sData .= 'NOTE:'.$sText."\n";
return $this;
}
/**
*
* @return self
*/
public function create()
{
$this->sData .= 'END:VCARD';
return $this;
}
/**
* Get the vCard data.
*/
public function get()
{
return $this->sData;
}
}