Component View displaying with 500 Internal Server Error - joomla

I have having issues following the tutorial of component development of Joomla. The tutorials I followed related to the issue are this and this.
I can view the default view properly, but when I click the new or edit and delete button, or when I browse too ../administrator/index.php?option=com_testimonials&view=testimonial&layout=edit I get that error.
I have rechecked the code so many times but I just can't find where I went wrong.
File: controllers\testimonial.php
class TestimonialsControllerTestimonial extends JControllerForm
{
//Nothing yet as per the tutorial
}
File: models\testimonial.php
class TestimonialsModelTestimonial extends JModelAdmin {
public function getTable($type = 'Testimonials', $prefix = 'TestimonialsTable', $config = array()) {
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true) {
// Get the form
$form = $this -> loadForm('com_testimonials.testimonial', 'testimonial', array('control' => 'jform', 'load_data' => $loadData));
if(empty($form)) {
return false;
}
return $form;
}
protected function loadFormData() {
// Check the session for previously entered form data
$data = JFactory::getApplication() -> getUserState('com_testimonials.edit.testimonial.data', array());
if(empty($data)) {
$data = $this -> getItem();
}
return $data;
}
}
File: views\testimonial\view.html.php
class TestimonialsViewTestimonial extends JView {
protected $form = null;
public function display($tpl = null) {
//get the data
$form = $this -> get('Form');
$item = $this -> get('Item');
$this -> form = $form;
$this -> item = $item;
$this -> addToolbar();
parent::display($tpl);
$this -> setDocument();
}
protected function addToolBar() {
JRequest::setVar('hidemainmenu', true);
$isNew = ($this -> item -> id == 0);
JToolBarHelper::title($isNew ? JText::_('COM_TESTIMONIALS_MANAGER_TESTIMONIAL_NEW') : JText::_('COM_TESTIMONIALS_MANAGER_TESTIMONIAL_EDIT'), 'testimonials');
JToolBarHelper::save('testimonial.save');
JToolBarHelper::cancel('testimonial.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
}
protected function setDocument() {
$isNew = ($this -> item -> id < 1);
$document = JFactory::getDocument();
$document -> setTitle($isNew ? JText::_('COM_TESTIMONIALS_TESTIMONIAL_CREATING') : JText::_('COM_TESTIMONIALS_TESTIMONIAL_EDITING'));
}
}
File: views\testimonial\tmpl\edit.php
<form action="<?php echo JRoute::_('index.php?option=com_testimonials&layout=edit&id='.(int) $this -> item -> id); ?>" method="post" name="adminForm" id="testimonial-form">
<fieldset class="adminForm">
<legend><?php echo JText::_('COM_TESTIMONIALS_TESTIMONIAL_DETAILS'); ?></legend>
<ul class="adminFormList">
<?php foreach($this -> form -> getFieldset() as $field): ?>
<li><?php echo $field -> label; echo $field -> input; ?></li>
<?php endforeach; ?>
</ul>
</fieldset>
<div>
<input type="hidden" name="task" value="testimonial.edit" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>

The problem is in your view folder name. Change testimonials folder name to testimonial as you have specified view=testimonial.
let me know if it does not work.
Update:
As discussed your table having naming problem-
class TestimonialsTableTestimonial extends JTable
{
public function __construct(&$db) {
parent::__construct('#__testimonial_table', 'id', $db);
}
function bind($array, $ignore = '')
{
return parent::bind($array, $ignore);
}
}

Related

undefined variable in codeigniter view which is already defined in the controller

This is my controller. here i declared current_company.
public function index($id='')
{
$this->load->model('Company_model');
($id!='') ? $data["company_details"]=$this->Company_model->get_company($id) :'';
($id!='') ? $data ["current_company"]=$this->Company_model->get_currentcomp($id) :'';
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',($id!='') ? $data : '');
$this->load->view('includes/footer');
}
This is my model. Here i declared the function
class Company_model extends CI_Model{
protected $strTableName = 'suc_company';
function __construct(){
parent::__construct ();
$this->db->from($this->strTableName);
}
function get_currentcomp($intPkId){
$this->db->where('pk_bint_company_id',$intPkId);
$q1 = $this->db->get($this->strTableName);
return $q1->result_array()[0];
}
This is the view part. here i called the $current_company !== FALSE then
<div class="form-group">
<label for="company_package" class="col-sm-3 control-label"> Package</label>
<div class="col-sm-9 col-xs-12">
<?php if ($current_company !== FALSE ) {?>
<select name="company_package" class="form-control select2" disabled="">
<option value="<?php echo $company_package;?>" selected=""><?php echo $packagename;?></option>
</select>
<?php } else { ?>
<?php } ?>
Error
an error is occurring... undefined data current_company
Change your controller code like this.
public function index($id='')
{
$this->load->model('Company_model');
$data["company_details"] = false;
$data["current_company"] = false;
if($id != ''){
$data["company_details"] = $this->Company_model->get_company($id);
$data["current_company"] = $this->Company_model->get_currentcomp($id);
}
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage',$data);
$this->load->view('includes/footer');
}
As said in comment, you are leaving possibility that maybe $data wouldn't be passed to view file. You have to restrict this kind of oscillations.
Try this way:
public function index($id='')
{
if ((int)$id < 1) {
redirect('some/generic/place', 'refresh');
}
// we have integer in parameter
// so we will check if data by that parameter exists
$data = [];// initialization of array so we are sure $data is set
$this->load->model('Company_model');
$data['company_details'] = $this->Company_model->get_company($id);
if ($data['company_details']) {
$data['current_company'] = $this->Company_model->get_currentcomp($id) :'';
} else {
// in this point $data is an empty array
}
// $this way variable will be available in all view files
$this->load->var($data);
$this->load->view('includes/header');
$this->load->view('includes/left_menu');
$this->load->view('company/manage');
$this->load->view('includes/footer');
// so now, in your view you would have wether company with details wether an empty array
// *first line of code assumes parameter would be an integer
// **also assumed that $this->Company_model->get_company($id) would return false/null/anEmptyArray if data doesn't exist
}

CakePHP 3.1 : My validation for translate behaviour fields, need some help in review/comment

I have worked on a hook for validate my translated fields, based on this thread : https://stackoverflow.com/a/33070156/4617689. That i've done do the trick, but i'm looking for you guys to help me to improve my code, so feel free to comment and modify
class ContentbuildersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Tree');
$this->addBehavior('Timestamp');
$this->addBehavior('Translate', [
'fields' => [
'slug'
]
]);
}
public function validationDefault(Validator $validator)
{
$data = null; // Contain our first $context validator
$validator
->requirePresence('label')
->notEmpty('label', null, function($context) use (&$data) {
$data = $context; // Update the $data with current $context
return true;
})
->requirePresence('type_id')
->notEmpty('type_id')
->requirePresence('is_activated')
->notEmpty('is_activated');
$translationValidator = new Validator();
$translationValidator
->requirePresence('slug')
->notEmpty('slug', null, function($context) use (&$data) {
if (isset($data['data']['type_id']) && !empty($data['data']['type_id'])) {
if ($data['data']['type_id'] != Type::TYPE_HOMEPAGE) {
return true;
}
return false;
}
return true;
});
$validator
->addNestedMany('translations', $translationValidator);
return $validator;
}
}
I'm not proud of my trick with the $data, but i've not found a method to get the data of the validator into my nestedValidator...
Important part here is to note that i only rule of my nestedValidator on 'translations', this is very important !
class Contentbuilder extends Entity
{
use TranslateTrait;
}
Here basic for I18ns to work
class BetterFormHelper extends Helper\FormHelper
{
public function input($fieldName, array $options = [])
{
$context = $this->_getContext();
$explodedFieldName = explode('.', $fieldName);
$errors = $context->entity()->errors($explodedFieldName[0]);
if (is_array($errors) && !empty($errors) && empty($this->error($fieldName))) {
if (isset($errors[$explodedFieldName[1]][$explodedFieldName[2]])) {
$error = array_values($errors[$explodedFieldName[1]][$explodedFieldName[2]])[0];
$options['templates']['inputContainer'] = '<div class="input {{type}} required error">{{content}} <div class="error-message">' . $error . '</div></div>';
}
}
return parent::input($fieldName, $options);
}
}
With that formHelper we gonna get the errors of nestedValidation and inject them into the input, i'm not confortable with the templates, so that's why it's very ugly.
<?= $this->Form->create($entity, ['novalidate', 'data-load-in' => '#right-container']) ?>
<div class="tabs">
<?= $this->Form->input('label') ?>
<?= $this->Form->input('type_id', ['empty' => '---']) ?>
<?= $this->Form->input('is_activated', ['required' => true]) ?>
<?= $this->Form->input('translations.fr_FR.slug') ?>
<?= $this->Form->input('_translations.en_US.slug') ?>
</div>
<?php
echo $this->Form->submit(__("Save"));
echo $this->Form->end();
?>
Here my fr_FR.slug is required when type_id is not set to Type::TYPE_HOMEPAGE, yeah my homepage has not slug, note that the en_US.slug is not required at all, because i only required 'translations.xx_XX.xxxx' and not '_translations.xx_XX.xxxx'.
And the last part of the code, the controller
$entity = $this->Contentbuilders->patchEntity($entity, $this->request->data);
// We get the locales
$I18ns = TableRegistry::get('I18ns');
$langs = $I18ns->find('list', [
'keyField' => 'id',
'valueField' => 'locale'
])->toArray();
// Merging translations
if (isset($entity->translations)) {
$entity->_translations = array_merge($entity->_translations, $entity->translations);
unset($entity->translations);
}
foreach ($entity->_translations as $lang => $data) {
if (in_array($lang, $langs)) {
$entity->translation($lang)->set($data, ['guard' => false]);
}
}
Here a .gif of the final result om my side : http://i.giphy.com/3o85xyrLOTd7q0YVck.gif

