Welcome Guest, Not a member yet? Register   Sign In
  Url functions includes index.php in CI 4.2.1
Posted by: jetspeed - 08-03-2022, 11:23 PM - Replies (2)

Hi guys,

I noticed another thing with the update from CI 4.1.9 to 4.2.1.

Functions which return a URL (e.g. anchor(), current_url()) will result in the url being appended with index.php.

For example:

PHP Code:
echo anchor('subdir''link'); 

Will produce

PHP Code:
<a href="https://mysite.url/public/index.php/subdir">link</a

Is there any setting to remove index.php from the url? This behaviour was not there in CI 4.1.9.


  Announcing: Bonfire - a drop-in admin area
Posted by: kilishan - 08-03-2022, 11:01 PM - Replies (9)

While you may have heard me mention Bonfire, I was waiting to announce it officially until I had it somewhere pretty stable and helpful. That day is today.

Bonfire is a drop-in admin area for your new and existing CodeIgniter 4 applications, installable through Composer. It currently ships with the following features:

  • Theme/template system, that ships with a flexible Auth and Admin theme.
  • View Components to reduce the complexity of your UI by allowing you to create reusable HTML snippets, that can be optionally controlled via code.
  • A Settings library that allows you to save config file values to the database and access them whether they're in the db or just in the files.
  • Resource Filter system to make filtering lists of User, Post, etc, simple to implement and with a comfortable, consistent UI.
  • A powerful, very customizable, user authentication/authorization system, Shield.
  • Global search feature that modules can easily integrate into
  • A Recycle Bin to handle restoring/purging soft deleted models that modules can easily integrate into
  • A way to manage cookie consent to help with GDPR rules.
  • Site offline status
  • Online Log viewer/manager
  • and more...

Both of the official packages, Shield and Settings, were originally created for Bonfire, before being taken under the CodeIgniter mantle and fine-tuned.

If you've been in the community for a few years, you might have heard of Bonfire before. Quite a number of years ago I had an original version of this admin area that I had shared. It received a pretty good amount of use, with one company using it on over a hundred sites, and a large hosting company using at for their users to manage their sites, and many more I barely heard from. While the philosophy has changed a little bit between then and now, the idea is the same: provide a good kick-start to your applications to get you up and running as fast as possible while providing a set of tools you can use in the rest of the site as well.

I hope you find it useful, and I look forward to hearing about what you build on it.


  can someone tell me when codeigniter 4.2.2 will be released
Posted by: startup - 08-03-2022, 08:54 PM - Replies (2)

can someone tell me when codeigniter 4.2.2 will be released?


Exclamation Error
Posted by: nc03061981 - 08-03-2022, 01:17 PM - Replies (2)

Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 8192 bytes) in /home/xyz/abc.com/vendor/codeigniter4/framework/system/HTTP/ResponseTrait.php on line 235


  Google Calendar
Posted by: pippuccio76 - 08-03-2022, 08:55 AM - No Replies

Hi sorry for english , i try to edit some classes found on internet :
this is my Googleplus.php library:

Code:
<?php

namespace App\Libraries;

// https://console.cloud.google.com/apis

/*
https://github.com/aididalam/CodeIgniter-Google-Calendar
*/

use Google\Client as Google_client;
use Google\Service\Calendar as Google_Service_Calendar ;
use Google\Service\Calendar\Event as Google_Service_Calendar_Event ;
use Google\Service\Oauth2 as Google_Service_Oauth2;


class Googleplus
{

    private $google_client;

    public function __construct()
    {
   
        $this->google_client = $this->googleGetClient();

    }

       


    public function googleGetClient(){


        $google_client = new Google_client();

        $google_client->setAuthConfig(WRITEPATH.'google_calendar/credentials.json');

        $google_client->setRedirectUri(base_url().'/admin_google_calendar/login');
       
        $google_client->addScope('email');

        $google_client->addScope('profile');

        $google_client->addScope(Google_Service_Calendar::CALENDAR);


        if(isset($_GET["code"]))
        {
            $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

            if(!isset($token["error"]))
            {
                $google_client->setAccessToken($token['access_token']);

                session()->set('access_token', $token['access_token']);

                $google_service = new Google_Service_Oauth2($google_client);

                $data_session = $google_service->userinfo->get();

                $current_datetime = date('Y-m-d H:i:s');


                //insert data
                session()->set('user_data' , array(
                  'login_oauth_uid' => $data_session['id'],
                  'first_name'  => $data_session['given_name'],
                  'last_name'  => $data_session['family_name'],
                  'email_address'  => $data_session['email'],
                  'profile_picture' => $data_session['picture'],
                  'created_at'  => $data_session
                ));


            }


        }

       

        return $google_client;
       
    }//END get_Client




