CKEditor -> CodeIgniter - php

I am trying to configure CKEditor but I get the following in my source, it seems that the helper is not being sent any of the $data from my index function, My helper is located application/helpers
This is my code:
Helper:
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
/*
* CKEditor helper for CodeIgniter
*
* #author Samuel Sanchez <samuel.sanchez.work#gmail.com> - http://kromack.com/
* #package CodeIgniter
* #license http://creativecommons.org/licenses/by-nc-sa/3.0/us/
* #tutorial http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/
* #see http://codeigniter.com/forums/viewthread/127374/
* #version 2010-08-28
*
*/
/**
* This function adds once the CKEditor's config vars
* #author Samuel Sanchez
* #access private
* #param array $data (default: array())
* #return string
*/
function cke_initialize($data = array()) {
$return = '';
if(!defined('CI_CKEDITOR_HELPER_LOADED')) {
define('CI_CKEDITOR_HELPER_LOADED', TRUE);
$return = '<script type="text/javascript" src="'.base_url(). $data['path'] . '/ckeditor.js"></script>';
$return .= "<script type=\"text/javascript\">CKEDITOR_BASEPATH = '" . base_url() . $data['path'] . "/';</script>";
}
return $return;
}
/**
* This function create JavaScript instances of CKEditor
* #author Samuel Sanchez
* #access private
* #param array $data (default: array())
* #return string
*/
function cke_create_instance($data = array()) {
$return = "<script type=\"text/javascript\">
CKEDITOR.replace('" . $data['id'] . "', {";
//Adding config values
if(isset($data['config'])) {
foreach($data['config'] as $k=>$v) {
// Support for extra config parameters
if (is_array($v)) {
$return .= $k . " : [";
$return .= config_data($v);
$return .= "]";
}
else {
$return .= $k . " : '" . $v . "'";
}
if($k !== end(array_keys($data['config']))) {
$return .= ",";
}
}
}
$return .= '});</script>';
return $return;
}
/**
* This function displays an instance of CKEditor inside a view
* #author Samuel Sanchez
* #access public
* #param array $data (default: array())
* #return string
*/
function display_ckeditor($data = array())
{
// Initialization
$return = cke_initialize($data);
// Creating a Ckeditor instance
$return .= cke_create_instance($data);
// Adding styles values
if(isset($data['styles'])) {
$return .= "<script type=\"text/javascript\">CKEDITOR.addStylesSet( 'my_styles_" . $data['id'] . "', [";
foreach($data['styles'] as $k=>$v) {
$return .= "{ name : '" . $k . "', element : '" . $v['element'] . "', styles : { ";
if(isset($v['styles'])) {
foreach($v['styles'] as $k2=>$v2) {
$return .= "'" . $k2 . "' : '" . $v2 . "'";
if($k2 !== end(array_keys($v['styles']))) {
$return .= ",";
}
}
}
$return .= '} }';
if($k !== end(array_keys($data['styles']))) {
$return .= ',';
}
}
$return .= ']);';
$return .= "CKEDITOR.instances['" . $data['id'] . "'].config.stylesCombo_stylesSet = 'my_styles_" . $data['id'] . "';
</script>";
}
return $return;
}
/**
* config_data function.
* This function look for extra config data
*
* #author ronan
* #link http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/comment-page-5/#comment-545
* #access public
* #param array $data. (default: array())
* #return String
*/
function config_data($data = array())
{
$return = '';
foreach ($data as $key)
{
if (is_array($key)) {
$return .= "[";
foreach ($key as $string) {
$return .= "'" . $string . "'";
if ($string != end(array_values($key))) $return .= ",";
}
$return .= "]";
}
else {
$return .= "'".$key."'";
}
if ($key != end(array_values($data))) $return .= ",";
}
return $return;
}
**.htaccess:**
# Customized error messages.
ErrorDocument 404 /index.php
# Set the default handler.
DirectoryIndex index.php
# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|css|js|images|files|scripts|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>
Source
<script type="text/javascript" src="http://house.dev.local//ckeditor.js"></script><script type="text/javascript">CKEDITOR_BASEPATH = 'http://house.dev.local//';</script><script type="text/javascript">
View
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Editpage extends CI_Controller {
function __construct(){
parent::__construct();
}
function index($id){
if(!$this->session->userdata('logged_in'))redirect('admin/home');
$this->load->helper('ckeditor');
//Ckeditor's configuration
$this->data['ckeditor'] = array(
//ID of the textarea that will be replaced
'id' => 'content',
'path' => 'includes/js/ckedit',
//Optionnal values
'config' => array(
'toolbar' => "Full", //Using the Full toolbar
'width' => "550px", //Setting a custom width
'height' => '100px', //Setting a custom height
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 1' => array (
'name' => 'Blue Title',
'element' => 'h2',
'styles' => array(
'color' => 'Blue',
'font-weight' => 'bold'
)
),
//Creating a new style named "style 2"
'style 2' => array (
'name' => 'Red Title',
'element' => 'h2',
'styles' => array(
'color' => 'Red',
'font-weight' => 'bold',
'text-decoration' => 'underline'
)
)
)
);
if ($this->input->post('submit')){
#The User has submitted updates, lets begin!
#Set The validation Rules
$this->form_validation->set_rules('content', 'Content', 'trim|required|xss_clean');
#if the form_validation rules fail then load the login page with the errors. Otherwise continue validating the user/pass
if ($this->form_validation->run() == FALSE){
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}
#Form Validation passed, so lets continue updating.
#lets set some variables.
$content = $this->input->post('content', TRUE);
#Now if updatePage fails to update hte database then show "there was a problem", you could echo the db error itself
if($this->page_model->updatePage($id, $content)) {
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSContent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['success'] = TRUE;
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if updatePage
}else{
$data['cms_pages'] = $this->navigation_model->getCMSPages($id);
#connect to getCMSCotent and set the page info equal to the $data['page'] where the row is equal to the passed $id from the URL.
$data['page'] = $this->page_model->getCMSContent($id);
$data['content'] = $this->load->view('admin/editpage', $data, TRUE);
$this->load->view('admintemplate', $data);
}//END if post submitted
} //END function index()
}

You do know that you can jst embed CK Editor with JS to a textarea, and not much around with all this.
http://ckeditor.com/demo
Hows you exactly how.. 3 second job.

One issue may be the double slash in your JS paths;
CKEDITOR_BASEPATH = 'http://house.dev.local//';
Also, is .htaccess blocking access to your CKEditor files ?
Where is your helper functions? what does it do ?
If that is the issue, please post it.
Also, your own helpers should NOT going in to 'system/helpers', they go in to your 'application/helpers', system helpers are for core helpers only.

Related

Google Recaptcha being ignored with form action

Just integrated Google Recaptcha. I am using this form as a POST to a secure checkout for a secure transaction site ( API ).
My challenge is, I have the form action =
"action="https://securepayments.cardconnect.com/hpp/payment/"
And event if I use :
if (isset($_POST['submit'])) {
to validate the :: recaptcha :: it still just goes straight to the form action URL without verifying the recaptcha.
Here is more code:
$secret = '-- XX --';
$response = $_POST['g-recaptcha-response'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
$res = json_decode($unpass, TRUE);
$result = json_decode($url, TRUE);
if ($result['success'] == 1) {
echo $_POST['name'];
echo $_POST['companyname'];
}
else { echo 'you are a robot'; }
}
The form action URL passes POST / hidden variables to connect via MID/Password to authenticate itself with the API. I can't figure out how to integrate a solution to use recaptcha and then do the form action. Any help would be awesome!
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => 'secret',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
if($_POST && isValid())
{
//do stuff
}
Why you don't use the Recaptcha Library?
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Recaptcha
{
/*
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* http://recaptcha.net/plugins/php/
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
* Mike Crawford
* Ben Maurer
*
* CONTRIBUTION:
* Codeigniter version - 23.08.2012 by Christer Nordbø, Norway.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
* UPDATE HISTORY:
* 28.08.2013 - Made recaptcha_check_answer() function bit simpler on default
* fields as html is generated by recaptcha_get_html() function.
* Updated by - Puneet Kalra (https://github.com/puneetkay)
*/
/**
* The reCAPTCHA server URL's
*/
const RECAPTCHA_API_SERVER = "http://www.google.com/recaptcha/api";
const RECAPTCHA_API_SECURE_SERVER = "https://www.google.com/recaptcha/api";
const RECAPTCHA_VERIFY_SERVER = "www.google.com";
protected $is_valid;
protected $error;
//Remember to obtain the Public and Private key # https://www.google.com/recaptcha/admin/create
protected $public_key = "YOUR PUBLIC KEY";
protected $privkey = "YOUR PRIVATE KEY";
protected $options = array();
function __construct()
{
log_message('debug', "RECAPTCHA Class Initialized.");
$this->_ci =& get_instance();
//Load the CI Config file for recaptcha
$this->_ci->load->config('recaptcha');
//load in the values from the config file.
$this->public_key = $this->_ci->config->item('public_key');
$this->privkey = $this->_ci->config->item('private_key');
$this->options = $this->_ci->config->item('recaptcha_options');
//Lets do some basic error handling to see if the configuration is A-OK.
$temp_error_msg = '';
if ($this->public_key === 'YOUR PUBLIC KEY') {
$temp_error_msg .= 'You need to set your public key in the config file <br />';
}
if ($this->privkey === 'YOUR PRIVATE KEY') {
$temp_error_msg .= 'You need to set your private key in the config file <br />';
}
if ($temp_error_msg != '') {
show_error($temp_error_msg);
}
}
/**
* Encodes the given data into a query string format
* #param $data - array of string elements to be encoded
* #return string - encoded request
*/
function recaptcha_qsencode($data)
{
$req = "";
foreach ($data as $key => $value)
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
// Cut the last '&'
$req = substr($req, 0, strlen($req) - 1);
return $req;
}
/**
* Submits an HTTP POST to a reCAPTCHA server
* #param string $host
* #param string $path
* #param array $data
* #param int port
* #return array response
*/
function recaptcha_http_post($host, $path, $data, $port = 80)
{
$req = $this->recaptcha_qsencode($data);
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($req) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $req;
$response = '';
if (false == ($fs = #fsockopen($host, $port, $errno, $errstr, 10))) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
while (!feof($fs))
$response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
return $response;
}
function recaptcha_get_html($error = null, $use_ssl = false)
{
if ($this->public_key == null || $this->public_key == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($use_ssl) {
$server = self::RECAPTCHA_API_SECURE_SERVER;
} else {
$server = self::RECAPTCHA_API_SERVER;
}
$errorpart = "";
if ($error) {
$errorpart = "&error=" . $error;
}
$options = "";
foreach ($this->options as $key => $value) {
$options .= $key . ':"' . $value . '", ';
}
return '<script type="text/javascript"> var RecaptchaOptions = { ' . $options . ' }; </script>
<script type="text/javascript" src="' . $server . '/challenge?k=' . $this->public_key . $errorpart . '"></script>
<noscript>
<iframe src="' . $server . '/noscript?k=' . $this->public_key . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>';
}
/**
* Calls an HTTP POST function to verify if the user's guess was correct
* #param string $remoteip
* #param string $challenge
* #param string $response
* #param array $extra_params an array of extra variables to post to the server
* #return ReCaptchaResponse
*/
function recaptcha_check_answer($remoteip = null, $challenge = null, $response = null, $extra_params = array())
{
if ($this->privkey == null || $this->privkey == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
$remoteip = ($remoteip == null) ? $_SERVER['REMOTE_ADDR'] : $remoteip;
$challenge = ($challenge == null) ? $this->_ci->input->post('recaptcha_challenge_field') : $challenge;
$response = ($response == null) ? $this->_ci->input->post('recaptcha_response_field') : $response;
if ($remoteip == null || $remoteip == '') {
die ("For security reasons, you must pass the remote ip to reCAPTCHA");
}
//discard spam submissions
if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
$this->is_valid = false;
$this->error = 'incorrect-captcha-sol';
}
$response = $this->recaptcha_http_post(self::RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
array(
'privatekey' => $this->privkey,
'remoteip' => $remoteip,
'challenge' => $challenge,
'response' => $response
) + $extra_params
);
$answers = explode("\n", $response [1]);
if (trim($answers [0]) == 'true') {
$this->is_valid = true;
} else {
$this->is_valid = false;
$this->error = $answers [1];
}
}
/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
* #param string $domain The domain where the page is hosted
* #param string $appname The name of your application
*/
function recaptcha_get_signup_url($domain = null, $appname = 'Codeigniter')
{
return "https://www.google.com/recaptcha/admin/create?" . $this->recaptcha_qsencode(array('domains' => $domain, 'app' => $appname));
}
function recaptcha_aes_pad($val)
{
$block_size = 16;
$numpad = $block_size - (strlen($val) % $block_size);
return str_pad($val, strlen($val) + $numpad, chr($numpad));
}
/* Mailhide related code */
function recaptcha_aes_encrypt($val, $ky)
{
if (!function_exists("mcrypt_encrypt")) {
die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
}
$mode = MCRYPT_MODE_CBC;
$enc = MCRYPT_RIJNDAEL_128;
$val = $this->recaptcha_aes_pad($val);
return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function recaptcha_mailhide_urlbase64($x)
{
return strtr(base64_encode($x), '+/', '-_');
}
/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($email)
{
if ($this->public_key == '' || $this->public_key == null || $this->privkey == "" || $this->privkey == null) {
die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
"you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
}
$ky = pack('H*', $this->privkey);
$cryptmail = $this->recaptcha_aes_encrypt($email, $ky);
return "http://www.google.com/recaptcha/mailhide/d?k=" . $this->public_key . "&c=" . $this->recaptcha_mailhide_urlbase64($cryptmail);
}
/**
* gets the parts of the email to expose to the user.
* eg, given johndoe#example,com return ["john", "example.com"].
* the email is then displayed as john...#example.com
*/
function recaptcha_mailhide_email_parts($email)
{
$arr = preg_split("/#/", $email);
if (strlen($arr[0]) <= 4) {
$arr[0] = substr($arr[0], 0, 1);
} else if (strlen($arr[0]) <= 6) {
$arr[0] = substr($arr[0], 0, 3);
} else {
$arr[0] = substr($arr[0], 0, 4);
}
return $arr;
}
/**
* Gets html to display an email address given a public an private key.
* to get a key, go to:
*
* http://www.google.com/recaptcha/mailhide/apikey
*/
function recaptcha_mailhide_html($email)
{
$emailparts = $this->recaptcha_mailhide_email_parts($email);
$url = $this->recaptcha_mailhide_url($this->public_key, $this->privkey, $email);
return htmlentities($emailparts[0]) . "<a href='" . htmlentities($url) .
"' onclick=\"window.open('" . htmlentities($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>#" . htmlentities($emailparts [1]);
}
function checkIfIsValid()
{
if ($this->getIsValid()) {
return $this->getIsValid();
} else {
return array($this->getIsValid(), $this->getError());
}
}
function getIsValid()
{
return $this->is_valid;
}
function getError()
{
return $this->error;
}
}
Use it:
$this->load->library('recaptcha');
$this->recaptcha->recaptcha_check_answer();
if (!$this->recaptcha->getIsValid()) {
$this->session->set_flashdata('error', 'Código Captcha incorrecto');
redirect(base_url() . 'add');
}
unset($post['recaptcha_challenge_field']);
unset($post['recaptcha_response_field']);

Custom Joomla profile plugin registered user database table update issues

I have a custom extension that uses the Joomla profile plugin and extends it to provide additional fields to the user profile in the administrator panel and in the registered area on the front end of the website. The fields are set to display to admins-only, be disabled, be optional or be required. When they are set to admin-only, they do not show on the front end of the website in the "edit your profile" form. The plugin handles the UPDATE command for all fields with no issues in the administrator panel, but when the UPDATE command is triggered by a user updating their profile on the front end, all of the admin-only fields are overwritten with empty values. All of the other fields, whether they are optional or required are successfully saved or maintained in the form. I have included the custom profile plugin's PHP code below.
<?php
/**
* #package Joomla.Plugin
* #subpackage User.profile
*
* #copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
/**
* An example custom profile plugin.
*
* #since 1.6
*/
class PlgUserKiduka extends JPlugin
{
/**
* Load the language file on instantiation.
*
* #var boolean
* #since 3.1
*/
protected $autoloadLanguage = true;
/**
* Constructor
*
* #param object &$subject The object to observe
* #param array $config An array that holds the plugin configuration
*
* #since 1.5
*/
public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
JFormHelper::addFieldPath(__DIR__ . '/fields');
}
/**
* Runs on content preparation
*
* #param string $context The context for the data
* #param object $data An object containing the data for the form.
*
* #return boolean
*
* #since 1.6
*/
public function onContentPrepareData($context, $data)
{
// No need to display the context variable as a heading on the registration page
// echo '<h1>'.$context.'</h1>';
// Check we are manipulating a valid form.
if (!in_array($context, array('com_users.profile', 'com_users.user', 'com_users.registration', 'com_admin.profile')))
{
return true;
}
if (is_object($data))
{
$userId = isset($data->id) ? $data->id : 0;
if ($userId > 0)
{
// Load the profile data from the database.
$db = JFactory::getDbo();
$db->setQuery(
'SELECT * FROM #__kiduka_accounts WHERE user_id = ' . $userId
);
$data->kiduka = $db->loadObject();
}
}
return true;
}
/**
* adds additional fields to the user editing form
*
* #param JForm $form The form to be altered.
* #param mixed $data The associated data for the form.
*
* #return boolean
*
* #since 1.6
*/
public function onContentPrepareForm($form, $data)
{
if (!($form instanceof JForm))
{
$this->_subject->setError('JERROR_NOT_A_FORM');
return false;
}
// Check we are manipulating a valid form.
$name = $form->getName();
if (!in_array($name, array('com_admin.profile', 'com_users.user', 'com_users.profile', 'com_users.registration')))
{
return true;
}
foreach(JFactory::getUser()->get('groups') as $group){
if(in_array($group, $this->params->get('usergroup'))){
return true;
}
}
// Add the registration fields to the form.
JForm::addFormPath(__DIR__ . '/profiles');
$form->loadFile('profile', false);
$fields = array(
'firechief',
'title',
'membership_no',
'organization',
'organizationtype',
'membertype',
'afcaregion',
'municipalcode',
'membershipyear',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'notes',
'gstexempt',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry'
);
// Change fields description when displayed in front-end or back-end profile editing
$app = JFactory::getApplication();
foreach ($fields as $field)
{
// Case using the users manager in admin
if ($name == 'com_users.user')
{
// Toggle whether the field is required.
if ($this->params->get('profile-require_' . $field, 1) > 0 || $this->params->get('profile-require_' . $field, 1) == -1)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
// Case registration
elseif ($name == 'com_users.registration')
{
// Toggle whether the field is required.
if ($this->params->get('register-require_' . $field, 1) > 0)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('register-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
// Case profile in site or admin
elseif ($name == 'com_users.profile' || $name == 'com_admin.profile')
{
// Toggle whether the field is required.
if ($this->params->get('profile-require_' . $field, 1) > 0)
{
$form->setFieldAttribute($field, 'required', ($this->params->get('profile-require_' . $field) == 2) ? 'required' : '', 'kiduka');
}
else
{
$form->removeField($field, 'kiduka');
}
}
}
return true;
}
/**
* saves user profile data
*
* #param array $data entered user data
* #param boolean $isNew true if this is a new user
* #param boolean $result true if saving the user worked
* #param string $error error message
*
* #return bool
*/
public function onUserAfterSave($data, $isNew, $result, $error)
{
$user = JFactory::getUser();
$modified_by = $user->get('id');
$userId = JArrayHelper::getValue($data, 'id', 0, 'int');
$datenow = JFactory::getDate();
$modified = $datenow->toSql();
$fields = array(
// 'membership_no',
'title',
'firechief',
'organization',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'organizationtype',
'membertype',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry',
'afcaregion',
'gstexempt',
'notes',
'municipalcode',
'membershipyear'
);
if($isNew){
$query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
foreach($fields as $field){
$query .= ', "'.$data['kiduka'][$field].'"';
}
$query .= ')';
}else{
$query = 'UPDATE #__kiduka_accounts SET ';
$query .= 'modified = "'.$modified.'", ';
$query .= 'modified_by = "'.$modified_by.'", ';
$query .= 'membership_no = "'.$userId.'", ';
for($i = 0; $i < count($fields); $i++){
$query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
if($i < count($fields) - 1){
$query .= ', ';
}
}
$query .= ' WHERE user_id = "'.$userId.'"';
}
// var_dump($data);
// die();
$db = JFactory::getDbo();
$db->setQuery($query);
$db->query();
// var_dump($query);
// die();
return true;
}
public function onUserAfterDelete($user, $success, $msg)
{
if (!$success)
{
return false;
}
$userId = JArrayHelper::getValue($user, 'id', 0, 'int');
if ($userId)
{
try
{
$db = JFactory::getDbo();
$db->setQuery(
'DELETE FROM #__kiduka_accounts WHERE user_id = ' . $userId);
$db->execute();
}
catch (Exception $e)
{
$this->_subject->setError($e->getMessage());
return false;
}
}
return true;
}
}
#Elin I have figured it out. It was suggested on the Joomla forum to use two $fields arrays, one for the front-end profile form and another with all of the fields for the administrator user manager profile form. I have included the PHP code for the onUserAfterSave function below. The if($app->isSite()) if/else shows the limited fields on the front-end profile form and the full list of fields on the administrator profile form.
public function onUserAfterSave($data, $isNew, $result, $error)
{
$app = JFactory::getApplication();
$user = JFactory::getUser();
$modified_by = $user->get('id');
$userId = JArrayHelper::getValue($data, 'id', 0, 'int');
$datenow = JFactory::getDate();
$modified = $datenow->toSql();
if($app->isSite())
{
$fields = array(
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax'
);
}
else
{
$fields = array(
'firechief',
'title',
'organization',
'organizationtype',
'membertype',
'afcaregion',
'municipalcode',
'membershipyear',
'address1',
'address2',
'city',
'province',
'postalcode',
'country',
'businessphone',
'homephone',
'cellphone',
'fax',
'notes',
'gstexempt',
'billorganization',
'billaddress1',
'billaddress2',
'billcity',
'billprovince',
'billpostalcode',
'billcountry'
);
}
if($isNew)
{
$db = JFactory::getDbo();
$query = 'INSERT INTO #__kiduka_accounts VALUES(NULL, '.$userId.', "", '.$userId.', '.$userId;
foreach($fields as $field)
{
$query .= ', "'.$data['kiduka'][$field].'"';
}
$query .= ')';
}
else
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query .= 'UPDATE #__kiduka_accounts SET ';
$query .= 'modified = "'.$modified.'", ';
$query .= 'modified_by = "'.$modified_by.'", ';
$query .= 'membership_no = "'.$userId.'", ';
for($i = 0; $i < count($fields); $i++)
{
$query .= $fields[$i] . ' = "'.$data['kiduka'][$fields[$i]].'"';
if($i < count($fields) - 1)
{
$query .= ', ';
}
}
$query .= ' WHERE user_id = "'.$userId.'"';
}
$db->setQuery($query);
$db->execute();
return true;
}

Zend installed but throwing error php

My host confirmed that Zend 2.3 is installed. I then proceeded to check the installation was working by uploading this script:
http://www.jarodmorris.com/zend_check.php
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#zend.com so we can send you a copy immediately.
*
* #category Zend
* #package Zend_Gdata
* #subpackage Demos
* #copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Simple class to verify that the server that this is run on has a correct
* installation of the Zend Framework Gdata component.
*/
class InstallationChecker {
const CSS_WARNING = '.warning { color: #fff; background-color: #AF0007;}';
const CSS_SUCCESS = '.success { color: #000; background-color: #69FF4F;}';
const CSS_ERROR = '.error { color: #fff; background-color: #FF9FA3;}';
const PHP_EXTENSION_ERRORS = 'PHP Extension Errors';
const PHP_MANUAL_LINK_FRAGMENT = 'http://us.php.net/manual/en/book.';
const PHP_REQUIREMENT_CHECKER_ID = 'PHP Requirement checker v0.1';
const SSL_CAPABILITIES_ERRORS = 'SSL Capabilities Errors';
const YOUTUBE_API_CONNECTIVITY_ERRORS = 'YouTube API Connectivity Errors';
const ZEND_GDATA_INSTALL_ERRORS = 'Zend Framework Installation Errors';
const ZEND_SUBVERSION_URI = 'http://framework.zend.com/download/subversion';
private static $REQUIRED_EXTENSIONS = array(
'ctype', 'dom', 'libxml', 'spl', 'standard', 'openssl');
private $_allErrors = array(
self::PHP_EXTENSION_ERRORS => array(
'tested' => false, 'errors' => null),
self::ZEND_GDATA_INSTALL_ERRORS => array(
'tested' => false, 'errors' => null),
self::SSL_CAPABILITIES_ERRORS => array(
'tested' => false, 'errors' => null),
self::YOUTUBE_API_CONNECTIVITY_ERRORS => array(
'tested' => false, 'errors' => null)
);
private $_sapiModeCLI = null;
/**
* Create a new InstallationChecker object and run verifications.
* #return void
*/
public function __construct()
{
$this->determineIfInCLIMode();
$this->runAllVerifications();
$this->outputResults();
}
/**
* Set the sapiModeCLI variable to true if we are running CLI mode.
*
* #return void
*/
private function determineIfInCLIMode()
{
if (php_sapi_name() == 'cli') {
$this->_sapiModeCLI = true;
}
}
/**
* Getter for sapiModeCLI variable.
*
* #return boolean True if we are running in CLI mode.
*/
public function runningInCLIMode()
{
if ($this->_sapiModeCLI) {
return true;
} else {
return false;
}
}
/**
* Run verifications, stopping at each step if there is a failure.
*
* #return void
*/
public function runAllVerifications()
{
if (!$this->validatePHPExtensions()) {
return;
}
if (!$this->validateZendFrameworkInstallation()) {
return;
}
if (!$this->testSSLCapabilities()) {
return;
}
if (!$this->validateYouTubeAPIConnectivity()) {
return;
}
}
/**
* Validate that the required PHP Extensions are installed and available.
*
* #return boolean False if there were errors.
*/
private function validatePHPExtensions()
{
$phpExtensionErrors = array();
foreach (self::$REQUIRED_EXTENSIONS as $requiredExtension) {
if (!extension_loaded($requiredExtension)) {
$requiredExtensionError = $requiredExtension .
' extension missing';
$documentationLink = null;
if ($requiredExtension != 'standard') {
$documentationLink = self::PHP_MANUAL_LINK_FRAGMENT .
$requiredExtension . '.php';
$documentationLink =
$this->checkAndAddHTMLLink($documentationLink);
} else {
$documentationLink = self::PHP_MANUAL_LINK_FRAGMENT .
'spl.php';
$documentationLink =
$this->checkAndAddHTMLLink($documentationLink);
}
if ($documentationLink) {
$phpExtensionErrors[] = $requiredExtensionError .
' - refer to ' . $documentationLink;
}
}
}
$this->_allErrors[self::PHP_EXTENSION_ERRORS]['tested'] = true;
if (count($phpExtensionErrors) > 0) {
$this->_allErrors[self::PHP_EXTENSION_ERRORS]['errors'] =
$phpExtensionErrors;
return false;
}
return true;
}
/**
* Validate that the Gdata component of Zend Framework is installed
* properly. Also checks that the required YouTube API helper methods are
* found.
*
* #return boolean False if there were errors.
*/
private function validateZendFrameworkInstallation()
{
$zendFrameworkInstallationErrors = array();
$zendLoaderPresent = false;
try {
$zendLoaderPresent = #fopen('Zend/Loader.php', 'r', true);
} catch (Exception $e) {
$zendFrameworkInstallationErrors[] = 'Exception thrown trying to ' .
'access Zend/Loader.php using \'use_include_path\' = true ' .
'Make sure you include the Zend Framework in your ' .
'include_path which currently contains: "' .
ini_get('include_path') . '"';
}
if ($zendLoaderPresent) {
#fclose($zendLoaderPresent);
require_once('Zend/Loader.php');
require_once('Zend/Version.php');
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_YouTube_VideoEntry');
$yt = new Zend_Gdata_YouTube();
$videoEntry = $yt->newVideoEntry();
if (!method_exists($videoEntry, 'setVideoTitle')) {
$zendFrameworkMessage = 'Your version of the ' .
'Zend Framework ' . Zend_Version::VERSION . ' is too old' .
' to run the YouTube demo application and does not' .
' contain the new helper methods. Please check out a' .
' newer version from Zend\'s repository: ' .
checkAndAddHTMLLink(self::ZEND_SUBVERSION_URI);
$zendFrameworkInstallationErrors[] = $zendFrameworkMessage;
}
} else {
if (count($zendFrameworkInstallationErrors) < 1) {
$zendFrameworkInstallationErrors[] = 'Exception thrown trying' .
' to access Zend/Loader.php using \'use_include_path\' =' .
' true. Make sure you include Zend Framework in your' .
' include_path which currently contains: ' .
ini_get('include_path');
}
}
$this->_allErrors[self::ZEND_GDATA_INSTALL_ERRORS]['tested'] = true;
if (count($zendFrameworkInstallationErrors) > 0) {
$this->_allErrors[self::ZEND_GDATA_INSTALL_ERRORS]['errors'] =
$zendFrameworkInstallationErrors;
return false;
}
return true;
}
/**
* Create HTML link from an input string if not in CLI mode.
*
* #param string The error message to be converted to a link.
* #return string Either the original error message or an HTML version.
*/
private function checkAndAddHTMLLink($inputString) {
if (!$this->runningInCLIMode()) {
return $this->makeHTMLLink($inputString);
} else {
return $inputString;
}
}
/**
* Create an HTML link from a string.
*
* #param string The string to be made into link text and anchor target.
* #return string HTML link.
*/
private function makeHTMLLink($inputString)
{
return '<a href="'. $inputString . '" target="_blank">' .
$inputString . '</a>';
}
/**
* Validate that SSL Capabilities are available.
*
* #return boolean False if there were errors.
*/
private function testSSLCapabilities()
{
$sslCapabilitiesErrors = array();
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
$httpClient = new Zend_Http_Client(
'https://www.google.com/accounts/AuthSubRequest');
$response = $httpClient->request();
$this->_allErrors[self::SSL_CAPABILITIES_ERRORS]['tested'] = true;
if ($response->isError()) {
$sslCapabilitiesErrors[] = 'Response from trying to access' .
' \'https://www.google.com/accounts/AuthSubRequest\' ' .
$response->getStatus() . ' - ' . $response->getMessage();
}
if (count($sslCapabilitiesErrors) > 0) {
$this->_allErrors[self::SSL_CAPABILITIES_ERRORS]['errors'] =
$sslCapabilitiesErrors;
return false;
}
return true;
}
/**
* Validate that we can connect to the YouTube API.
*
* #return boolean False if there were errors.
*/
private function validateYouTubeAPIConnectivity()
{
$connectivityErrors = array();
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
$topRatedFeed = $yt->getTopRatedVideoFeed();
if ($topRatedFeed instanceof Zend_Gdata_YouTube_VideoFeed) {
if ($topRatedFeed->getTotalResults()->getText() < 1) {
$connectivityErrors[] = 'There was less than 1 video entry' .
' in the \'Top Rated Video Feed\'';
}
} else {
$connectivityErrors[] = 'The call to \'getTopRatedVideoFeed()\' ' .
'did not result in a Zend_Gdata_YouTube_VideoFeed object';
}
$this->_allErrors[self::YOUTUBE_API_CONNECTIVITY_ERRORS]['tested'] =
true;
if (count($connectivityErrors) > 0) {
$this->_allErrors[self::YOUTUBE_API_CONNECTIVITY_ERRORS]['tested'] =
$connectivityErrors;
return false;
}
return true;
}
/**
* Dispatch a call to outputResultsInHTML or outputResultsInText pending
* the current SAPI mode.
*
* #return void
*/
public function outputResults()
{
if ($this->_sapiModeCLI) {
print $this->getResultsInText();
} else {
print $this->getResultsInHTML();
}
}
/**
* Return a string representing the results of the verifications.
*
* #return string A string representing the results.
*/
private function getResultsInText()
{
$output = "== Ran PHP Installation Checker using CLI ==\n";
$error_count = 0;
foreach($this->_allErrors as $key => $value) {
$output .= $key . ' -- ';
if (($value['tested'] == true) && (count($value['errors']) == 0)) {
$output .= "No errors found\n";
} elseif ($value['tested'] == true) {
$output .= "Tested\n";
$error_count = 0;
foreach ($value['errors'] as $error) {
$output .= "Error number: " . $error_count . "\n--" .
$error . "\n";
}
} else {
$output .= "Not tested\n";
}
$error_count++;
}
return $output;
}
/**
* Return an HTML table representing the results of the verifications.
*
* #return string An HTML string representing the results.
*/
private function getResultsInHTML()
{
$html = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " .
"\"http://www.w3.org/TR/html4/strict.dtd\">\n".
"<html><head>\n<title>PHP Installation Checker</title>\n" .
"<style type=\"text/css\">\n" .
self::CSS_WARNING . "\n" .
self::CSS_SUCCESS . "\n" .
self::CSS_ERROR . "\n" .
"</style></head>\n" .
"<body>\n<table class=\"verification_table\">" .
"<caption>Ran PHP Installation Checker on " .
gmdate('c') . "</caption>\n";
$error_count = 0;
foreach($this->_allErrors as $key => $value) {
$html .= "<tr><td class=\"verification_type\">" . $key . "</td>";
if (($value['tested'] == true) && (count($value['errors']) == 0)) {
$html .= "<td class=\"success\">Tested</td></tr>\n" .
"<tr><td colspan=\"2\">No errors found</td></tr>\n";
} elseif ($value['tested'] == true) {
$html .= "<td class=\"warning\">Tested</td></tr>\n";
$error_count = 0;
foreach ($value['errors'] as $error) {
$html .= "<tr><td class=\"error\">" . $error_count . "</td>" .
"<td class=\"error\">" . $error . "</td></tr>\n";
}
} else {
$html .= "<td class=\"warning\">Not tested</td></tr>\n";
}
$error_count++;
}
$html .= "</body></html>";
return $html;
}
}
$installationChecker = new InstallationChecker();
Go to the above link to see the results. Specifically, I'm interested in this error message:
Exception thrown trying to access Zend/Loader.php using 'use_include_path' = true.
Make sure you include Zend Framework in your include_path which currently contains:
.:/usr/lib/php:/usr/local/lib/php
Here is the link to my php info printout: http://www.jarodmorris.com/cms/phpinfo.php
I've obtained the Zend Framework from the zend website and uploaded it to a /zend folder on my website. For whatever reason, my host won't give me access to the php.ini file. I have purchased a reseller account with my host.
I'm doing all of this because I want to integrate Google Calendar API into an application I'm building on one of my websites. Maybe there is a simpler solution to my ultimate goal, but I don't see it.
Thanks for pointing me in the right direction.
EDITED TO SHOW CURRENT PHP CODE WHERE INCLUDE IS CONCERNED:
set_include_path(get_include_path() . PATH_SEPARATOR . "/home/jarodmo/public_html/zend/library");
echo get_include_path();
echo "<br>";
///home/jarodmo/public_html/zend/library/Zend
Add the dir to your include path:
set_include_path(
get_include_path()
. PATH_SEPARATOR
. '/whatever/your/zend/dir/is');

Js file of ckeditor failed to load in codeigniter

I am trying to integrate ck editor in my admin section.i putted the ck editor folder into my assets folder.here is the code
<script type="text/javascript" src="<?php echo base_url(); ?>assets/admin/ckeditor/ckeditor.js"></script>
after that i make a code for helper.here is the code
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
/*
* CKEditor helper for CodeIgniter
*
* #author Samuel Sanchez <samuel.sanchez.work#gmail.com> - http://kromack.com/
* #package CodeIgniter
* #license http://creativecommons.org/licenses/by-nc-sa/3.0/us/
* #tutorial http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/
* #see http://codeigniter.com/forums/viewthread/127374/
* #version 2010-08-28
*
*/
/**
* This function adds once the CKEditor's config vars
* #author Samuel Sanchez
* #access private
* #param array $data (default: array())
* #return string
*/
function cke_initialize($data = array()) {
$return = '';
if(!defined('CI_CKEDITOR_HELPER_LOADED')) {
define('CI_CKEDITOR_HELPER_LOADED', TRUE);
$return = '<script type="text/javascript" src="'.base_url(). $data['path'] . '/ckeditor.js"></script>';
$return .= "<script type=\"text/javascript\">CKEDITOR_BASEPATH = '" . base_url() . $data['path'] . "/';</script>";
}
return $return;
}
/**
* This function create JavaScript instances of CKEditor
* #author Samuel Sanchez
* #access private
* #param array $data (default: array())
* #return string
*/
function cke_create_instance($data = array()) {
$return = "<script type=\"text/javascript\">
CKEDITOR.replace('" . $data['id'] . "', {";
//Adding config values
if(isset($data['config'])) {
foreach($data['config'] as $k=>$v) {
// Support for extra config parameters
if (is_array($v)) {
$return .= $k . " : [";
$return .= config_data($v);
$return .= "]";
}
else {
$return .= $k . " : '" . $v . "'";
}
if($k !== end(array_keys($data['config']))) {
$return .= ",";
}
}
}
$return .= '});</script>';
return $return;
}
/**
* This function displays an instance of CKEditor inside a view
* #author Samuel Sanchez
* #access public
* #param array $data (default: array())
* #return string
*/
function display_ckeditor($data = array())
{
// Initialization
$return = cke_initialize($data);
// Creating a Ckeditor instance
$return .= cke_create_instance($data);
// Adding styles values
if(isset($data['styles'])) {
$return .= "<script type=\"text/javascript\">CKEDITOR.addStylesSet( 'my_styles_" . $data['id'] . "', [";
foreach($data['styles'] as $k=>$v) {
$return .= "{ name : '" . $k . "', element : '" . $v['element'] . "', styles : { ";
if(isset($v['styles'])) {
foreach($v['styles'] as $k2=>$v2) {
$return .= "'" . $k2 . "' : '" . $v2 . "'";
if($k2 !== end(array_keys($v['styles']))) {
$return .= ",";
}
}
}
$return .= '} }';
if($k !== end(array_keys($data['styles']))) {
$return .= ',';
}
}
$return .= ']);';
$return .= "CKEDITOR.instances['" . $data['id'] . "'].config.stylesCombo_stylesSet = 'my_styles_" . $data['id'] . "';
</script>";
}
return $return;
}
/**
* config_data function.
* This function look for extra config data
*
* #author ronan
* #link http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/comment-page-5/#comment-545
* #access public
* #param array $data. (default: array())
* #return String
*/
function config_data($data = array())
{
$return = '';
foreach ($data as $key)
{
if (is_array($key)) {
$return .= "[";
foreach ($key as $string) {
$return .= "'" . $string . "'";
if ($string != end(array_values($key))) $return .= ",";
}
$return .= "]";
}
else {
$return .= "'".$key."'";
}
if ($key != end(array_values($data))) $return .= ",";
}
return $return;
}
now here is my controller code:
public $data = array();
public function __construct() {
//parent::Controller();
parent::__construct();
$this->load->helper('url'); //You should autoload this one ;)
$this->load->helper('ckeditor');
//Ckeditor's configuration
$this->data['ckeditor'] = array(
//ID of the textarea that will be replaced
'id' => 'content',
'path' => base_url().'assets/admin/js/ckeditor',
//Optionnal values
'config' => array(
'toolbar' => "Full", //Using the Full toolbar
'width' => "550px", //Setting a custom width
'height' => '100px', //Setting a custom height
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 1' => array (
'name' => 'Blue Title',
'element' => 'h2',
'styles' => array(
'color' => 'Blue',
'font-weight' => 'bold'
)
),
//Creating a new style named "style 2"
'style 2' => array (
'name' => 'Red Title',
'element' => 'h2',
'styles' => array(
'color' => 'Red',
'font-weight' => 'bold',
'text-decoration' => 'underline'
)
)
)
);
$this->data['ckeditor_2'] = array(
//ID of the textarea that will be replaced
'id' => 'content_2',
'path' => 'js/ckeditor',
//Optionnal values
'config' => array(
'width' => "550px", //Setting a custom width
'height' => '100px', //Setting a custom height
'toolbar' => array( //Setting a custom toolbar
array('Bold', 'Italic'),
array('Underline', 'Strike', 'FontSize'),
array('Smiley'),
'/'
)
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 3' => array (
'name' => 'Green Title',
'element' => 'h3',
'styles' => array(
'color' => 'Green',
'font-weight' => 'bold'
)
)
)
);
}
and here is my view code:
<textarea name="content" id="content" ><p>Example data</p></textarea>
<?php echo display_ckeditor($ckeditor); ?>
but my ckeditor.js is failed to load please help me or give me the suitable steps for integrating the ck editor in codeigniter.
i got the answer of my own question.
to install the ck editor in codeignitor you just have to follow the below steps:-
1.put the ck editor folder in assets(or in which you want).and give the proper path to js file.
2.now in your view section just include the js file like that:
<script type="text/javascript" src="<?php echo base_url(); ?>assets/admin/ckeditor/ckeditor.js"></script>
3.now on same file put this code:-
<textarea class="ckeditor" name="editor1"></textarea>
4.now you can see the editor on your browser.

Symfony2 links with CSRF token

I can't found a documentation about how to generate a link with the CSRF token, like in Symfony 1.4:
link_to(__('Delete'), url_for('ntw-delete', $network), array('confirm' => 'Are you sure?', 'method' => 'delete'))
UPDATED: I created a twig extension for that. Maybe it will help to someone
src/UmbrellaWeb/Bundle/ExtraTwigBundle/Twig/LinkExtension.php
<?php
namespace UmbrellaWeb\Bundle\ExtraTwigBundle\Twig;
use Twig_Extension;
use Twig_Function_Method;
use Twig_Environment;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface;
class LinkExtension extends Twig_Extension
{
protected $csrfProvider;
public function __construct(CsrfProviderInterface $csrfProvider)
{
$this->csrfProvider = $csrfProvider;
}
public function getFunctions()
{
return array(
'link_to' => new Twig_Function_Method($this, 'linkToFunction', array(
'is_safe' => array('html')
))
);
}
/**
* Build a link with anchor
*
* #param string $path
* #param string $title
* #param array $options Available options:
* string 'confirm' - Text for the popup
* string 'method' - HTTP Method: post, delete, put
* string 'csrfIntention' - CSRF intention. If empty then no CSRF. Not used for GET requests
* string 'csrfField' - CSRF field name. _token by default
* bool 'escape' - escape title, TRUE by default
*/
public function linkToFunction($path,$title,array $options = array())
{
$default = array(
'csrf_intention' => '',
'csrf_field' => '_token',
'escape' => TRUE
);
$options = array_merge($default,$options);
$ecape = $options['escape'];
unset($options['escape']);
$return = '<a href="%s"%s>%s</a>';
$return = sprintf($return,
htmlspecialchars($path),
$this->_tagOptions($this->_options2javascript($options)),
($ecape)?htmlspecialchars($title):$title
);
return $return;
}
function _options2javascript($options)
{
// confirm
$confirm = isset($options['confirm']) ? $options['confirm'] : '';
unset($options['confirm']);
// method
$method = isset($options['method']) ? $options['method'] : false;
unset($options['method']);
// CSRF Intention
$csrfIntention = isset($options['csrf_intention']) ? $options['csrf_intention'] : false;
unset($options['csrf_intention']);
// CSRF field name
$csrfField = isset($options['csrf_field']) ? $options['csrf_field'] : false;
unset($options['csrf_field']);
$onclick = isset($options['onclick']) ? $options['onclick'] : '';
if ($confirm && $method)
{
$options['onclick'] = $onclick . 'if (' . $this->_confirmJsFunction($confirm) . ') { ' . $this->_methodJsFunction($method,$csrfIntention,$csrfField) . ' };return false;';
} else
if ($confirm)
{
if ($onclick)
{
$options['onclick'] = 'if (' . $this->_confirmJsFunction($confirm) . ') { return ' . $onclick . '} else return false;';
} else
{
$options['onclick'] = 'return ' . $this->_confirmJsFunction($confirm) . ';';
}
} else
if ($method)
{
$options['onclick'] = $onclick . $this->_methodJsFunction($method,$csrfIntention,$csrfField) . 'return false;';
}
return $options;
}
function _confirmJsFunction($confirm)
{
return "confirm('".$this->_escapeJs($confirm)."')";
}
/**
* Escape carrier returns and single and double quotes for Javascript segments.
*/
function _escapeJs($javascript = '')
{
$javascript = preg_replace('/\r\n|\n|\r/', "\\n", $javascript);
$javascript = preg_replace('/(["\'])/', '\\\\\1', $javascript);
return $javascript;
}
function _methodJsFunction($method,$csrfIntention,$csrfField)
{
$function = "var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'post'; f.action = this.href;";
//put, delete HTTP methods
if ('post' != strtolower($method))
{
$function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
$function .= sprintf("m.setAttribute('name', '_method'); m.setAttribute('value', '%s'); f.appendChild(m);", strtolower($method));
}
// CSRF protection
if ($csrfIntention)
{
/**
* #todo isCsrfEnabled() - check a global config
*/
if (TRUE)
{
$function .= "var m = document.createElement('input'); m.setAttribute('type', 'hidden'); ";
$function .= sprintf("m.setAttribute('name', '%s'); m.setAttribute('value', '%s'); f.appendChild(m);", $csrfField, $this->csrfProvider->generateCsrfToken($csrfIntention));
}
}
$function .= "f.submit();";
return $function;
}
function _tagOptions(array $options = array())
{
$html = '';
foreach ($options as $key => $value)
{
$html .= ' ' . $key . '="' . htmlspecialchars($value) . '"';
}
return $html;
}
public function getName()
{
return 'umbrellaweb_link';
}
}
services.xml
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="umbrellaweb.twig.link_extension" class="UmbrellaWeb\Bundle\ExtraTwigBundle\Twig\LinkExtension">
<tag name="twig.extension" />
<argument type="service" id="form.csrf_provider" />
</service>
</services>
</container>
Now in twig you can use:
{{ link_to(path('jk_aa_admin_delete',{'id' : admin.id}),'<img src="del_icon.png"/>',
{'escape':false,'method':'delete','csrf_intention':'delete-admin',
'confirm':'Are you sure?'}) }}
I controller:
//check CSRF token
if (FALSE === $this->get('form.csrf_provider')->isCsrfTokenValid('delete-admin', $request->get('_token')))
{
throw new AccessDeniedHttpException('Invalid CSRF token.');
}
Solution from Symfony 4, from documentation here http://symfony.com/doc/current/security/csrf.html:
Twig template:
<a href="{{ path("remove", { "id" : 1, "csrf_token" : csrf_token('remove') }) }}">
{{ "remove" | trans }}
</a>
Controller:
/**
* #Route("/remove/{id}", name="dashboard_alert_remove")
*
* #ParamConverter("alert", class="App:Alert")
*
* #param Alert $alert
*/
public function doRemoveAction(Alert $alert, Request $request)
{
$submittedToken = $request->get('csrf_token');
if ($this->isCsrfTokenValid('remove', $submittedToken))
{
// Do the deletion stuff
}
}
I had same problem. First I generated token in the Controller and passed to a twig file
$intentions = 'unknown';
$csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken($intentions);
return array('csrfToken'=>$csrfToken);
than from the twig file you can access the token as
var token = '{{csrfToken}}'

Categories