I am using a php module in my joomla site called: Ari Sexy Lightbox Lite. I was running on php 5.3 and had to go to 5.6.
However... Since this php upgrade i am getting two errors in my page.
Deprecated: Non-static method AriJSONHelper::encode() should not be called statically, assuming $this from incompatible context in /home/deb25878n3/domains/hang-on-run.nl/public_html/plugins/content/arisexylightboxlite/arisexylightboxlite.php on line 93
Deprecated: Non-static method AriJSONHelper::_getJSONHandler() should not be called statically, assuming $this from incompatible context in /home/deb25878n3/domains/hang-on-run.nl/public_html/plugins/content/arisexylightboxlite/arisexylightboxlite/kernel/Web/JSON/class.JSONHelper.php on line 21
I tried to fix this myself but my php knowledge is way to rusty...
I really hope that someone can help solve this.
This is the code itself:
<?php
/*
* ARI Sexy Lightbox Lite Joomla! 1.5 plugin
*
* #package ARI Sexy Lightbox Lite
* #version 1.0.0
* #author ARI Soft
* #copyright Copyright (c) 2009 www.ari-soft.com. All rights reserved
* #license GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
*
*/
defined('_JEXEC') or die('Restricted access');
jimport('joomla.plugin.plugin');
jimport('joomla.filter.filterinput');
require_once dirname(__FILE__) . '/arisexylightboxlite/kernel/class.AriKernel.php';
AriKernel::import('Web.JSON.JSONHelper');
class plgContentArisexylightboxlite extends JPlugin
{
/*
* Constructor
*/
function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
}
function onContentPrepare($context, &$article, &$params)
{
$this->prepareContent($article, 'arisexylightboxlite');
}
function onPrepareContent(&$article, &$params, $limitstart)
{
$this->prepareContent($article);
}
function prepareContent($article, $folder = '')
{
static $loaded;
if ($loaded)
return ;
$mainframe = JFactory::getApplication();
$plgParams = $this->params;
$rel = $plgParams->get('opt_find', 'sexylightbox');
$loadAssets = $plgParams->get('loadAssets', 'auto');
if ($loadAssets == 'auto' && (empty($article->text) || !preg_match('/<[^>]*rel=("|\')?' . $rel . '(\[|"|\'| |\/)/i', $article->text)))
return ;
$document = JFactory::getDocument();
$baseUri = JURI::root(true) . '/plugins/content/' . ($folder ? $folder . '/' : '') . 'arisexylightboxlite/js/';
$loadJQuery = (bool)$plgParams->get('includeJQuery', false);
$noConflict = (bool)$plgParams->get('noConflict', true);
if ($loadJQuery)
{
$loadJQueryMethod = $plgParams->get('loadJQueryMethod', 'google_cdn');
if ($loadJQueryMethod == 'local')
{
if (J3_0)
JHtml::_('jquery.framework', $noConflict);
else
$document->addScript($baseUri . 'jquery.min.js');
}
else
{
$document->addScript('//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js');
}
if ($noConflict)
{
if (!J3_0 || $loadJQueryMethod != 'local')
$document->addScript($baseUri . 'jquery.noconflict.js');
}
}
$document->addScript($baseUri . 'jquery.easing.js');
$document->addScript($baseUri . 'jquery.sexylightbox.min.js');
$document->addStyleSheet($baseUri . 'sexylightbox.css');
$jsOptions = $this->getOptions($folder);
$document->addScriptDeclaration(
sprintf('jQuery(document).ready(function(){ SexyLightbox.initialize(%s); });',
$jsOptions ? AriJSONHelper::encode($jsOptions) : ''));
$loaded = true;
}
function getOptions($folder = '')
{
$defOptions = array(
'find' => 'sexylightbox',
'zIndex' => 32000,
'color' => 'black',
'emergefrom' => 'top',
'showDuration' => 200,
'closeDuration' => 400,
'moveDuration' => 1000,
'moveEffect' => 'easeInOutBack',
'resizeDuration' => 1000,
'resizeEffect' => 'easeInOutBack',
'shake' => array(
'distance' => 10,
'duration' => 100,
'loops' => 2,
'transition' => 'easeInOutBack'
)
);
$options = $this->getParamOptions($defOptions);
$options['dir'] = str_replace(' ', '%20', JURI::root(true) . '/plugins/content/' . ($folder ? $folder . '/' : '') . 'arisexylightboxlite/js/sexyimages');
return $options;
}
function getParamOptions($defOptions, $prefix = 'opt_')
{
$plgParams = $this->params;
$options = array();
$filter = JFilterInput::getInstance();
foreach ($defOptions as $key => $value)
{
if (is_array($value))
{
$subOptions = $this->getParamOptions($value, $prefix . $key . '_');
if (count($subOptions) > 0)
$options[$key] = $subOptions;
}
else
{
$paramValue = $plgParams->get($prefix . $key, $value);
if ($paramValue !== $value)
{
$paramValue = $filter->clean($paramValue, gettype($value));
if ($paramValue !== $value)
$options[$key] = $paramValue;
}
}
}
return $options;
}
}
Related
I have a Joomla Module it will produce an error code with php 8.0.1 on wampserver on helper.php line 121 "Error Code: Non-static method modSidePanelHelper::getModuleById() cannot be called statically". This is helper.php
<?php
// no direct access
defined('_JEXEC') or die;
require_once JPATH_SITE . '/components/com_content/helpers/route.php';
if (!class_exists('LofPanelGroupBase')) {
require_once(dirname(__FILE__) . '/libs/group_base.php');
}
abstract class modSidePanelHelper {
/**
* get list articles
*/
public static function getList($params) {
if ($params->get('enable_cache')) {
$cache = JFactory::getCache('mod_sidepanel_jt1');
$cache->setCaching(true);
$cache->setLifeTime($params->get('cache_time', 15) * 60);
return $cache->get(array('modSidePanelHelper', 'getGroupObject'), array($params));
} else {
return self::getGroupObject($params);
}
}
/**
* get list articles
*/
public static function getGroupObject($params) {
$group = $params->get('group', 'file');
$file = dirname(__FILE__) .'/libs/groups/'. strtolower($group) . '/' . strtolower($group) . '.php';
if (file_exists($file)) {
require_once($file);
$className = 'SidePanelGroup' . ucfirst($group);
if (class_exists($className)) {
$object = new $className($group);
$object->setCurrentPath(dirname(__FILE__) .'/libs/groups/'. strtolower($group) . '/');
}
}
if ($object) {
return $object->getListByParameters($params);
} else {
return array();
}
}
/**
* load css - javascript file.
*
* #param JParameter $params;
* #param JModule $module
* #return void.
*/
public static function loadMediaFiles($params, $module, $theme='') {
$mainframe = JFactory::getApplication();
// if the verion is equal 1.6.x
JHTML::script('modules/' . $module->module . '/assets/script.js');
if ($theme && $theme != -1) {
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/'. $module->module . '/' . $theme .'/assets/style.css';
if (file_exists($tPath)) {
JHTML::stylesheet('templates/' . $mainframe->getTemplate() . '/html/' . $module->module . '/' . $theme . '/assets/style.css');
} else {
JHTML::stylesheet('modules/' . $module->module . '/tmpl/' . $theme . '/assets/style.css');
}
} else {
JHTML::stylesheet('modules/' . $module->module . '/assets/style.css');
}
}
/**
*
*/
public function renderItem(&$row, $params, $layout='_item') {
$mainframe = JFactory::getApplication();
$theme = $params->get('theme');
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/mod_sidepanel_jt1/'. $theme . '/' . $layout . '.php';
$bPath = JPATH_BASE .'/modules/mod_sidepanel_jt1/tmpl/'. $theme . '/' . $layout . '.php';
if (file_exists($tPath)) {
require($tPath);
} elseif (file_exists($bPath)) {
require($bPath);
}
}
/**
* load theme
*/
public static function getLayoutByTheme($module, $group, $theme= '') {
$mainframe = JFactory::getApplication();
// Build the template and base path for the layout
$tPath = JPATH_BASE .'/templates/'. $mainframe->getTemplate() .'/html/'. $module->module . '/' . $theme .'/default.php';
$bPath = JPATH_BASE .'/modules/'. $module->module .'/tmpl/'. $theme .'/default.php';
// If the template has a layout override use it
if (file_exists($tPath)) {
return $tPath;
} elseif (file_exists($bPath)) {
return $bPath;
}
}
public static function getModulesEnable($params) {
$enableModules = array();
for ($i = 0; $i <= 6; $i++) {
$module = $params->get('file' . $i);
if($module){
if (intval($module->enable) == 1) {
$enableModules[] = self::getModuleById($module->image);
}
}
}
return $enableModules;
}
private function getModuleById($id) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('module, title');
$query->from('#__modules');
$query->where('published=1 AND client_id=0 AND id=' . $db->quote($id));
$db->setQuery($query);
return $db->loadObject();
}
static function getReturnURL($params, $type) {
$app = JFactory::getApplication();
$router = $app->getRouter();
$url = null;
if ($itemid = $params->get($type)) {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('link'));
$query->from($db->quoteName('#__menu'));
$query->where($db->quoteName('published') . '=1');
$query->where($db->quoteName('id') . '=' . $db->quote($itemid));
$db->setQuery($query);
if ($link = $db->loadResult()) {
if ($router->getMode() == JROUTER_MODE_SEF) {
$url = 'index.php?Itemid=' . $itemid;
} else {
$url = $link . '&Itemid=' . $itemid;
}
}
}
if (!$url) {
// stay on the same page
$uri = clone JFactory::getURI();
$vars = $router->parse($uri);
unset($vars['lang']);
if ($router->getMode() == JROUTER_MODE_SEF) {
if (isset($vars['Itemid'])) {
$itemid = $vars['Itemid'];
$menu = $app->getMenu();
$item = $menu->getItem($itemid);
unset($vars['Itemid']);
if (isset($item) && $vars == $item->query) {
$url = 'index.php?Itemid=' . $itemid;
} else {
$url = 'index.php?' . JURI::buildQuery($vars) . '&Itemid=' . $itemid;
}
} else {
$url = 'index.php?' . JURI::buildQuery($vars);
}
} else {
$url = 'index.php?' . JURI::buildQuery($vars);
}
}
return base64_encode($url);
}
}
line 121 is like this: $enableModules[] = self::getModuleById($module->image);
the self::getModuleById seems deprecated on php 8. Changing that line like this
$enableModules[] = (new modSidePanelHelper)->getModuleById($module->image);
causes another error code like this
Error Code: Cannot instantiate abstract class modSidePanelHelper
any suggestion? Thanks in advance
You have an abstract class:
abstract class modSidePanelHelper {
public static function getList($params) {
// ...
}
public static function getGroupObject($params) {
// ...
}
public static function loadMediaFiles($params, $module, $theme='') {
// ...
}
public function renderItem(&$row, $params, $layout='_item') {
// ...
}
public static function getLayoutByTheme($module, $group, $theme= '') {
// ...
}
public static function getModulesEnable($params) {
// ...
}
private function getModuleById($id) {
// ...
}
static function getReturnURL($params, $type) {
// ...
}
}
The only non-static function is getModuleById, which cannot be called from a static context of this class directly. You either have to create a new concrete class and call its instance then or make this function static.
In this case, I understand that making this class abstract is for preventing calling the constructor of this class, and this functionality is clearly only for static methods execution.
Then, replace:
private function getModuleById($id) {
// ...
}
with:
private static function getModuleById($id) {
// ...
}
I think you also have to do the same for the renderItem function, as long as it's not used here, it has to be executed in a static context if you need to execute it from some other place.
I'm using Parsedown to parse HTML from the database to my site. With Parsedown, you can't really add target="_blank" to the links.
So what I'm trying to do is to add target="_blank" to external links. I've found this function in Parsedown.php:
protected function inlineLink($Excerpt)
{
$Element = array(
'name' => 'a',
'handler' => 'line',
'text' => null,
'attributes' => array(
'href' => null,
'title' => null,
),
);
$extent = 0;
$remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches))
{
$Element['text'] = $matches[1];
$extent += strlen($matches[0]);
$remainder = substr($remainder, $extent);
}
else
{
return;
}
if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches))
{
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2]))
{
$Element['attributes']['title'] = substr($matches[2], 1, - 1);
}
$extent += strlen($matches[0]);
}
else
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
{
$definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
$definition = strtolower($definition);
$extent += strlen($matches[0]);
}
else
{
$definition = strtolower($Element['text']);
}
if ( ! isset($this->DefinitionData['Reference'][$definition]))
{
return;
}
$Definition = $this->DefinitionData['Reference'][$definition];
$Element['attributes']['href'] = $Definition['url'];
$Element['attributes']['title'] = $Definition['title'];
}
$Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']);
return array(
'extent' => $extent,
'element' => $Element,
);
}
Now, what I've tried is this (added a comment of what I changed):
protected function inlineLink($Excerpt)
{
$Element = array(
'name' => 'a',
'handler' => 'line',
'text' => null,
'attributes' => array(
'href' => null,
'target' => null, // added this
'title' => null,
),
);
$extent = 0;
$remainder = $Excerpt['text'];
if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches))
{
$Element['text'] = $matches[1];
$extent += strlen($matches[0]);
$remainder = substr($remainder, $extent);
}
else
{
return;
}
if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches))
{
$Element['attributes']['href'] = $matches[1];
if (isset($matches[2]))
{
$Element['attributes']['title'] = substr($matches[2], 1, - 1);
}
$extent += strlen($matches[0]);
}
else
{
if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
{
$definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
$definition = strtolower($definition);
$extent += strlen($matches[0]);
}
else
{
$definition = strtolower($Element['text']);
}
if ( ! isset($this->DefinitionData['Reference'][$definition]))
{
return;
}
$Definition = $this->DefinitionData['Reference'][$definition];
$Element['attributes']['href'] = $Definition['url'];
if (strpos($Definition['url'], 'example.com') !== false) { // added this aswell, checking if its our own URL
$Element['attributes']['target'] = '_blank';
}
$Element['attributes']['title'] = $Definition['title'];
}
$Element['attributes']['href'] = str_replace(array('&', '<'), array('&', '<'), $Element['attributes']['href']);
return array(
'extent' => $extent,
'element' => $Element,
);
}
Any suggestions to accomplish this?
Ran into this issue today. I wanted to have all links from a different host open up in a new target automatically. Unfortunately, the accepted answer recommends editing the Parsedown class file, which is a bad idea imo.
I created a new PHP class which extends Parsedown, and created an override for the element method. Here is the whole class:
class ParsedownExtended extends Parsedown
{
protected function element(array $Element)
{
if ($this->safeMode) {
$Element = $this->sanitiseElement($Element);
}
$markup = '<' . $Element['name'];
if (isset($Element['name']) && $Element['name'] == 'a') {
$server_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
$href_host = isset($Element['attributes']['href']) ? parse_url($Element['attributes']['href'], PHP_URL_HOST) : null;
if ($server_host != $href_host) {
$Element['attributes']['target'] = '_blank';
}
}
if (isset($Element['attributes'])) {
foreach ($Element['attributes'] as $name => $value) {
if ($value === null) {
continue;
}
$markup .= ' ' . $name . '="' . self::escape($value) . '"';
}
}
if (isset($Element['text'])) {
$markup .= '>';
if (!isset($Element['nonNestables'])) {
$Element['nonNestables'] = array();
}
if (isset($Element['handler'])) {
$markup .= $this->{$Element['handler']}($Element['text'], $Element['nonNestables']);
}
else {
$markup .= self::escape($Element['text'], true);
}
$markup .= '</' . $Element['name'] . '>';
}
else {
$markup .= ' />';
}
return $markup;
}
}
Here is where the magic happens:
if (isset($Element['name']) && $Element['name'] == 'a') {
$server_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
$href_host = isset($Element['attributes']['href']) ? parse_url($Element['attributes']['href'], PHP_URL_HOST) : null;
if ($server_host != $href_host) {
$Element['attributes']['target'] = '_blank';
}
}
Now I simply use ParsedownExtended instead of Parsedown when parsing content, e.g.:
$parsedown = new ParsedownExtended();
return $parsedown->text($this->body);
Hope this helps someone.
Such issue already exists on GitHub. Please see this comment.
My extension can automatically set rel="nofollow" and target="_blank"
attributes to a link when it is detected as an external link. You can
also set those attributes manually through the attribute block:
[text](http://example.com) {rel="nofollow" target="_blank"}
Automatic rel="nofollow" Attribute on External Links
// custom external link attributes
$parser->links_external_attr = array(
'rel' => 'nofollow',
'target' => '_blank'
);
If you want to make changes in Parsedown class without using the parsedown-extra-plugin extension, you can do as follows:
1) In \Parsedown::element method after the first line $markup = '<'.$Element['name']; add this line $Element = $this->additionalProcessElement($Element);
2) Add new method to Parsedown class:
protected function additionalProcessElement($Element) { }
3) Extend Parsedown class and save it as MyParsedown.php file:
<?php
namespace myapps;
require_once __DIR__.'/Parsedown.php';
/**
* Class MyParsedown
* #package app
*/
class MyParsedown extends \Parsedown
{
/**
* #param array $Element
* #return array
*/
protected function additionalProcessElement($Element)
{
if ($Element['name'] == 'a' && $this->isExternalUrl($Element['attributes']['href'])) {
$Element['attributes']['target'] = '_blank';
}
return $Element;
}
/**
* Modification of the funciton from answer to the question "How To Check Whether A URL Is External URL or Internal URL With PHP?"
* #param string $url
* #param null $internalHostName
* #see https://stackoverflow.com/a/22964930/7663972
* #return bool
*/
protected function isExternalUrl($url, $internalHostName = null) {
$components = parse_url($url);
$internalHostName = ($internalHostName == null) ? $_SERVER['HTTP_HOST'] : $internalHostName;
// we will treat url like '/relative.php' as relative
if (empty($components['host'])) {
return false;
}
// url host looks exactly like the local host
if (strcasecmp($components['host'], $internalHostName) === 0) {
return false;
}
$isNotSubdomain = strrpos(strtolower($components['host']), '.'.$internalHostName) !== strlen($components['host']) - strlen('.'.$internalHostName);
return $isNotSubdomain;
}
}
4) Create test.php file and run it:
require_once __DIR__.'/MyParsedown.php';
$parsedown = new \myapps\MyParsedown();
$text = 'External link to [example.com](http://example.com/abc)';
echo $parsedown->text($text);
This HTML code will be displayed on the browser page (if your host is not example.com, of course):
<p>External link to example.com</p>
Just like kjdion84 I'd also extend the Parsedown class. I suggest to not copy and change the element method but overwrite inlineLink; it's less work and more future proof if the base code changes.
Heads up: the urlIsExternal method is by no means complete (host check is missing).
class ParsedownExtended extends Parsedown
{
protected function inlineLink($Excerpt)
{
$link = parent::inlineLink($Excerpt);
if ($this->urlIsExternal($link['element']['attributes']['href'])) {
$link['element']['attributes'] += [
'target' => '_blank',
'rel' => 'nofollow',
];
}
return $link;
}
protected function urlIsExternal($url)
{
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
if (!$scheme || !$host) {
return false;
}
if (strpos(strtolower($scheme), 'http') !== 0) {
return false;
}
// #TODO check the host
return true;
}
}
This will work.
<?php
declare(strict_types=1);
namespace YourNamespace;
class ParsedownExt extends \Parsedown
{
// Add target to links
protected function element(array $Element)
{
if (strcasecmp($Element['name'], 'a')===0)
$Element['attributes']['target'] = '_blank';
return parent::element($Element);
}
}
I am using codeigniter. I need to get all variables from a language file to an array.Is it possible?
Is there any method available like as follows?
$a = $this->load->language('editor');
print_r($a);
I was tried $this->lang->language; But,This will return labels from another language files loaded.
$CI = & get_instance();
$arr = $CI->lang->language;
Or Use following library
Class My_language {
var $language = array();
/**
* List of loaded language files
*
* #var array
*/
var $is_loaded = array();
function __construct() {
log_message('debug', "Language Class Initialized");
}
function load($langfile = '', $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') {
$langfile = str_replace('.php', '', $langfile);
if ($add_suffix == TRUE) {
$langfile = str_replace('_lang.', '', $langfile) . '_lang';
}
$langfile .= '.php';
if (in_array($langfile, $this->is_loaded, TRUE)) {
return;
}
$config = & get_config();
if ($idiom == '') {
$deft_lang = (!isset($config['language'])) ? 'english' : $config['language'];
$idiom = ($deft_lang == '') ? 'english' : $deft_lang;
}
// Determine where the language file is and load it
if ($alt_path != '' && file_exists($alt_path . 'language/' . $idiom . '/' . $langfile)) {
include($alt_path . 'language/' . $idiom . '/' . $langfile);
} else {
$found = FALSE;
foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) {
if (file_exists($package_path . 'language/' . $idiom . '/' . $langfile)) {
include($package_path . 'language/' . $idiom . '/' . $langfile);
$found = TRUE;
break;
}
}
if ($found !== TRUE) {
show_error('Unable to load the requested language file: language/' . $idiom . '/' . $langfile);
}
}
if (!isset($lang)) {
log_message('error', 'Language file contains no data: language/' . $idiom . '/' . $langfile);
return;
}
if ($return == TRUE) {
return $lang;
}
$this->is_loaded[] = $langfile;
$this->language = array();
$this->language = $lang;
return $this->language;
unset($lang);
log_message('debug', 'Language file loaded: language/' . $idiom . '/' . $langfile);
return TRUE;
}
}
Call like this
$this->load->library('my_language');
$arr = $this->my_language->load('demo');
print_r($arr);
I know this is quite an old question, but I just want to give my solution for this problem since no answers has done the trick for this problem. (tested on codeigniter 3)
$this->load->helper('language');
$foo = $this->lang->load('lang_file', 'english', true);
print_r($foo);
notice that the third parameter for load method determines whether to return the loaded array of translations. source: codeigniter 3 docs.
hope this helps
Yeah ofcourse its possible. You can do like this :
//load helper for language
$this->load->helper('language');
//test is the language file in english folder
$this->lang->load('test','english');
//fetch all the data in $var variable
$var=$this->lang->language;
//print $var
print_r($var);
$var will return the array. :)
If you want to return language file data in Array than you need to pass the third parameter in load function.
$this->lang->load('header','hindi',true) // filename,language,true
This is one of my controller:
class MediaController extends BaseController {
private $js_files = array(), $css_files = array();
/** Media specific function **/
static function base_uri(){
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
);
}
function AddJquery($version = null) {
if($version === null) $version = 'custom';
$js_files[] = '<script src="assets/js/jquery/jquery.' . $version . '.js"></script>';
}
function AddJS($name, $minified = true) {
$js_base_uri = base_uri() . "assets/js/";
$js_files[] = $js_base_uri . ($minified ? '/min/' : '') . $name . ($minified ? '.min' : '') . '.js';
}
/** Page specific function **/
public function index_page() {
if(!empty($js_files)) $js_files = array();
if(!empty($css_files)) $css_files = array();
AddJquery();
AddJS('mainscript');
$data = array(
'js_files' => $js_files
);
return View::make('homepage', $data);
}
}
?>
When I access my main page with Route::get('/', 'MediaController#index_page');
in routes.php, in the index_page() it cannot access AddJquery() method.
Anyone can tell me why? Thanks.
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.