    // check login session
    public function googleIsLogin() {

        $token = session()->get('access_token');


        if ($token) {
            $this->google_client->setAccessToken($token);

        }

        return $token;
               
       
           
    }//end isLogin

    public function google_logout()
    {
        session()->remove('access_token');


    }//end google_logout



    public function loginUrl()
    {

        return $this->google_client->createAuthUrl();

    }



    public function getAccessToken()
    { 


        return $this->google_client->getAccessToken();

    }


    public function refreshToken()
    {

        $this->google_client->getRefreshToken();

        $token = $this->getAccessToken();

        session()->set('access_token' ,$token['access_token']);
    }

       



    public function revokeToken()
    {

        return $this->google_client->revokeToken();

    }


    public function getUser()
    {

        $google_ouath = new Google_Service_Oauth2($this->google_client);

        return (object)$google_ouath->userinfo->get();

    }

    public function isAccessTokenExpired()
    {


        return $this->google_client->isAccessTokenExpired();

    }


    public function getClient()
    {
        return $this->google_client;

    }
   
}
and this is my controller :

Code:
<?php

namespace App\Controllers;

use Google\Service\Calendar as Google_Service_Calendar ;
use Google\Service\Calendar\Event as Google_Service_Calendar_Event ;

use App\Libraries\Googleplus;

class Admin_google_calendar extends BaseController {





    public function login()
    {

        $google_library =new Googleplus();

        $google_client = $google_library->GetClient();

        $login_button = '';


        //print_r($_SESSION);
        //die();

        if(!session()->get('access_token'))
        {
            $login_button = '<a class="btn btn-danger" href="'.$google_client->createAuthUrl().'">Google Login</a>';
            $data['login_button'] = $login_button;
            echo view('empty_view',$data);
            echo view('admin/google_calendar/google_login');
        }
        else
        { 

            return redirect()->to('/admin_google_calendar/show_calendar');
           
        }
    }




    public function getCalendar() {

        $google_library =new Googleplus();


        if (!$google_library->googleIsLogin()) {
           
             
            return redirect()->to('admin_google_calendar/login');
       
        } else {   
           
            $google_client = $google_library->getClient();


            //$client = googleGetClient();
            $service = new Google_Service_Calendar($google_client);

            // Print the next 10 events on the user's calendar.
            $calendarId = 'primary';
           
            //funziona
            /*
            $optParams = array(
              'maxResults' => 10,
              'orderBy' => 'startTime',
              'singleEvents' => true,
              'timeMin' => date('c'),
            );
            */

            $optParams = array(
              'maxResults' => 10,
              'orderBy' => 'startTime',
              'singleEvents' => true,
              'timeMin' => date('c'),
              'timeMin' => '2022-08-01T00:00:00-02:00',
              'timeMax' => '2022-08-31T00:00:00-02:00',
            );

            $results = $service->events->listEvents($calendarId, $optParams);
            $events = $results->getItems();

            if (empty($events)) {
                print "No upcoming events found.\n";
            } else {
                print "Upcoming events:\n";
                foreach ($events as $event) {
                    $start = $event->start->dateTime;
                    if (empty($start)) {
                        $start = $event->start->date;
                    }
                    printf("%s (%s)\n", $event->getSummary(), $start);
                }
            }


        }
    }







    // oauth method
    public function oauth() {
        $code = $this->input->get('code', true);
        $this->oauthLogin($code);
        return redirect()->to(base_url(), 'refresh');
    }

    // oauthLogin
    public function oauthLogin($code) {

        $google_library =new Googleplus();

        $google_client = $google_library->googleGetClient();

        $login = $google_client->authenticate($code);
        if ($login) {
            $token = $google_client->getAccessToken();
            session()->set('google_calendar_access_token', $token);
            session()->set('is_authenticate_user', TRUE);
            return true;
        }
    }