Object of class error in Codeigniter with loading function in array

On my Welcome controller I have a function called content_top which loads function $this->$part[0]($setting_info); in this case $this->slideshow($setting_info); Then it should display that slideshow functions view in that data array.
When I have refreshed my page I get a error
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/content_top.php
Line Number: 7
Backtrace:
File: C:\wamp\www\cms\application\views\common\content_top.php
Line: 7
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 51
Function: view
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 19
Function: content_top
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
And
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_Loader could not be converted to string
Filename: common/welcome_message.php
Line Number: 3
Backtrace:
File: C:\wamp\www\cms\application\views\common\welcome_message.php
Line: 3
Function: _error_handler
File: C:\wamp\www\cms\application\controllers\Welcome.php
Line: 20
Function: view
File: C:\wamp\www\cms\index.php
Line: 292
Function: require_once
Question Is there any way to when I have a function in array to be able to make it display the view with out throwing error.
<?php
class Welcome extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->load->view('common/header');
$data['content_top'] = $this->content_top();
$this->load->view('common/welcome_message', $data);
$this->load->view('common/footer');
}
public function content_top() {
if ($this->uri->segment(1)) {
$route = $this->uri->segment(1) .'/'. $this->uri->segment(2);
} else {
$route = 'common/home';
}
$layout_id = $this->model_layout->get_layout($route);
$data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
if (isset($part[1])) {
$setting_info = $this->model_module->get_module($part[1]);
if ($setting_info) {
$data['modules'][] = $this->$part[0]($setting_info);
}
}
}
return $this->load->view('common/content_top', $data);
}
public function slideshow($setting_info) {
static $module = 0;
$data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$data['module'] = $module++;
$data['resize_errors'] = $this->image_lib->display_errors();
return $this->load->view('module/slideshow', $data);
}
}
In the CI when you loading the view and printing as a string then need to pass the third parameter as 'TRUE'.
<?php echo $this->load->view('headers/menu', '', TRUE);?>
Solved
On the controller I had to change a couple things around
I also have had to use a template layout to minimize the views
But on content_top and sideshow function I had to use return and true
return $this->load->view('folder/name', $this->data, TRUE);
Controller
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('design/model_layout');
$this->load->model('extension/model_module');
$this->load->model('design/model_banner');
$this->load->model('tool/model_image');
$this->load->library('image_lib');
}
public function index() {
$this->data['title'] = 'Home';
$this->data = array(
'column_left' => $this->column_left(),
'column_right' => $this->column_right(),
'content_bottom' => $this->content_bottom(),
'content_top' => $this->content_top(),
'page' => 'common/home'
);
$this->load->view('common/template', $this->data);
}
public function column_left() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_left');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_left', $this->data, TRUE);
}
public function column_right() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'column_right');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/column_right', $this->data, TRUE);
}
public function content_bottom() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_bottom');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_bottom', $this->data, TRUE);
}
public function content_top() {
$route = 'common/home';
$layout_id = $this->model_layout->get_layout($route);
$this->data['modules'] = array();
$modules = $this->model_layout->get_layout_modules($layout_id, 'content_top');
foreach ($modules as $module) {
$part = explode('.', $module['code']);
$setting_info = $this->model_module->get_module($part[1]);
$this->data['modules'][] = array (
'module_name' => $this->$part[0]($setting_info)
);
}
return $this->load->view('common/content_top', $this->data, TRUE);
}
/*
Add function for modules that are enabled for this page
*/
public function slideshow($setting_info) {
static $module = 0;
$this->data['banners'] = array();
$results = $this->model_banner->get_banner($setting_info['banner_id']);
foreach ($results as $result) {
$this->data['banners'][] = array(
'banner_image' => $this->model_image->resize($result['banner_image'], $setting_info['width'], $setting_info['height'])
);
}
$this->data['module'] = $module++;
return $this->load->view('module/slideshow', $this->data, TRUE);
}
}
Template View
<?php $this->load->view('common/header');?>
<?php $this->load->view($page);?>
<?php $this->load->view('common/footer');?>
Content Top View
<?php foreach ($modules as $module) {?>
<?php echo $module['module_name'];?>
<?php }?>
Home View
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php echo $content_top;?>
</div>
</div>
</div>
Proof Working
This happened to me when I did this:
$model = $this->load->model('user_model);
$data = [
'model' => $model
];
instead of this:
$this->load->model('user_model);
$model = $this->user_model->edit();
$data = [
'model' => $model
];
then when I echoed out the $model, it gave me the error. So I tried to print_r then it gave me a very long array until I realize my mistake. Hope it helps.
Just remove the echo on view page when you are using CI new versions.
<?php $this->load->view('headers/menu');?>
https://stackoverflow.com/a/40675633/2790502

Codeigniter. Controller cannot receive session data

I set session successfully as output profiler show me session name and value.
But when I POST data controller cannot receive session data.
Library is loaded, $config['sess_expire_on_close'] = TRUE I've changed TRUE-FALSE without any success. Also tried rewrite code.
And another question I use two PC and on Linux machine I get error "Header already sent...", but on Win machine I don't receive this message. How to enable it on Win PC. Notices and warnings are enabled.
So ...
Controller kmgld:
function authorisation_user()
{
......
$data['set_cookie'] = "Surname";
......
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
View:
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
}
<!Doctype...>
<form action="<?php echo base_url()?>index.php/kmgld/update_kmgld" method="post" name="">
And again Controller kmgld
function update_kmgld()
{
...update DB
$test=$this->session->userdata('surname');
echo $test; //it is NULL
$this->output->enable_profiler(TRUE); // show me only now session id, ip, user agent
}
you have to set the userdata in the controller, the view isn't the proper place for it. so you probably would do something like this in your controller:
$surname = "Surname";
$this->session->set_userdata('surname',$surname);
$data['set_cookie'] = $surname;
...
$this->load->view('vheader', $data);
don't know if you autoload the session library. otherwise you have to load it in every function you need it.
remove session setting from view and do it in controller:
function authorisation_user()
{
$data['set_cookie'] = "Surname";
$this->session->set_userdata('surname',$set_cookie);
$this->load->view('vheader', $data);//are you sure here is where $data should go ?
$this->load->view('vuser_kmgld');//not $data here?
$this->output->enable_profiler(TRUE); //show me only session name and value which I set
}
Controller:
<?php
class Kmgld extends CI_Controller {
function index()
{
$data['flag'] = "first";
$this->load->model('Mkmgld');
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
function get_kmgld()
{
$this->load->model('Mkmgld');
$this->Mkmgld->get_kmgld();
$this->load->view('vheader');
$this->load->view('kmgld');
$this->load->view('vfooter');
}
function authorisation_user()
{
$this->load->model('Mkmgld');
$surname_session = $this->session->userdata('surname');
$data['surname_post'] = mb_convert_case($this->input->post('surname'), MB_CASE_TITLE, "UTF-8");
$data['user_id'] = $this->Mkmgld->valid_user($data['surname_post']);
$surname = (isset($data['user_id'][0]->surname)? $data['user_id'][0]->surname: "");
if(isset($surname) and $surname !=NULL)
{
$data['query'] = $this->Mkmgld->get_kmgld($data['surname_post']);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$data['set_cookie'] = $data['surname_post'];
$this->session->sess_destroy();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
}else if (isset($surname_session) and $surname_session!= NULL)
{
//echo "you are in session";
$data['query'] = $this->Mkmgld->get_kmgld($surname_session);
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$this->load->view('vheader', $data);
$this->load->view('vuser_kmgld');
$this->load->view('vfooter');
} else
{
$data['flag'] = "wrong";
$this->load->view('vheader');
$this->load->view('vauthorisation',$data);
$this->load->view('vfooter');
}
//echo "<pre>";
//var_dump($data);
$this->output->enable_profiler(TRUE);
}//end authorisation_user()
function update_kmgld()
{
$this->load->model('Mkmgld');
$data['get_trip_target_id'] = $this->Mkmgld->get_trip_target_id();
$trip_target_id = $data['get_trip_target_id'][0]->Auto_increment;
$this->Mkmgld->update_kmgld($this->input->post('day')
,$this->input->post('mon')
,$this->input->post('year')
,$this->input->post('spd_before')
,$this->input->post('spd_after')
,$this->input->post('total')
,$this->input->post('target')
,$this->input->post('approved')
,$this->input->post('user_id')
,$trip_target_id);
$a=$this->session->userdata('surname');
if ($a==NULL)
{
echo $a;
//redirect('kmgld/authorisation_user');
$this->output->enable_profiler(TRUE);
}
}
}//end class kmgld
?>
Model:
enter code here<?php
Class Mkmgld extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_kmgld($surname){
$query = $this->db->query("SELECT
*
FROM `user`
INNER JOIN `user_has_trip`
ON `user`.`user_id` = `user_has_trip`.`user_id`
INNER JOIN `trip_target`
ON `user_has_trip`.`user_has_trip_id` = `trip_target`.`trip_target_id`
WHERE `user`.`surname` = '$surname'
");
return $query->result();
}
function valid_user($surname)
{
$user_id = $this->db->query("SELECT
*
FROM `user`
WHERE `user`.`surname`='$surname'
");
return $user_id->result();
}
function get_trip_target_id()
{
$get_trip_target_id = $this->db->query("SHOW TABLE STATUS LIKE 'trip_target'");
return $get_trip_target_id->result();
}
function update_kmgld($day, $mon, $year, $spd_before, $spd_after, $total, $target, $approved, $user_id, $trip_target_id)
{
$date = $year."-".$mon."-".$day;
$this->db->query("INSERT INTO `trip_target` (`trip_target_id`
,`date`
,`speedometer_before`
,`speedometer_after`
,`duration`
,`target`
,`approved`)
VALUES (NULL
,'$date'
,'$spd_before'
,'$spd_after'
,'$total'
,'$target'
,'$approved')
");
$this->db->query("INSERT INTO `user_has_trip`
(`user_has_trip_id`
,`user_id`
,`trip_target_id`
)
VALUES (NULL
,'$user_id'
,'$trip_target_id'
)
");
}
}//end class
?>
View vauthorisation:
<?php
$surname_value = $this->session->userdata('surname');
?>
<?php
if ($flag =="wrong")
{
echo "...Bad very bad. Try use another language ";
}
?>
html:
form method="post" action="authorisation_user"
input type="text" name="surname"
View vheader:
<?php
if ($set_cookie!=NULL)
{
$this->session->set_userdata('surname',$set_cookie);
echo "cookie set".$set_cookie;
}
?>
View vuser_kmgld:
html:
form action="update_kmgld"
inputs name=day, name=mon, name=year, name=spd_before...etc. After php code:
if (isset($user_id[0]->user_id))
{
foreach ($query as $row)
{
echo "<tr>
<td>".(isset($row->date)? date("d.m.Y", strtotime($row->date)): "")."</td>
<td>". (isset($row->speedometer_before)? $row->speedometer_before : "")."</td>
<td>". (isset($row->speedometer_after)? $row->speedometer_after : "")."</td>
<td>". (isset($row->duration)? $row->duration : "")."</td>
<td>". (isset($row->target)? $row->target : "")."</td>
<td>". (isset($row->aproved)? $row->aproved : "")."</td>
</tr>";
}
} //else redirect('kmgld/index');
?>

Codeigniter - Facebook Login and registeration sing PHP SDK

I am using Facebook PHP SDK with Codeigniter to do login and registration using Facebook. For this I am using This tutorial
my controller 'facebooktest.php' code is:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Facebooktest extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('input');
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('security');
}
function Facebooktest() {
parent::Controller();
$cookies = $this->load->model('facebook_model');
}
function index() {
$this->load->view('facebooktest/test2');
}
function test1() {
$data = array();
$data['user'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test1', $data);
}
function test2() {
$data['friends'] = $this->facebook_model->get_facebook_cookie();
$this->load->view('facebooktest/test2', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
view 'test2.php' has code as:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Kent is Learning CodeIgniter - Test 2</title>
</head>
<body>
<fb:login-button autologoutlink="true"
onlogin="window.location.reload(true);"></fb:login-button>
<div style="width:600px;">
<?
if(isset($friends)){
foreach($friends as $friend){
?>
<img src="http://graph.facebook.com/<?=$friend['id'];?>/picture" title="<?=$friend['name'];?>" />
<?
}
}
?>
</div>
<p><?=anchor('facebook_connect/page4','Go back to page 4 of the tutorial');?></p>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '457228377680583', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
// A user has logged in, and a new cookie has been saved
window.location.reload(true);
} else {
// The user has logged out, and the cookie has been cleared
}
});
</script>
</body>
</html>
And model 'facebook_model.php' has code:
<?php
class Facebook_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_facebook_cookie() {
$app_id = '457228377680583';
$application_secret = '01f660b73bc085f0b78cd22322556495';
if (isset($_COOKIE['fbs_' . $app_id])) {
echo "dfgdsf";exit;
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
} else {
return null;
}
}
function getUser() {
$cookie = $this->get_facebook_cookie();
$user = #json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']), true);
return $user;
}
function getFriendIds($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friend_ids = array();
foreach ($friends['data'] as $friend) {
$friend_ids[] = $friend['id'];
}
if ($include_self == TRUE) {
$friend_ids[] = $cookie['uid'];
}
return $friend_ids;
}
function getFriends($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
print_r($cookie);
$friends = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
if ($include_self == TRUE) {
$friends['data'][] = array(
'name' => 'You',
'id' => $cookie['uid']
);
}
return $friends['data'];
}
function getFriendArray($include_self = TRUE) {
$cookie = $this->get_facebook_cookie();
$friendlist = #json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
$cookie['access_token']), true);
$friends = array();
foreach ($friendlist['data'] as $friend) {
$friends[$friend['id']] = array(
'name' => $friend['name'],
'picture' => 'http://graph.facebook.com/'.$friend['id'].'/picture'
);
}
if ($include_self == TRUE) {
$friends[$cookie['uid']] = 'You';
}
return $friends;
}
}
?>
The problem is that, in model, it is coming inside 'getFriends()'. From there it is going inside 'get_facebook_cookie()'. But it is not going inside if(isset($_COOKIE['fbs_' . $app_id])))
and hence, it is nor displaying data that I want.
So, if possible, please let me know whats wrong with my code.
Thanks in advance....

Resources