How to call shell function to another Controller - Cakephp - shell

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.");
}
}

Related

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.

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

how to i print session on view page in zend framework

I am very new to zend framework, and going to add session in my small application but i dont know how to print session variable to my header.phtml page.
UsersTable.php
public function fetchbyWhere($where) {
$rowset = $this->tableGateway->select($where);
$row = $rowset->current();
if (!$row) {
return;
}
return $row;
}
IndexController.php
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Model\Users; // <-- Add this import
use Zend\Session\Container; // We need this when using sessions
class IndexController extends AbstractActionController {
protected $usersTable;
public function getUsersTable() {
if (!$this->usersTable) {
$sm = $this->getServiceLocator();
$this->usersTable = $sm->get('Application\Model\UsersTable');
}
return $this->usersTable;
}
public function indexAction() {
$request = $this->getRequest();
if ($request->isPost()) {
$user = $request->getPost('txtuser');
$pass = $request->getPost('txtpassword');
$wher = array('username' => $user, 'password' => $pass);
$resultSet = $this->getUsersTable()->fetchbyWhere($wher);
//var_dump($resultSet);
if($resultSet)
{
$user_session = new Container('user');
$user_session->ses_user = $resultSet->username;
return new ViewModel(array(
'msg' => 'valid user',
'sesuser' => $user_session->ses_user,
));
}
else {
return new ViewModel(array(
'msg' => 'not a valid user',
));
}
} else {
return new ViewModel();
}
}
}
now i dont know how to print this session on header.phtml page.
You need to add session container in your header file as well.
Add following line in your header file.
<?php
use Zend\Session\Container; // We need this when using sessions
$user_session = new Container('user');
if(isset($user_session->ses_user))
echo "user:".$user_session->ses_user;
?>

Why laravel assertions are not called from closure?

My code is:
public function testOne()
{
$mail = ['subject' => 'My subject'];
$this->assertEquals(1, 1);
$mock = Mockery::mock(\Illuminate\Support\Facades\Mail::getSwiftMailer());
$this->app['mailer']->setSwiftMailer($mock);
$msg = $mock->shouldReceive('send')->once()->andReturnUsing(function($msg) {
echo $msg->getSubject();
$this->assertEquals($mail['subject'], $msg->getSubject());
});
$this->assertEquals(1, 1);
}
I get output:
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.
My subject
Time: 852 ms, Memory: 26.00Mb
OK (1 test, 2 assertions)
I see from output:
echo $msg->getSubject();
that I get good subject but nothing is asserted, why?
Use like this
public function testOne()
{
$mail = ['subject' => 'My subject'];
$this->assertEquals(1, 1);
$mock = Mockery::mock(\Illuminate\Support\Facades\Mail::getSwiftMailer());
$this->app['mailer']->setSwiftMailer($mock);
$obj = $this;
$msg = $mock->shouldReceive('send')->once()->andReturnUsing(function($msg) use ($obj, $mail) {
echo $msg->getSubject();
$obj->assertEquals($mail['subject'], $msg->getSubject());
});
$this->assertEquals(1, 1);
}
Inside your closure it's an instance of Closure so it will not get $this from there for that you have to assign to another variable & use it.
But you can rewrite your tests like this
public function testOne()
{
$mail = ['subject' => 'My subject'];
$this->assertEquals(1, 1);
$mock = Mockery::mock(\Illuminate\Support\Facades\Mail::getSwiftMailer());
$this->app['mailer']->setSwiftMailer($mock);
$message = null;
$mock->shouldReceive('send')->once()->andReturnUsing(function($msg) use ($message) {
$message = $msg->getSubject();
});
$this->assertEquals($mail['subject'], $message);
$this->assertEquals(1, 1);
}

CodeIgniter form validation always return false