    // add google calendar event
    public function addEvent() {

        $google_library =new Googleplus();

        if (!$google_library->googleIsLogin()) {
            session_destroy();   
           
            return redirect()->to(base_url(), 'refresh');
       
        } else {
            $json = array();
            $calendarId = 'primary';
            //$calendarId = '[email protected]';
            //$post = $this->request->getPost();

            $post['summary'] ='Test Insert';
            $post['startDate'] = '2022-07-31';
            $post['startTime'] ='07:00';
            $post['endDate'] = '2022-07-31';
            $post['endTime'] = '08:00';
            $post['description'] = 'Prova inserimento  da codeigniter';

            if(empty(trim($post['summary']))){
                $json['error']['summary'] = 'Please enter summary';
            }
            // start date time validation
            if(empty(trim($post['startDate'])) && empty($post['startTime'])){
                $json['error']['startdate'] = 'Please enter start date time';
            }
            if(empty(trim($post['endDate'])) && empty($post['endTime'])){
                $json['error']['enddate'] = 'Please enter end date time';
            }
            if(empty(trim($post['description']))){
                $json['error']['description'] = 'Please enter description';
            }

            if(empty($json['error'])){
                $event = array(
                    'summary'    => $post['summary'],
                    'start'      => $post['startDate'].'T'.$post['startTime'].':00+02:00',
                    'end'        => $post['endDate'].'T'.$post['endTime'].':00+02:00',
                    'description' => $post['description'],

                );
                $data = $this->actionEvent($calendarId, $event);
                if ($data->status == 'confirmed') {
                    $json['message'] = 1;
                } else {
                    $json['message'] = 0;
                }
            }
            //$this->output->set_header('Content-Type: application/json');
            echo json_encode($json);
        }
       
    }

    // actionEvent
    public function actionEvent($calendarId, $data) {

        $google_library =new Googleplus();


        $google_client = $google_library->googleGetClient();

        $google_client->setAccessToken(session()->get('access_token'));

        $google_service_calendar= new Google_Service_Calendar($google_client);

        //Date Format: 2016-06-18T17:00:00+03:00
        $event = new Google_Service_Calendar_Event(
            array(
                'summary'    => $data['summary'],
                'description' => $data['description'],
                'start'      => array(
                    'dateTime' => $data['start'],
                    'timeZone' => 'Europe/Rome',
                ),
                'end'        => array(
                    'dateTime' => $data['start'],
                    'timeZone' => 'Europe/Rome',
                ),
                'attendees'  => array(
                    array('email' => '[email protected]'),
                ),
            )
        );

        return $google_service_calendar->events->insert($calendarId, $event);
    }


    public function show_calendar()
    {

        $data=[];

        $google_library =new Googleplus();


        if (!$google_library->googleIsLogin()) {
           
            //session_destroy();   
            return redirect()->to('admin_google_calendar/login');
       
        } else {   
           
            //DEBUG
            //echo 'Inside';
            //die();
           
            $google_client = $google_library->googleGetClient();

            $google_client->setAccessToken(session()->get('access_token'));

            $service = new Google_Service_Calendar($google_client);



            // Print the next 10 events on the user's calendar.
            $calendarId = 'primary';
           

            $optParams = array(
              'orderBy' => 'startTime',
              'singleEvents' => true,
              'timeMin' => date('c'),
             
            );

            $results = $service->events->listEvents($calendarId, $optParams);
            $eventi = $results->getItems();

            $lista_eventi= [];

            $n=0;
            foreach ($eventi as $event) {
                $start = $event->start->dateTime;
                if (empty($start)) {
                    $start = $event->start->date;
                }

                $end = $event->end->dateTime;
                if (empty($start)) {
                    $end = $event->end->date;
                }

                $lista_eventi[$n]['id']    = $event->id;
                $lista_eventi[$n]['title'] = $event->getSummary();
                $lista_eventi[$n]['start'] = $start;
                $lista_eventi[$n]['end']  = $end;
                $lista_eventi[$n]['backgroundColor']  = "#00a65a";
                $n++;
            }

/*            print_r($lista_eventi);
            die();*/



        }
       
        $data['events'] = $lista_eventi;

        echo view('empty_view',$data );
        echo view('admin/google_calendar/show_calendar',$data);
    }


    public function carica_eventi_calendario_ajax()
    {
        $google_library =new Googleplus();


        if (($this->request->getMethod() === 'post')){

            $post = $this->request->getPost();


            $google_client = $google_library->googleGetClient();

            $google_client->setAccessToken(session()->get('access_token'));

            //$client = googleGetClient();
            $service = new Google_Service_Calendar($google_client);

            // Print the next 10 events on the user's calendar.
            $calendarId = 'primary';
           

            $optParams = array(
              'orderBy' => 'startTime',
              'singleEvents' => true,
              'timeMin' => date('c'),
              'timeMin' => $post['start'].'T00:00:00-02:00',
              'timeMax' => $post['end'].'T00:00:00-02:00',
            );

            $results = $service->events->listEvents($calendarId, $optParams);
            $eventi = $results->getItems();

            $lista_eventi= [];

            $n=0;
            foreach ($eventi as $event) {
                $start = $event->start->dateTime;
                if (empty($start)) {
                    $start = $event->start->date;
                }

                $end = $event->end->dateTime;
                if (empty($start)) {
                    $end = $event->end->date;
                }

                $lista_eventi[$n]['id']    = $event->id;
                $lista_eventi[$n]['title'] = $event->getSummary();
                $lista_eventi[$n]['start'] = $start;
                $lista_eventi[$n]['end']  = $end;
                $lista_eventi[$n]['backgroundColor']  = "#00a65a";
                $n++;
            }

           
            echo json_encode($lista_eventi);


        }else{


            echo 'alert("dati non ricevuti")';
        }
       
     
    }//end carica_eventi_calendario_ajax
   
       
    public function test_access_token($val=NULL)
    {
        $google_library =new Googleplus();

        $google_client = $google_library->getClient();

       
        if($google_library->isAccessTokenExpired() ){
           
            $token = session()->get('access_token');           

            $google_client->setAccessToken($token);


            if ($google_client->isAccessTokenExpired()) {             
             
                $google_client->fetchAccessTokenWithRefreshToken($google_client->getRefreshToken());
                $google_client->setAccessToken($google_client->getAccessToken());
                $_SESSION['access_token'] =$token=  $google_client->getAccessToken();       

                echo 'refereshato';
                die();     
            }   

            echo 'Scaduto';

            //print_r(redirect()->back());
       
        }else{
       
            echo 'Attivo';
       
        }
           
    }

    public function logout_google($val=NULL)
    {
        $google_library =new Googleplus();
        $google_library->google_logout();

        return redirect()->to('admin_google_calendar/login');

    }
   
       
   
       
}
It work but if the access token expire i have an exception :
i try to use this code in lbrary :
Code:
    // check login session
    public function googleIsLogin() {

        $token = session()->get('access_token');


        if ($token) {
            $this->google_client->setAccessToken($token);

        }

        if ($this->google_client->isAccessTokenExpired()) {

          // Set the access token on the client.
            $this->google_client->setAccessToken($_SESSION['access_token']);               
           
            // Refresh the access token if it's expired.
            if ($this->google_client->isAccessTokenExpired()) {             
                $this->google_client->fetchAccessTokenWithRefreshToken($this->google_client->getRefreshToken());
                $this->google_client->setAccessToken($this->google_client->getAccessToken());
                session()->set('access_token', $this->google_client->getAccessToken());         
            }   

        }

        return $token;
               
       
           
    }//end isLogin
as in this class https://github.com/LindaLawton/Google-AP...cation.php

but have this error :

refresh token must be passed in or set as part of setAccessToken

How can fix it ?


  app.baseurl or public $baseURL
Posted by: gfgrisales - 08-03-2022, 04:35 AM - Replies (3)

I've been looking around but I still can't find a clear concept about the diferrences of these two:

PHP Code:
app_baseURL 'http://myurl.any/'  
declared on the /.env file and

PHP Code:
public $baseURL 'http://myurl.any/'
 declared on the /app/config/App.php file

As far as my understanding goes about CodeIgniter the one declared on the .env file has development purposes only and the one in the App.php is for production... Or that's what I thougth.  Undecided

Running some tests today I found myself with an App crash after I removed/comment the public $baseURL from the App.php file even while in the .env file the CodeIgniter environment has been set as development.
PHP Code:
CI_ENVIRONMENT development 

What's the real difference and case of use for each one of them? Huh


  Design Pattern question: how to "merge" Entities and Models?
Posted by: tgix - 08-03-2022, 02:33 AM - Replies (2)

Hi,
I have a case where I'd like to mimic the JavaScript front-end design but can't see the best to do that in CI4 using the Models and Entities.
The system has an Admin with multiple settings (+50) for various parts of the system. I want to allow an Admin to be member of one or more AdminGroup where these 50+ settings can be stored and managed. In JS I have created a AdminGroupModel containing the settings and then an AdminModel extending AdminGroupModel and adding additional fields such as firstname, lastname and email. 
My rationale for this approach is that I only have to manage the settings in one place, for example when adding new features.
So for this to work, in AdminModel I need to merge the protected properties defined in AdminGroupModel with the fields required for the AdminModel. Same for the Entities defined.
I have been thinking like this:

(UPDATE: corrected some mistakes with the scope that I found so far)

PHP Code:
class AdminGroupModel extends BaseModel
{
    protected $commonFields = [
        // Defining all common settings here, such as:
        'access_users''access_companies',
        'item_version'
    ];

    public function 
__construct(?ConnectionInterface &$db null, ?ValidationInterface $validation null)
    {
        
$fields get_class_vars(self::class)['commonFields'];
        
$this->allowedFields += $fields;

        
parent::__construct($db$validation);
    }


And then in AdminModel:
PHP Code:
<?php
class AdminModel extends AdminGroupModel
{

    protected $allowedFields = [
        'firstname''lastname''email'
    ];



Would this be a viable approach? Any hints greatly appreciated.
/Mattias


  how to data in basecontroller.php pass to footer.php view codeigniter 4
Posted by: startup - 08-03-2022, 01:34 AM - Replies (8)

1. BaseController.php

PHP Code:
<?php
namespace App\Controllers;
use 
CodeIgniter\Controller;
use 
CodeIgniter\HTTP\CLIRequest;
use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Psr\Log\LoggerInterface;
use 
App\Models\HeaderModel;

class 
BaseController extends Controller{
  
    
protected $data=array();
    protected $session;
    protected $option ='';
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger){
        parent::initController($request$response$logger);

        $this->db = \Config\Database::connect();
        $this->session = \Config\Services::session();

        $mSite= new HeaderModel();
        $this->option $mSite->site_option_bottom();
        $this->data['site_name']        $this->option->site_name;
    }

    


2.footer.php
PHP Code:
<?php echo $this->site_name?>

NOTE FOR SOMEONE NEED

i only write demo, if you do your project, you can write  method function to show

1. in BaseController.php 
PHP Code:
<?php
namespace App\Controllers;
use 
CodeIgniter\Controller;
use 
CodeIgniter\HTTP\CLIRequest;
use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Psr\Log\LoggerInterface;
use 
App\Models\HeaderModel;

class 
BaseController extends Controller{
  
    
protected $data;
    protected $session;

    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger){
        parent::initController($request$response$logger);

        $this->data = \Config\Database::connect();
        $this->session = \Config\Services::session();

        $mSite = new HeaderModel();
        $data['test']= $mSite->site_option_bottom();
     //path view footer.php in your project
        return view('Site\footer',$data);
    }

    


in footer.php we show this

PHP Code:
<?php

print_r
($test); 
?>


Exclamation Model with many allowedFields data
Posted by: pws - 08-02-2022, 11:58 AM - Replies (3)

Hello,
I have an Model where i need to set the "allowedFields" with big array data (more than 50 fields)!
Is possible to define "allowedFields" where i not need to insert all fields!?
thanks


  Puzzling Error
Posted by: donpwinston - 08-02-2022, 08:46 AM - Replies (2)

I've upgraded CodeIgniter from 3.9 to 4.2.1. I'm getting the following exception for all my routes except two. I don't understand why. I don't know what is different about the two that work. Invalid routes are not giving me same error and not Page Not Found page. I was using the legacy routing in the previous version.

ErrorException

preg_match(): Compilation failed: unmatched closing parenthesis at offset 23
SYSTEMPATH/Router/Router.php at line 418

My route config:

PHP Code:
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('ReadPdf');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
// The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
// where controller filters or CSRF protection are bypassed.
// If you don't want to define all routes, please use the Auto Routing (Improved).
// Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
//$routes->setAutoRoute(false);

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/''ReadPdf::index'); //does not work
$routes->get('/enroll''Enroll::index'); //works!
$routes->get('/notice''Notice::index'); //works!
$routes->get('/notice/upload''Notice::upload'); //?
$routes->get('/notice/download/{:segment)/(:segment)''Notice::download/$1/$2'); //?
$routes->get('/receive-pdf''ReceivePdf::index'); //all of these below don't work
$routes->get('/read-pdf''ReadPdf::index');
$routes->get('/relay-pdf''RelayPdf::index');
$routes->get('/reset-pdf''ResetPdf::index');
$routes->get('/reset-pdf/list''ResetPdf::list');
$routes->get('/reset-pdf/move''ResetPdf::move');
$routes->get('/server-up''ServerUp::index');
$routes->get('/test''Test::index'); 


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Session Lost after Paymen...
by Austin638
5 hours ago
extention of autorouter i...
by kenjis
6 hours ago
redirecting from another ...
by vgrigorov
6 hours ago
Shield validation questio...
by chronic
7 hours ago
How to set dynamic base_u...
by kenjis
8 hours ago
Upgrading from 4.1.9 to 4...
by fre2mansur
Yesterday, 06:45 PM
trouble starting
by dum1
Yesterday, 01:05 PM
add CI4 view features lik...
by kilishan
Yesterday, 12:25 PM
Adding or changing views ...
by Mostafa Khudair
Yesterday, 11:46 AM
Title Suggestions
by Ramipa Pimma
Yesterday, 11:29 AM

Forum Statistics
» Members: 40,591
» Latest member: ELISEO AMAR
» Forum threads: 75,307
» Forum posts: 367,071

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB