I am converting current date to hijri date. Please see the link of code below which i have used in codeigniter format taken from the website in the same way but it was not showing me anything. If I have done something wrong please do let me know that also.
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class HijriDate extends CI_Controller{
private $hijri;
public function __construct(){
parent::__construct();
$this->load->helper('url');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
//header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
// $this->load->model('HijriDateModel','hdm');
// date_default_timezone_set('America/New_York');
}
public function index($time = false)
{
//$this->load->view('view');
if(!$time) $time = time();
$this->hijri = $this->GregorianToHijri($time);
$result=$this->hijri;
return json_encode($result);
// $this->GregorianToHijri($time = null);
}
public function get_date(){
return $this->hijri[1] . ' ' . $this->get_month_name($this->hijri[0]) . ' ' . $this->hijri[2] . 'H';
}
public function get_day(){
return $this->hijri[1];
}
public function get_month(){
return $this->hijri[0];
}
public function get_year(){
return $this->hijri[2];
}
public function get_month_name($i){
static $month = array(
"muharram", "safar", "rabiulawal", "rabiulakhir",
"jamadilawal", "jamadilakhir", "rejab", "syaaban",
"ramadhan", "syawal", "zulkaedah", "zulhijjah"
);
return $month[$i-1];
}
private function GregorianToHijri($time = null){
if ($time === null) $time = time();
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);
return $this->JDToHijri(cal_to_jd(CAL_GREGORIAN, $m, $d, $y));
}
private function HijriToGregorian($m, $d, $y){
return jd_to_cal(CAL_GREGORIAN, $this->HijriToJD($m, $d, $y));
}
# Julian Day Count To Hijri
private function JDToHijri($jd){
$jd = $jd - 1948440 + 10632;
$n = (int)(($jd - 1) / 10631);
$jd = $jd - 10631 * $n + 354;
$j = ((int)((10985 - $jd) / 5316)) *
((int)(50 * $jd / 17719)) +
((int)($jd / 5670)) *
((int)(43 * $jd / 15238));
$jd = $jd - ((int)((30 - $j) / 15)) *
((int)((17719 * $j) / 50)) -
((int)($j / 16)) *
((int)((15238 * $j) / 43)) + 29;
$m = (int)(24 * $jd / 709);
$d = $jd - (int)(709 * $m / 24);
$y = 30*$n + $j - 30;
return array($m, $d, $y);
}
# Hijri To Julian Day Count
private function HijriToJD($m, $d, $y){
return (int)((11 * $y + 3) / 30) +
354 * $y + 30 * $m -
(int)(($m - 1) / 2) + $d + 1948440 - 385;
}
}// end class Hijri Page
?>
Code Details: I have made controller class in codeigniter and want only today's date in Hijri like this in json format,
{"hijridate":"18 Jumada al-Ukhra 1440"}
However it is not showing as desired. Please help me. I am not expert in codeigniter :(
Related
Is it possible to customize the chunk configuration in Filepond such that the chunk information is provided to the upload server:
as query parameters instead of headers
with custom query parameter names instead of Upload-Length, Upload-Name, and Upload-Offset
I am trying to fit Filepond's chunk implementation to a third party upload endpoint that I don't have control over.
I have found the Advanced configuration where you provide a process function which I've played with a little bit to see what comes through the options param -- however that appears (I think) to make the chunking calculations my responsibility. My original thought was to manipulate the options.chunkServer.url to include the query params I need but I don't believe this processes individual chunks.
In case it makes a difference, this is being done in React using the react-filepond package.
I made and implementation in Laravel 6 using Traits and some "bad practices" (I didn't have time because ... release in prod) to join chunks into a file
Basically:
post to get unique id folder to storage
get chunks and join together
profit!
Here's the full code:
<?php
namespace App\Http\Traits\Upload;
use Closure;
use Faker\Factory as Faker;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait Uploadeable
{
public function uploadFileInStorage(Request $request, Closure $closure)
{
// get the nex offset for next chunk send
if (($request->isMethod('options') || $request->isMethod('head')) && $request->has('patch')) {
//get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// reead all chunks in directory
$patch = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// read offsets for calculate
$offsets = array();
$size = 0;
$last_offset = 0;
foreach ($patch as $filename) {
$size = Storage::size($filename);
list($dir, $offset) = explode('file.patch.', $filename, 2);
array_push($offsets, $offset);
if ($offset > 0 && !in_array($offset - $size, $offsets)) {
$last_offset = $offset - $size;
break;
}
// last offset is at least next offset
$last_offset = $offset + $size;
}
// return offset
return response($last_offset, 200)
->header('Upload-Offset', $last_offset);
}
// chunks
if ($request->isMethod('patch') && $request->has('patch')) {
// get the temp dir
$dir = $request->patch . DIRECTORY_SEPARATOR;
// read headers
$offset = $request->header('upload-offset');
$length = $request->header('upload-length');
// should be numeric values, else exit
if (!is_numeric($offset) || !is_numeric($length)) {
return response('', 400);
}
// get the file name
$name = $request->header('Upload-Name');
// sleep server for get a diference between file created to sort
usleep(500000);
// storage the chunk with name + offset
Storage::put($dir . 'file.patch.' . $offset, $request->getContent());
// calculate total size of patches
$size = 0;
$patch = Storage::files($dir);
foreach ($patch as $filename) {
$size += Storage::size($filename);
}
// make the final file
if ($size == $length) {
// read all chunks in directory
$files = collect(Storage::files($dir))
->sortBy(function ($file) {
return Storage::lastModified($file);
});
// create output file
//Log::info(storage_path('app'));
$new_file_name = $final_name = trim(storage_path('app') . DIRECTORY_SEPARATOR . $dir . $name);
$file_handle = fopen($new_file_name, 'w');
// write patches to file
foreach ($files as $filename) {
// get offset from filename
list($dir, $offset) = explode('.patch.', $filename, 2);
// read chunk
$patch_handle = fopen(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename), 'r');
$patch_contents = fread($patch_handle, filesize(storage_path('app') . DIRECTORY_SEPARATOR . trim($filename)));
fclose($patch_handle);
// apply patch
fseek($file_handle, $offset);
fwrite($file_handle, $patch_contents);
}
// done with file
fclose($file_handle);
// file permission (prefered 0755)
chmod($final_name, 0777);
// remove patches
foreach ($patch as $filename) {
$new_file_name = storage_path('app') . DIRECTORY_SEPARATOR . trim($filename);
unlink($new_file_name);
}
// simple class (no time to explain)
$file = new UploadedFile(
$final_name,
basename($final_name),
mime_content_type($final_name),
filesize($final_name),
false
);
$dir = $request->patch . DIRECTORY_SEPARATOR;
$object = new \stdClass();
$object->full_path = (string)$file->getPathname();
$object->directory = (string)($dir);
$object->path = (string)($dir . basename($final_name));
$object->name = (string)$file->getClientOriginalName();
$object->mime_type = (string)$file->getClientMimeType();
$object->extension = (string)$file->getExtension();
$object->size = (string)$this->formatSizeUnits($file->getSize());
// exec closure
$closure($file, (object)$object, $request);
}
// response
return response()->json([
'message' => 'Archivo subido correctamente.',
'filename' => $name
], 200);
}
// get dir unique id folder temp
if ($request->isMethod('post')) {
$faker = Faker::create();
$unique_id = $faker->uuid . '-' . time();
$unique_folder_path = $unique_id;
// create directory
Storage::makeDirectory($unique_folder_path);
// permisos directorio
chmod(storage_path('app') . DIRECTORY_SEPARATOR . $unique_folder_path . DIRECTORY_SEPARATOR, 0777);
// response with folder
return response($unique_id, 200)
->header('Content-Type', 'text/plain');
}
}
private function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' bytes';
} elseif ($bytes == 1) {
$bytes = $bytes . ' byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
}
´´´
We're using Memcached to store Laravel's cookie-based session at the moment but want to use Redis throughout for session and cache for consistency.
Is there a way to migrate all user sessions from Memcached to Redis without logging out the users?
I was able to migrate the sessions without logging out the users. I created an artisan command for the purpose:
<?php
namespace App\Console\Commands;
use \Memcached;
use \Redis;
use Illuminate\Console\Command;
class MigrateSessionToRedis extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'migrate:session';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Migrate sessions from Memcached to Redis';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct() #NOSONAR
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$this->info('Starting session migration..');
$memcached = new Memcached();
$memcached->addServer(env('MEMCACHED_HOST'), 11211);
$sessions = $this->getMemcachedKeys(env('MEMCACHED_HOST'));
if (! is_array($sessions)) {
$this->error('Could not retrieve sessions from Memcached');
exit(1);
}
foreach ($sessions as $session) {
$value = $memcached->get($session);
if ($value) {
$object = unserialize($value);
$valueForRedis = serialize(serialize($object));
// Set session in Redis with session expiry lifetime
Redis::set("{$session}", $valueForRedis, 'EX', config('session.lifetime'));
}
}
$this->info('Finished session migration.');
}
/**
* Get all memcached keys. Special function because getAllKeys() is broken since memcached 1.4.23.
* Should only be needed on php 5.6
*
* cleaned up version of code found on Stackoverflow.com by Maduka Jayalath
*
* #return array|int - all retrieved keys (or negative number on error)
*/
private function getMemcachedKeys($host = '127.0.0.1', $port = 11211) #NOSONAR
{
$mem = #fsockopen($host, $port);
if ($mem === false) {
return -1;
}
// retrieve distinct slab
$r = #fwrite($mem, 'stats items' . chr(10));
if ($r === false) {
return -2;
}
$slab = [];
while (($l = #fgets($mem, 1024)) !== false) {
// finished?
$l = trim($l);
if ($l == 'END') {
break;
}
$m = [];
// <STAT items:22:evicted_nonzero 0>
$r = preg_match('/^STAT\sitems\:(\d+)\:/', $l, $m);
if ($r != 1) {
return -3;
}
$a_slab = $m[1];
if (!array_key_exists($a_slab, $slab)) {
$slab[$a_slab] = [];
}
}
reset($slab);
foreach ($slab as $a_slab_key => &$a_slab) {
$r = #fwrite($mem, 'stats cachedump ' . $a_slab_key . ' 100' . chr(10));
if ($r === false) {
return -4;
}
while (($l = #fgets($mem, 1024)) !== false) {
// finished?
$l = trim($l);
if ($l == 'END') {
break;
}
$m = [];
// ITEM 42 [118 b; 1354717302 s]
$r = preg_match('/^ITEM\s([^\s]+)\s/', $l, $m);
if ($r != 1) {
return -5;
}
$a_key = $m[1];
$a_slab[] = $a_key;
}
}
// close the connection
#fclose($mem);
unset($mem);
$keys = [];
reset($slab);
foreach ($slab as &$a_slab) {
reset($a_slab);
foreach ($a_slab as &$a_key) {
$keys[] = $a_key;
}
}
unset($slab);
return $keys;
}
}
Hope it can help others.
Below just example how to make this kind of migration. Try it that way:
<?php
$host = '127.0.0.1';
$port = null;
$oldPrefix = 'sess_';
$newPrefix = 'sess_';
$sessionDir = '/var/lib/php/session/';
$m = new \Redis();
$m->connect($host, $port);
// $m = new \Memcached();
// $m->addServer($host, $port);
$sessions = scandir($sessionDir);
if (!$sessions) {
die('nothing to migrate');
}
foreach ($sessions as $s) {
if (in_array($s, ['.', '..'])) {
continue;
}
$sessionName = str_replace($oldPrefix, '', $s);
$sessionContents = file_get_contents($sessionDir.$s);
if (!$m->set($newPrefix.$sessionName, $sessionContents)) {
die(sprintf('Could not migrate session %s'.PHP_EOL, $newPrefix.$sessionName));
}
echo '.';
}
die(PHP_EOL);
But I guess hat users will be logged out.
I`m using custom form request to validate all input data to store users.
I need validate the input before send to form request, and get all validated data in my controller.
I have a regex function ready to validate this input, removing unwanted characters, spaces, allow only numbers and etc.
Would to get all data validated in controller, but still have no success.
Input example:
$cnpj= 29.258.602/0001-25
How i need in controller:
$cnpj= 29258602000125
UsuarioController
class UsuarioController extends BaseController
{
public function cadastrarUsuarioExterno(UsuarioStoreFormRequest $request)
{
//Would to get all input validated - no spaces, no!##$%^&*, etc
$validated = $request->validated();
dd($data);
}
...
}
UsuarioStoreFormRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class UsuarioStoreFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'cnpj' => 'required|numeric|digits:14',
];
}
Custom function to validate cnpj
function validar_cnpj($cnpj)
{
$cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
// Valida tamanho
if (strlen($cnpj) != 14)
return false;
// Valida primeiro dígito verificador
for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
return false;
// Valida segundo dígito verificador
for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
{
$soma += $cnpj{$i} * $j;
$j = ($j == 2) ? 9 : $j - 1;
}
$resto = $soma % 11;
return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
}
You could use the prepareForValidation method in your FormRequest. This way your input would be modified and replaced in the request before it is validated and you can normally retrieve it in the controller with $request->get('cnpj'); after the validation was successful.
public function prepareForValidation()
{
$input = $this->all();
if ($this->has('cnpj')) {
$input['cnpj'] = $this->get('cnpj'); // Modify input here
}
$this->replace($input);
}
You could extend the validated function in UsuarioStoreFormRequest as follows
/**
* Get the validated data from the request.
*
* #return array
*/
public function validated()
{
$validated = parent::validated();
//Add here more characters to remove or use a regex
$validated['cnpj'] = str_replace(['-', '/', ' ', '.'], '', $validated['cnpj']);
return $validated;
}
Do it like this:
$string = "29.258.602/0001-25";
preg_match_all('!\d+!', $string, $matches);
return (implode("",$matches[0]));
Hope its help
I'm trying to develop an algorithm to create a symfony template service.
I want to check if a template exists in a subset of paths, ordered.
Given an array of parameter like this (already ordered like I want):
$params = ['O', 'U', 'W', 'P']
How can I output this array?
$urls = [
'O/U/W/P/template',
'O/U/W/template',
'O/U/P/template',
'O/U/template',
'O/W/P/template',
'O/W/template',
'O/P/template',
'O/template',
'U/W/P/template',
'U/W/template',
'U/P/template',
'U/template',
'W/P/template',
'W/template',
'P/template',
'template'
];
I can perform for a little list of parameters (like everyone can do it I suppose) with a code like this :
private function getPaths($template, $params)
{
$urls = [];
$alreadyPerform = [];
$paramsCounter = count($params);
for ($i = 0; $i < $paramsCounter; $i++) {
for ($j = 0; $j < $paramsCounter; $j++) {
if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
$urls[] = sprintf(
'/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
);
}
}
$alreadyPerform[] = $params[$i];
$urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
}
$urls[] = sprintf('%s.html.twig', $template);
return $urls;
}
This function work like I wanted until today (max 3 parameters), but I want to add one parameters today, maybe more after.
Thank you very much for your help !
Cheers.
Using recursion, you can do the following:
/**
* #param array $elements
* #param array $extra
*
* #return Generator
*/
function gen(array $elements, array $extra = []): \Generator {
foreach ($elements as $i => $head) {
foreach (gen(array_slice($elements, $i + 1), $extra) as $tail) {
yield array_merge([$head], $tail);
}
}
yield $extra;
}
demo: https://3v4l.org/gJB8q
Or without recursion:
/**
* #param array $elements
*
* #return Generator
*/
function gen2(array $elements): \Generator {
for ($num = count($elements), $i = pow(2, $num) - 1; $i >= 1; $i -= 2) {
$r = [];
for ($j = 0; $j < $num; $j += 1) {
if ($i & (1 << ($num - $j - 1))) {
$r[] = $elements[$j];
}
}
yield $r;
}
}
demo: https://3v4l.org/grKXo
Consider using the following package:
https://github.com/drupol/phpermutations
Just a very basic example of what it can do:
$permutations = new \drupol\phpermutations\Generators\Permutations(['A', 'B', 'C'], 2);
foreach ($permutations->generator() as $permutation) {
echo implode('/', $permutation);
echo "\n";
}
A/B
B/A
A/C
C/A
B/C
C/B
I am trying to unlink files that were created the day before
I have a custom application > core > MY_Log.php file and it creates a log for each error level. For easier reading.
logs > DEBUG-04-08-2016.php
logs > ERROR-04-08-2016.php
logs > INFO-04-08-2016.php
logs > DEBUG-03-08-2016.php
logs > ERROR-03-08-2016.php
logs > INFO-03-08-2016.php
Question how am I able to modify the write_log so could delete / unlink files that were created the day before?
<?php
class MY_Log extends CI_Log {
public function write_log($level, $msg)
{
if ($this->_enabled === FALSE)
{
return FALSE;
}
$level = strtoupper($level);
if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
&& ! isset($this->_threshold_array[$this->_levels[$level]]))
{
return FALSE;
}
$filepath = $this->_log_path . $level .'-'. date('d-m-Y').'.'.$this->_file_ext;
$message = '';
if ( ! file_exists($filepath))
{
$newfile = TRUE;
// Only add protection to php files
if ($this->_file_ext === 'php')
{
$message .= "";
}
}
if ( ! $fp = #fopen($filepath, 'ab'))
{
return FALSE;
}
flock($fp, LOCK_EX);
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->_date_fmt, 'u') !== FALSE)
{
$microtime_full = microtime(TRUE);
$microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$microtime_short, $microtime_full));
$date = $date->format($this->_date_fmt);
}
else
{
$date = date($this->_date_fmt);
}
$message .= $this->_format_line($level, $date, $msg);
for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($message, $written))) === FALSE)
{
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === TRUE)
{
chmod($filepath, $this->_file_permissions);
}
return is_int($result);
}
}
First of use
$config['log_threshold'] = 1;
For only error message, so there will be less number of files
Add below code just before $filepath; to delete previous date logs
$unlink_date = date('Y-m-d',strtotime("-1 days"));
$filepath_unlink = $this->_log_path . $level .'-'. $unlink_date.'.'.$this->_file_ext;
if ( file_exists($filepath_unlink))
{
unlink($filepath_unlink);
}