I've been scouring the webs and potching with my code for hours now and can't seem to figure out why this isn't working.
I have a template library which scans a template.html for {#tags} and then runs the function associated to the tag to create data for that {#tag}'s content and then replaces {#tag} for the content generated, so I can have widget like parts to my template.
On my account/access page I have a login form and a registration form, now when the template library calls the widget_register() function, the form validation doesn't seem to do anything, the data is posted as I can see from the profiler, but the form validation doesn't seem to do anything with it
Account Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Account extends CI_Controller {
public function index()
{
$this->load->helper('url');
#redirect('/');
}
public function access()
{
$this->load->helper('url');
#if($this->auth->loggedin()) redirect('/');
$this->template->compile_page();
}
public function widget_register($template)
{
$this->output->enable_profiler(TRUE);
$this->load->helper('url');
if($this->auth->loggedin()) redirect('/');
if ($this->input->post('register_submit'))
{
$this->load->model('auth_model');
$this->form_validation->set_rules('register_nickname', 'Nickname', 'required|min_length[3]|max_length[75]');
$this->form_validation->set_rules('register_email_address', 'Email Address', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('register_confirm_email_address', 'Confirm Email Address', 'required|valid_email|matches[register_email_address]');
$this->form_validation->set_rules('register_password', 'Password', 'required|min_length[5]');
$this->form_validation->set_rules('register_confirm_password', 'Confirm Password', 'required|min_length[5]|matches[register_password]');
if($this->form_validation->run() !== false)
{
echo 'validation successful';
$nickname = $this->input->post('register_nickname');
$email = $this->input->post('register_email_address');
$generate_salt = $this->auth->generate_keys();
$salt = $generate_salt['1'];
$this->load->library('encrypt');
$generate_password = $salt . $this->input->post('register_password');
$password = $this->encrypt->hash($generate_password);
$generate_series_key = $this->auth->generate_keys();
$user_series_key = $generate_series_key['1'];
$this->db->query('INSERT INTO users (nickname, email, password, salt, register_date) VALUES ( "'.$nickname.'", "'.$email.'", "'.$password.'", "'.$salt.'", "'.time().'")');
}
else
{
echo 'invalid';
echo validation_errors();
}
}
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open('account/access');
$view_data['input_nickname'] = form_input(array('name' => 'register_nickname', 'value' => set_value('register_nickname'), 'id' => 'register_nickname', 'class' => 'common_input', 'size' => '55'));
$view_data['input_email'] = form_input(array('name' => 'register_email_address', 'value' => set_value('register_email_address'), 'id' => 'register_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_email'] = form_input(array('name' => 'register_confirm_email_address', 'value' => '', 'id' => 'register_confirm_email_address', 'class' => 'common_input', 'size' => '55'));
$view_data['input_password'] = form_password(array('name' => 'register_password', 'value' => '', 'id' => 'register_password', 'class' => 'common_input', 'size' => '55'));
$view_data['input_confirm_password'] = form_password(array('name' => 'register_confirm_password', 'value' => '', 'id' => 'register_confirm_password', 'class' => 'common_input', 'size' => '55'));
$view_data['form_submit'] = form_submit('register_submit', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/'.$template.'.html', $view_data, TRUE);
}
function widget_login()
{
$this->load->helper('url');
// user is already logged in
if ($this->auth->loggedin())
{
return $this->load->view(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/user.html', '', TRUE);
}
if($this->input->post('register'))
{
redirect('authentication/register');
}
// form submitted
if ($this->input->post('login_email_address') && $this->input->post('login_password'))
{
$this->load->library('form_validation');
$this->load->model('auth_model');
$this->form_validation->set_rules('login_email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('login_password', 'Password', 'required|min_length[4]');
if($this->form_validation->run() !== false)
{
// validation passed verify from db
$remember = $this->input->post('remember') ? TRUE : FALSE;
if($remember == 'remember');
// check user exists and return user data
$user_data = $this->auth_model->user_exists($this->input->post('email_address'), TRUE);
if($user_data != FALSE)
{
// compare passwords
if ($this->auth_model->check_password($this->input->post('password'), $this->input->post('email_address')))
{
$this->auth->login($user_data->uid, $remember);
redirect('/');
}
else { $this->form_validation->set_custom_error('Incorrect password'); }
}
else { $this->form_validation->set_custom_error('There are no users with that email address'); }
}
}
// show login form
$this->load->helper('form');
$view_data = array();
$view_data['form'] = form_open();
$view_data['input_email'] = form_input('login_email_address', set_value('login_email_address'), 'id="login_email_address"');
$view_data['input_password'] = form_password('login_password', '', 'id="login_password"');
$view_data['input_remember'] = form_checkbox('remember', 'rememberme');
$view_data['form_submit'] = form_submit('login_submit', 'Login');
$view_data['register_button'] = form_submit('register', 'Register');
$view_data['/form'] = form_close();
$view_data['validation_errors'] = validation_errors('<div class="error-box">', '</div>');
return $this->parser->parse(FCPATH.'themes/'.$this->settings->settings['system_settings']['theme'].'/widgets/login/login.html', $view_data, TRUE);
}
function logout()
{
$this->load->helper('url');
$this->session->sess_destroy();
$this->load->helper('cookie');
delete_cookie('aws_session');
delete_cookie('aws_autologin_cookie');
redirect('/');
}
}
and the Template library
class Template {
private $settings;
private $_ci;
private $_controller = ''; # Controller in use
private $_method = ''; # Method in use
private $_is_mobile = FALSE; # Is the User agent a mobile?
private $cache_lifetime = '1';
private $page_output = "";
private $partials = array();
private $spts = array(); # Static page tags
function __construct()
{
$this->_ci =& get_instance();
$this->settings = $this->_ci->settings->settings;
$this->_controller = $this->_ci->router->fetch_class();
$this->_method = $this->_ci->router->fetch_method();
$this->_ci->load->library('user_agent');
$this->_is_mobile = $this->_ci->agent->is_mobile();
log_message('debug', "Template Class Initialized");
}
function build_page()
{
$page = $this->_ci->load->view(FCPATH.'themes/'.$this->settings['system_settings']['theme'].'/pages/'.$this->settings['page_settings']['template'].'.html', '', TRUE);
$this->page_output .= $page;
}
# MAIN PAGE FUNCTIONS END ------------------------------------------------------------------------------------------
public function check_static_tags()
{
if(preg_match_all('/{#[A-Z]{1,75}}/', $this->page_output, $matches))
{
$this->spts = $matches['0'];
$this->spts = array_diff($this->spts, array('{#CONTENT}')); # removes stp_content from array list
return TRUE;
}
return FALSE;
}
# Convert static tags
public function convert_static_tags()
{
foreach($this->spts as $key => $static_tag)
{
$static_tag = str_replace(array('{','}'), '', $static_tag);
$this->partials[$static_tag] = $this->build_widget($static_tag);
}
}
# Convert widget tags
function column_widget_tags()
{
if(preg_match_all('/{#COLUMN_[0-9]{1,11}}/', $this->page_output, $matches))
{
if(isset($this->settings['page_settings']['widgets']))
{
$columns = unserialize($this->settings['page_settings']['widgets']);
}
foreach($columns as $column_id => $widgets)
{
if(count($columns[$column_id]) > '0') // if the column contains widgets
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
foreach($widgets as $key => $widget_id)
{
// build the widget and add it to the $this->page_bits['column_id'] variable for replacing later in the compiler
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] .= $this->build_widget($widget_id);
}
}
else
{
$this->partials[''.$this->_stp.'_COLUMN_'.$column_id] = '';
}
}
}
}
# Build Widget
function build_widget($widget_id)
{
if(is_numeric($widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE id = "'.$widget_id.'"'); # BIND STATEMENTS
}
elseif(preg_match('/#[A-Z]{1,75}/', $widget_id))
{
$widget_query = $this->_ci->db->query('SELECT * FROM widgets WHERE tag = "'.$widget_id.'"'); # BIND STATEMENTS
}
else
{
show_error('Could not get widget from database: '.$widget_id);
}
if($widget_query->num_rows() > 0)
{
$widget_info = $widget_query->row_array();
// loads widgets parent controller, builds the widget (class method) and returns it
$this->_ci->load->controller($widget_info['controller'], $widget_info['controller']);
$method_name = 'widget_'.$widget_info['method'];
$complete_widget = $this->_ci->$widget_info['controller']->$method_name($widget_info['template']);
return $complete_widget;
}
else
{
show_error('The requested widget could not be loaded: '.$widget_id);
}
}
# Replace Partials
function replace_partials()
{
$this->_ci->load->library('parser');
$this->page_output = $this->_ci->parser->parse_string($this->page_output, $this->partials, TRUE);
}
## METADATA
public function prepend_metadata($line)
{
array_unshift($this->_metadata, $line);
return $this;
}
# Put extra javascipt, css, meta tags, etc after other head data
public function append_metadata($line)
{
$this->_metadata[] = $line;
return $this;
}
# Set metadata for output later
public function set_metadata($name, $content, $type = 'meta')
{
$name = htmlspecialchars(strip_tags($name));
$content = htmlspecialchars(strip_tags($content));
// Keywords with no comments? ARG! comment them
if ($name == 'keywords' AND ! strpos($content, ','))
{
$content = preg_replace('/[\s]+/', ', ', trim($content));
}
switch($type)
{
case 'meta':
$this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
break;
case 'link':
$this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />';
break;
}
return $this;
}
# Embed page into layout wrapper
function layout()
{
$this->_ci->load->helper('html');
$this->append_metadata(link_tag('themes/'.$this->settings['system_settings']['theme'].'/css/layout.css')); # default stylesheet
$this->append_metadata('<link rel="shortcut icon" href="/favicon2.ico" />'); # default favicon
$template['template.title'] = $this->settings['page_settings']['title']; # Page title, can be overidden by the controller ?
$template['template.metadata'] = implode("\n\t\t", $this->_metadata); # Metadata
$template['template.body'] = $this->page_output; # The page
return $this->_ci->parser->parse(FCPATH.'assets/layout/L6_layout_wrapper.html', $template, TRUE);
}
# Run all functions to build page and set in output class
function compile_page($content_data = '')
{
$this->partials['#CONTENT'] = $content_data;
$this->build_page();
$this->column_widget_tags();
if($this->check_static_tags())
{
$this->convert_static_tags();
$this->replace_partials();
}
$output = $this->layout();
$this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
$this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
$this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
$this->_ci->output->set_header('Pragma: no-cache');
# Let CI do the caching instead of the browser
#$this->_ci->output->cache($this->cache_lifetime);
$this->_ci->output->append_output($output);
}
}
Sorry for the incredibly long post, I'm really stumped here and didn't want to miss any code out, thanks in advance!

Resources