extends multiple system class of codeigniter - codeigniter

I want to handle error on codeigniter so I need to extends both the class "CI_Controller" and "CI_Exceptions" so how to implement it. something like below. if it's possible to handling error globally in hooks or other way for whole system?
class Language extends CI_Controller , CI_Exceptions{
public function __construct()
{
parent::__construct();
parent::CI_Exceptions();
}
}

There is a nice post on how to do this using a hook. I copied the samples from the post, but I would go there and read up on the solution to get going int the right direction.
Hook
$hook['pre_controller'][] = array(
'class' => 'ExceptionHook',
'function' => 'SetExceptionHandler',
'filename' => 'ExceptionHook.php',
'filepath' => 'hooks'
);
Exception Class
class MY_Exceptions extends CI_Exceptions {
public function __construct()
{
parent::CI_Exceptions();
}
public function show_php_error($severity, $message, $filepath, $line)
{
$severity = ( ! isset($this->levels[$severity])) ? $severity : $this->levels[$severity];
$filepath = str_replace("\\", "/", $filepath);
// For safety reasons we do not show the full file path
if (FALSE !== strpos($filepath, '/'))
{
$x = explode('/', $filepath);
$filepath = $x[count($x)-2].'/'.end($x);
}
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'errors/error_php'.EXT);
$buffer = ob_get_contents();
ob_end_clean();
$msg = 'Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line;
log_message('error', $msg , TRUE);
mail('dev-mail#example.com', 'An Error Occurred', $msg, 'From: test#example.com');
}
}

Related

Try to use the codeigniter's file upload library as a general function from Helpers

Can anybody help as I am trying to use the codeigniter's upload library from the helpers folder but I keep getting the same error that I am not selecting an image to upload? Has any body tried this before?
class FileUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'file_uploading'));
$this->load->library('form_validation', 'upload');
}
public function index() {
$data = array('title' => 'File Upload');
$this->load->view('fileupload', $data);
}
public function doUpload() {
$submit = $this->input->post('submit');
if ( ! isset($submit)) {
echo "Form not submitted correctly";
} else { // Call the helper
if (isset($_FILES['image']['name'])) {
$result = doUpload($_FILES['image']);
if ($result) {
var_dump($result);
} else {
var_dump($result);
}
}
}
}
}
The Helper Function
<?php
function doUpload($param) {
$CI = &get_instance();
$CI->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|png|jpg|jpeg|png';
$config['file_name'] = date('YmdHms' . '_' . rand(1, 999999));
$CI->upload->initialize($config);
if ($CI->upload->do_upload($param['name'])) {
$uploaded = $CI->upload->data();
return $uploaded;
} else {
$uploaded = array('error' => $CI->upload->display_errors());
return $uploaded;
}
}
There are some minor mistakes in your code, please fix it as below,
$result = doUpload($_FILES['image']);
here you should pass the form field name, as per your code image is the name of file input.
so your code should be like
$result = doUpload('image');
then, inside the function doUpload you should update the code
from
$CI->upload->do_upload($param['name'])
to
$CI->upload->do_upload($param)
because Name of the form field should be pass to the do_upload function to make successful file upload.
NOTE
Make sure you added the enctype="multipart/form-data" in the form
element

Object of class Illuminate\Routing\Redirector could not be converted to string. srmklive/laravel-paypal

I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.

How to call shell function to another Controller - Cakephp

I'm using this function in my shell to send email
Edit :
UsersShell
<?php
namespace App\Shell;
use Cake\Console\Shell;
use Cake\Log\Log;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use App\Controller\Component\EmailComponent;
class UsersShell extends Shell
{
public function initialize()
{
parent::initialize();
$this->loadModel('Users');
//Load Component
$this->Email = new EmailComponent(new ComponentRegistry());
}
public function mail()
{
$to = 'exemple#gmail.com';
$subject = 'Hi buddy, i got a message for you.';
$message = 'User created new event';
try {
$mail = $this->Email->send_mail($to, $subject, $message);
print_r($mail);
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail-
>ErrorInfo;
}
exit;
}
I would like to know how can I call it in my controller ? here
Edit : Events is located in the plugins folder
EventsController
<?php
namespace FullCalendar\Controller;
use FullCalendar\Controller\FullCalendarAppController;
use Cake\Routing\Router;
use Cake\Event\Event;
use Cake\Console\ShellDispatcher;
class EventsController extends FullCalendarAppController
{
public $name = 'Events';
public function add()
{
$event = $this->Events->newEntity();
if ($this->request->is('post')) {
$event = $this->Events->patchEntity($event, $this->request->data);
if ($this->Events->save($event)) {
/* $shell = new ShellDispatcher();
$output = $shell->run(['cake', 'users'], ['plugin' =>
'Events']);
if (0 === $output) {
$this->Flash->success('Success from shell command.');
} else {
$this->Flash->error('Failure from shell command.'); */
$this->Flash->success(__('The event has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The event could not be saved. Please,
try again.'));
}
}
$this->set('eventTypes', $this->Events->EventTypes->find('list'));
$this->set(compact('event'));
$this->set('_serialize', ['event']);
$this->set('user_session', $this->request->session()-
>read('Auth.User'));
$this->viewBuilder()->setLayout('user');
}
As you can see i used the shell dispatched i'm not sure if it's correct
but i'm getting failure
Thanks !
Edit :
EmailComponent
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Core\App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require ROOT. '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/SMTP.php';
class EmailComponent extends Component {
public function send_mail($to, $subject, $message)
{
// date_default_timezone_set('Asia/Calcutta');
$sender = "exemple#gmail.com"; // this will be overwritten by GMail
$header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";
$mail = new PHPMailer();
$mail->SMTPDebug = 2; // turn it off in production
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "exemple#gmail.com";
$mail->Password = "xxxx";
$mail->SMTPSecure = "tls"; // ssl and tls
$mail->Port = 587; // 465 and 587
$mail->SMTPOptions = array (
'tls' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
),
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->From = $sender;
$mail->FromName = "From Me";
$mail->AddAddress($to);
$mail->isHTML(true);
$mail->CreateHeader($header);
$mail->Subject = $subject;
$mail->Body = nl2br($message);
$mail->AltBody = nl2br($message);
// return an array with two keys: error & message
if(!$mail->Send()) {
return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
} else {
return array('error' => false, 'message' => "Message sent!");
}
}
}
Correct me if I'm wrong. First your shell must be started something like this.
class UsersShell extends AppShell {
public function main(){ //change name here to main
$to = 'exemple#gmail.com';
$subject = 'Hi buddy, i got a message for you.';
$message = 'User created new event';
try {
$mail = $this->Email->send_mail($to, $subject, $message);
print_r($mail);
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
exit;
}
}
By the way, if you want to check output, you must return something like true or false. Otherwise, there is no point to check output after execute the shell.
First Check Shell Command Run in CakePHP-CLI. Like this
bin/cake users mail
if shell command successfully running. Shell Class Fine.
Next Use Shell in Controller
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Console\ShellDispatcher;
class PagesController extends AppController
{
/**
* Run shell command
*/
public function run()
{
$shell = new ShellDispatcher();
$output = $shell->run(['cake', 'users', 'mail']);
// $output = $shell->run(['cake', 'users', 'mail', 'email']); // [pass arguments]
// debug($output);
if ($output === 0) {
echo "Shell Command execute";
} else {
echo "Failure form shell command";
}
exit;
}
}
Change Shell Function : if mail not sent run $this->abort() function and return (int) 1 and mail sent successfully run $this->out() function and return (int) 0
/**
* Send Mail with shell command
*/
public function mail()
{
$to = 'mail#gmail.com';
$subject = 'Hi buddy, i got a message for you.';
$message = 'Nothing much. Just test out my Email Component using PHPMailer.';
$mail = $this->Email->send_mail($to, $subject, $message);
// debug($mail);
if ($mail['error'] === false) {
$this->out("Mail Successfully Sent For :: ". $to);
} else {
$this->abort("Mail Error.");
}
}

ReflectionException in laravel. Class does not exist

Why does laravel cannot detect my class this time. In my previous tries it worked but this time it does not. Here are my codes :
DataEntry.php
<?php namespace App\Server ;
abstract class DataEntry{
/*This class facilitates the
storing of data to the server...
*/
abstract protected function storeData($data);
abstract protected function updateData($data ,$id);
}
MedicineDosageEntry.php
<?php
namespace App\Server ;
use Image;
use App\Dosage ;
use App\Photo ;
use App\Server\DataEntry ;
use Request ;
use Auth ;
class MedicineDosageEntry extends DataEntry{
public function storeData ($data){
$file = $data['photo'] ;
$fileName = uniqid().$file->getClientOriginalName() ;
if(!file_exists('medicine/images')){
mkdir('medicine/images', 0777, true);
}
$file->move('medicine/images', $fileName);
if(!file_exists('medicine/images/thumbs')){
mkdir('medicine/images/thumbs', 0777, true);
}
$thumb = Image::make('medicine/images/' .$fileName)->resize(150,150)->save('medicine/images/thumbs/' . $fileName,50);
$dosage = new Dosage;
$dosage->dosage_name = $data['dosage_name'];
$dosage->form = $data['form'];
$dosage->medicine_id = $data['medicine_id'];
$dosage->price = $data['price'];
$dosage->save();
$dosage->photo()->create([
'dosage_id' => $data['id'];
'file_name' => $fileName,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => 'medicine/images/thumbs'. $fileName,
'created_by'=> Auth::user()->id,
]);
}
public function updateData($data , $id) {
}
}
MedicineController.php
<?php namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\DB\MedicineRepository;
use App\Http\Requests\MedicineRequest ;
use App\Dosage ;
use App\Medicine;
use Auth ;
use App\Server\MedicineDosageEntry ;
use Flash ;
class MedicineController extends Controller {
public function store(MedicineRequest $request, MedicineDosageEntry $dosage ){
$requestData = $request->all();
$dosage->storeData($requestData);
}
}
Do i have to register this class. Why do I encounter this. It worked out in my previous tries but after doing some refactoring and coding. It crashed..

Codeigniter with google oauth2 adds hashtag php to redirect('usercp')

I want to be able to redirect to another controller but when user logins in with google and is success full it gets redirected to there usercp but for some reason it gets the # from the end of here
http://www.example.com/test/google?code=4/sorrynocodeshown#
And when redirects using codeigniter redirect() it adds # to it.
http://www.example.com/usercp#
Question When redirecting to new page once successful login how to stop # from being added.
I use https://github.com/moemoe89/google-login-ci3
I also use vhost with xammp
Controller function
public function google() {
if ($this->input->get('code')) {
$googleplus_auth = $this->googleplus->getAuthenticate();
$googleplus_info = $this->googleplus->getUserInfo();
$google_data = array(
'google_id' => $googleplus_info['id'],
'google_name' => $googleplus_info['name'],
'google_link' => $googleplus_info['link'],
'image' => $googleplus_info['picture'],
'email' => $googleplus_info['email'],
'firstname' => $googleplus_info['given_name'],
'lastname' => $googleplus_info['family_name']
);
$login_google_userid = $this->login_model->login_with_google($googleplus_info['id'], $google_data);
$_SESSION['user_id'] = $login_google_userid;
redirect('usercp');
}
}
config/googleplus.php settings
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['googleplus']['application_name'] 'Somename';
$config['googleplus']['client_id'] = '*****';
$config['googleplus']['client_secret'] = '*****';
$config['googleplus']['redirect_uri'] = 'http://www.mysetname.com/account/login/google';
$config['googleplus']['api_key'] = '*****';
$config['googleplus']['scopes'] = array();
I am using HMVC with codeigniter
application/modules/account/controllers/Login.php
Full Controller
<?php
class Login extends MX_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('googleplus');
}
public function index() {
if ($this->login_model->is_logged_in()) {
$this->session->set_flashdata('success', 'Welcome back! If you wish to logout ' . anchor('account/logout', 'Click Here'));
redirect(base_url('usercp'));
}
if (($this->input->server("REQUEST_METHOD") == 'POST') && $this->validateForm()) {
$this->load->model('account/login_model');
$user_info = $this->login_model->get_user($this->input->post('username'));
if ($user_info) {
$_SESSION['user_id'] = $user_info['user_id'];
redirect(base_url('usercp'));
}
}
$data['login_url'] = $this->googleplus->loginURL();
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['username'])) {
$data['error_username'] = $this->error['username'];
} else {
$data['error_username'] = '';
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
// Common
$data['header'] = Modules::run('common/header/index');
$data['navbar'] = Modules::run('common/navbar/index');
$data['footer'] = Modules::run('common/footer/index');
$this->load->view('login', $data);
}
public function validateForm() {
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->error['username'] = form_error('username', '<div class="text-danger">', '</div>');
$this->error['password'] = form_error('password', '<div class="text-danger">', '</div>');
}
if ($this->input->post('username') && $this->input->post('password')) {
$this->load->model('account/login_model');
if (!$this->login_model->verify_password($this->input->post('username'), $this->input->post('password'))) {
$this->error['warning'] = 'Incorrect login credentials';
}
}
return !$this->error;
}
public function google() {
if ($this->input->get('code')) {
$googleplus_auth = $this->googleplus->getAuthenticate();
$googleplus_info = $this->googleplus->getUserInfo();
$google_data = array(
'google_id' => $googleplus_info['id'],
'google_name' => $googleplus_info['name'],
'google_link' => $googleplus_info['link'],
'image' => $googleplus_info['picture'],
'email' => $googleplus_info['email'],
'firstname' => $googleplus_info['given_name'],
'lastname' => $googleplus_info['family_name']
);
$login_google_userid = $this->login_model->login_with_google($googleplus_info['id'], $google_data);
$_SESSION['user_id'] = $login_google_userid;
redirect('usercp');
}
}
}
Codeigniter's redirect() function uses the php header() function in 2 ways:
switch ($method)
{
case 'refresh':
header('Refresh:0;url='.$uri);
break;
default:
header('Location: '.$uri, TRUE, $code);
break;
}
using the refresh parameter will not add the hashtag.
You find more about this in system/helpers/url_helper.php
you can use this to your advantage in google_login.php changing
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
accordingly to
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Refresh:0;url=' . filter_var($redirect, FILTER_SANITIZE_URL));
When calling the redirect, you should be able to drop the hash by using the refresh param:
redirect('usercp', 'refresh');
You can modifying the url by doing something like
$url = strstr($url, '#', true);
But otherwise since it's a client-side stuff there's not a lot of options. You could also remove it from javascript when the client load the page with
history.pushState('', document.title, window.location.pathname + window.location.search)
since this is too long in the comment section, here goes:
try to use your browser's debug mode/developer tools, and see the network part of it. in there, you could see the sequence of requests when your page are loading.
if you are using chrome, thick the preserve log option before doing the oauth.
do the oauth and then try to find the request to google that redirects to your page.
click on the request, you will get the details of the request.
see for the response header, it should be 302 status and the destination should be your http://www.example.com/usercp url.
if you did not see the #, then you have problems in your part, try to check your .htaccess file.
if it's there in the destination, then the problem lies in google part, and not much you can do about it

Resources