Welcome Guest, Not a member yet? Register   Sign In
  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'); 


  Call to undefined function form_open() in CI 4
Posted by: TuqueroIMKJernalyn - 08-02-2022, 05:34 AM - Replies (1)

I am using CodeIgniter 4 and loading form helper in the following way, but it still says,

Call to undefined function form_open()

In BaseController.php i am autoloading form helper.

protected $helpers = ["form"];
Route:

$routes->get('admin/login', 'admin\LoginController::index');
Controller:

public function index()
{
   
    echo view('admin/login');
}
View:

<?php echo form_open('admin/dologin');?>
    <?= csrf_token() ?>
    <div class="input-group mb-3">
      <input type="email" class="form-control" name="email" placeholder="Email">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-envelope"></span>
        </div>
      </div>
    </div>
    <div class="input-group mb-3">
      <input type="password" class="form-control" name="password" placeholder="Password">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-lock"></span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-4">
        <button type="submit" class="btn btn-primary btn-block">Sign In</button>
      </div>
      <!-- /.col -->
    </div>
  <?php echo form_close();?>
How can i get rid of from this error?

Call to undefined function form_open()


  Database driven routing in CodeIgniter 2.x
Posted by: EdwardSMaTeresa - 08-02-2022, 05:24 AM - Replies (2)

I am creating a site that will have a lot of routes that will need to be added to the routes file (800+) - obviously I do not want to manually add these one by one into the routes config file.

Can anyone suggest the best practice to have my routes loaded automatically from the database. Is there a suitable library/helper that will perform this task that works with version 2.x

For instance..

$route['apple'] = 'brands/index';
$route['blackberry'] = 'brands/index';
$route['htc'] = 'brands/index';
$route['samsung'] = 'brands/index';
These are just a few of the brands i'd be adding to the routes - but there are hundreds of these so i'd want to have this loaded from a database rather than manually type these in. Also - would this method have any impact on site performance having them load from the database?

I am using Codeigniter v2.1.3


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

Username
  

Password
  





Latest Threads
dropdown filter datatable...
by SubrataJ
2 hours ago
SHIELD - Table name
by nfaiz
4 hours ago
Config\Paths different on...
by kenjis
7 hours ago
Session destroy randomly ...
by Kiranrs
8 hours ago
What CI4-related book wou...
by SubrataJ
Yesterday, 08:41 AM
Use of subfolder for cont...
by iRedds
08-05-2022, 06:28 PM
404 Not Found in a route ...
by kenjis
08-05-2022, 05:41 PM
Announcing: Bonfire - a d...
by kilishan
08-05-2022, 11:45 AM
checkbox value for Edit n...
by SubrataJ
08-05-2022, 08:59 AM
PHP 8.1.9. This is a bug ...
by InsiteFX
08-05-2022, 04:12 AM

Forum Statistics
» Members: 40,036
» Latest member: symspot
» Forum threads: 75,265
» Forum posts: 366,945

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB