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);
}
}
Related
I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.
I am creating a new moodle theme which the css needs to be customizable. By "customizable", i mean that from the admin page you can edit for exemple, the color of your background.
I followed the tutorial from https://docs.moodle.org/dev/Themes, which is great but should be, from my opinion, about the same parent theme for each parts of it.
My page is displaying well at the exception of my admin drop down menu (so i can't see my theme editing page). Everything was fine before i tried to setup my own settings just as the tutorial.
I assume that i probably made a mistake by adaptating my theme from the tutorial but i'm completly lost right now.
We are here in the 'theme/mytheme' directory.
File 'settings.php' :
<?php
defined('MOODLE_INTERNAL') || die();
$name = 'theme_mytheme/backcolor';
$title = get_string('backcolor', 'theme_mytheme');
$desc = get_string('backcolor_desc', 'theme_mytheme');
$setting = new admin_setting_configcolourpicker($name, $title, $desc, '#ffffff');
$setting->set_updatedcallback('theme_reset_all_caches');
$page->add($setting);
?>
File 'lib.php':
<?php
defined('MOODLE_INTERNAL') || die;
function theme_mytheme_process_css($css, $theme) {
// Set custom CSS.
if (!empty($theme->settings->customcss)) {
$customcss = $theme->settings->customcss;
} else {
$customcss = null;
}
$css = theme_mytheme_set_customcss($css, $customcss);
$defaults = array(
'[[setting:backcolor]]' => '#FFFFFF',
);
foreach ($theme->settings as $key => $val) {
if (array_key_exists('[[setting:'.$key.']]', $defaults) && !empty($val)) {
$defaults['[[setting:'.$key.']]'] = $val;
}
}
$homebkg = '';
if (!empty($theme->settings->homebk)) {
$homebkg = $theme->setting_file_url('homebk', 'homebk');
$homebkg = 'background-image: url("' . $homebkg . '");';
}
$defaults['[[setting:homebkg]]'] = $homebkg;
// Replace the CSS with values from the $defaults array.
$css = strtr($css, $defaults);
if (empty($theme->settings->tilesshowallcontacts) || $theme->settings->tilesshowallcontacts == false) {
$css = theme_mytheme_set_tilesshowallcontacts($css, false);
} else {
$css = theme_mytheme_set_tilesshowallcontacts($css, true);
}
return $css;
}
function theme_mytheme_set_customcss($css, $customcss) {
$tag = '[[setting:customcss]]';
$replacement = $customcss;
if (is_null($replacement)) {
$replacement = '';
}
$css = str_replace($tag, $replacement, $css);
return $css;
}
function theme_mytheme_set_tilesshowallcontacts($css, $display) {
$tag = '[[setting:tilesshowallcontacts]]';
if ($display) {
$replacement = 'block';
} else {
$replacement = 'none';
}
$css = str_replace($tag, $replacement, $css);
return $css;
}
function theme_mytheme_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel == CONTEXT_SYSTEM &&
($filearea === 'logo' || $filearea === 'smalllogo' || $filearea === 'backgroundimage')) {
$theme = theme_config::load('mytheme');
// By default, theme files must be cache-able by both browsers and proxies.
if (!array_key_exists('cacheability', $options)) {
$options['cacheability'] = 'public';
}
return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
} else {
send_file_not_found();
}
}
?>
File 'config.php' :
<?php
defined('MOODLE_INTERNAL') || die();
$THEME->name = 'mytheme';
$THEME->sheets = array('styles');
$THEME->editor_sheets = array();
$THEME->parents = array('base');
$THEME->yuicssmodules = array();
$THEME->scss = function($theme) {
return theme_mytheme_get_pre_scss($theme);
};
$THEME->layouts = array(
// Most backwards compatible layout without the blocks - this is the layout used by default
'base' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array(),
),
'standard' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array('side-pre', 'side-post'),
'defaultregion' => 'side-pre',
),
'frontpage' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array('side-pre', 'side-post'),
'defaultregion' => 'side-post'
)
);
$THEME->csspostprocess = 'theme_mytheme_process_css';
?>
I feel sorry for passing my complete files but it can't be pertinent if i don't...
I am trying to create an API using CakePHP that allows searching. For example:
http://localhost:8765/users/index/?username=admin
Which should return users with usernames equal to 'admin':
users: [
{
id: 3,
username: "admin",
image: "",
firstName: "Jeremy",
lastName: "Quick",
userTypeId: 1,
email: "jrquick#test.com",
groupId: 2
}
]
So far, I have been able to accomplish this with a custom get() in the AppController which checks the $_GET and $_POST array for fields on the model. But the function is getting more and more complicated and verging on hackiness as I add more functionality (range search, collection search, and child table filtering). Is there a better, more CakePHP friendly way of accomplishing this? Whether through pure cakephp or a plugin?
I think you want to use the Cakephp Search plugin. It has good documentation and uses a PRG method similar to what you are currently using. It will function just fine through an API. Here's a link to that plugin: github.com/FriendsOfCake/search
If You want to create API, You should create a MiddleWare at first, which will filter tokens, keys etc. to make Your API more protected.
Also, You should use Plugins and RESTful Routes, which will be very helpful.
To create plugin:
bin/cake bake plugin Api
Create Model:
bin/cake bake model Users
For example, You want to have UsersController in Api plugin:
<?php
namespace Api\Controller;
/* This controller will be extending like parent */
use Api\Controller\AppController;
use Api\Model\Table\UsersTable;
/**
* Class UsersController
* #package Api\Controller
* #property UsersTable $Users
*
*/
class UsersController extends AppController{
public function initialize(){
parent::initialize();
$this->loadModel('Api.Users');
}
public function getUser($field ='username', $username = false){
return $this->_jsonResponse(
[
'users' => $this->Users->findBy{ucfirst($field)}($username)
];
)
}
public function _jsonResponse($data, $code = 200){
$this->response->type('json');
$this->response->statusCode($code);
$this->response->body(
json_encode((array)$data)
);
return $this->response;
}
}
Route will be descripbed in plugins/config/routes.php. You need to create Route Map for API in /api path:
function (RouteBuilder $routes) {
$routes->resources('Users', [
'map' => [
'get-user' => [
'action' => 'getUser',
'method' => 'GET' /* Can be also as array ['GET', 'PUT', 'DELETE'] */
]
]
]);
$routes->fallbacks('DashedRoute');
}
If You have frequent calls, You should use Cache that calls and save them for some amount of time. For example - 10 minutes. Cache can be configured in config/app.php. You should create separate Cache prefix and use it in this way:
<?php
use Cake\Cache\Cache;
$data = [];
Cache::write('some_key', $data, 'prefix')
dump(Cache::read('some_key', 'prefix'));
It's just examples. If You will face some problems - just tell in comments :)
Also, use Migrations and Seeds instead dumping sql files
If You want to filter data from Middleware - You should have Event as argument, that will contain request data ($_POST) and request query($_GET) variables that You will be able to easily handle with.
From controllers You need to use $this->request->data to get POST data array or $this->request->query to get GET data array.
I haven't found an answer that seems to work exactly how I am wanting, so here is my current get command. It does allow searching by fields, join tables, greater/less than, in array, and like.
If anyone has recommendations to improve I will update my answer.
public function get() {
$response = new Response();
$model = $this->loadModel();
$fields = $this->getFields();
$joins = $this->getJoins();
$order = $this->getOrder();
$params = $this->getParams();
$limit = $this->getLimit();
$offset = $this->getOffset();
$query = $model->find('all', ['fields' => $fields]);
if (!is_null($joins)) {
$query->contain($joins);
}
if (sizeof($params['equals']) > 0) {
foreach ($params['equals'] as $equalsKey=>$equalsValue) {
$query->andWhere([$equalsKey => $equalsValue]);
}
}
if (sizeof($params['or']) > 0) {
foreach ($params['or'] as $orKey=>$orValue) {
$query->orWhere([$orKey => $orValue]);
}
}
if (!is_null($order)) {
$query->order([$order]);
}
if (!is_null($limit)) {
$query->limit($limit);
if (!is_null($offset)) {
$query->offset($offset);
}
}
$response->addMessage($model->table(), $query->toArray());
$response->respond($this);
}
private function getFields() {
$fields = [];
if (array_key_exists('fields', $_GET)) {
$fields = explode(',', $_GET['fields']);
}
return $fields;
}
private function getLimit() {
$limit = null;
if (array_key_exists('limit', $_GET)) {
$limit = $_GET['limit'];
}
return $limit;
}
private function getJoins() {
$joins = null;
if (array_key_exists('joins', $_GET)) {
$joins = explode(',', $_GET['joins']);
}
return $joins;
}
private function getOffset() {
$offset = null;
if (array_key_exists('offset', $_GET)) {
$offset = $_GET['limit'];
}
return $offset;
}
private function getOrder() {
$results = [];
if (array_key_exists('order', $_GET)) {
$orders = explode(',', $_GET['order']);
foreach ($orders as $order) {
$sign = substr($order, 0, 1);
$direction = 'ASC';
if (in_array($sign, ['+', '-'])) {
if ($sign === '-') {
$direction = 'DESC';
}
$order = substr($order, 1);
}
$result = $order;
if (strpos($result, '.') === false) {
$result = $this->loadModel()->alias() . '.' . $order;
}
$result = $result . ' ' . $direction;
$results[] = $result;
}
}
return (sizeof($results) == 0) ? null : implode(',', $results);
}
private function getParams() {
$params = [
'equals' => [],
'or' => []
];
$parentModel = $this->loadModel();
$array = array_merge($_GET, $_POST);
foreach ($array as $field=>$value) {
$comparisonType = 'equals';
$operator = substr($field, strlen($field) - 1);
if (in_array($operator, ['!', '>', '<'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator .= '=';
} else if (in_array($operator, ['|'])) {
$field = substr($field, 0, strlen($field) - 1);
$comparisonType = 'or';
$operator = '=';
} else if (in_array($operator, ['%'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator = 'LIKE';
$value = '%'.$value.'%';
} else {
$operator = '=';
}
if ($value == 'null') {
$operator = (strpos($operator, '!') === false) ? 'IS' : 'IS NOT';
$value = null;
}
$field = str_replace('_', '.', $field);
if (strpos($field, '.') === false) {
$alias = $parentModel->alias();
} else {
$fieldExplosion = explode('.', $field);
$alias = $fieldExplosion[0];
$field = $fieldExplosion[1];
}
$model = null;
if ($parentModel->alias() !== $alias) {
$association = $parentModel->associations()->get($alias);
if (!is_null($association)) {
$model = $this->loadModel($association->className());
}
} else {
$model = $parentModel;
}
if (!is_null($model)) {
if ($model->hasField(rtrim($field, 's')) && !$model->hasField($field)) {
$field = rtrim($field, 's');
$value = '(' . $value . ')';
$operator = ' IN';
}
if ($model->hasField($field)) {
$params[$comparisonType][$alias.'.'.$field . ' ' . $operator] = $value;
}
}
}
return $params;
}
I'm having trouble getting the "stock" blog functionality / template working within FUEL CMS.
I have read that it is already there, stock with the download configuration of the CMS; I have also tried creating one from scratch and uploading a 'blog' theme from a project found in GitHub. None have worked so far.
I found the blog variable at:
_variables/global.php
I have created a 'blog' controller via interpretation of (gappy) docs.
By adding the below code within it; then making a corresponding 'blog.php' view. I get nothing but a 404 error.
<?php
class Blog extends CI_Controller {
public function view($page = 'home')
{
//you can acesse this http://example.com/blog/view/
}
public function new($page = 'home')
{
//you can acesse this http://example.com/blog/new/
}
}
Within the modules folder. I found this 'stock' blog controller file. But don't know how to use it? found at: /fuel/modules/blog/controller/blog.php
<?php
require_once(MODULES_PATH.'/blog/libraries/Blog_base_controller.php');
class Blog extends Blog_base_controller {
function __construct()
{
parent::__construct();
}
function _remap()
{
$year = ($this->uri->rsegment(2) != 'index') ? (int) $this->uri->rsegment(2) : NULL;
$month = (int) $this->uri->rsegment(3);
$day = (int) $this->uri->rsegment(4);
$slug = $this->uri->rsegment(5);
$limit = (int) $this->fuel->blog->config('per_page');
$view_by = 'page';
// we empty out year variable if it is page because we won't be querying on year'
if (preg_match('#\d{4}#', $year) && !empty($year) && empty($slug))
{
$view_by = 'date';
}
// if the first segment is id then treat the second segment as the id
else if ($this->uri->rsegment(2) === 'id' && $this->uri->rsegment(3))
{
$view_by = 'slug';
$slug = (int) $this->uri->rsegment(3);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
redirect($post->url);
}
}
else if (!empty($slug))
{
$view_by = 'slug';
}
// set this to false so that we can use segments for the limit
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache))
{
$output =& $cache;
}
else
{
$vars = $this->_common_vars();
if ($view_by == 'slug')
{
return $this->post($slug);
}
else if ($view_by == 'date')
{
$page_title_arr = array();
$posts_date = mktime(0, 0, 0, $month, $day, $year);
if (!empty($day)) $page_title_arr[] = $day;
if (!empty($month)) $page_title_arr[] = date('M', strtotime($posts_date));
if (!empty($year)) $page_title_arr[] = $year;
// run before_posts_by_date hook
$hook_params = array('year' => $year, 'month' => $month, 'day' => $day, 'slug' => $slug, 'limit' => $limit);
$this->fuel->blog->run_hook('before_posts_by_date', $hook_params);
$vars = array_merge($vars, $hook_params);
$vars['page_title'] = $page_title_arr;
$vars['posts'] = $this->fuel->blog->get_posts_by_date($year, (int) $month, $day, $slug);
$vars['pagination'] = '';
}
else
{
$limit = $this->fuel->blog->config('per_page');
$this->load->library('pagination');
$config['uri_segment'] = 3;
$offset = $this->uri->segment($config['uri_segment']);
$this->config->set_item('enable_query_strings', FALSE);
$config = $this->fuel->blog->config('pagination');
$config['base_url'] = $this->fuel->blog->url('page/');
//$config['total_rows'] = $this->fuel->blog->get_posts_count();
$config['page_query_string'] = FALSE;
$config['per_page'] = $limit;
$config['num_links'] = 2;
//$this->pagination->initialize($config);
if (!empty($offset))
{
$vars['page_title'] = lang('blog_page_num_title', $offset, $offset + $limit);
}
else
{
$vars['page_title'] = '';
}
// run before_posts_by_date hook
$hook_params = array('offset' => $offset, 'limit' => $limit, 'type' => 'posts');
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
$vars['offset'] = $offset;
$vars['limit'] = $limit;
$vars['posts'] = $this->fuel->blog->get_posts_by_page($limit, $offset);
// run hook again to get the proper count
$hook_params['type'] = 'count';
$this->fuel->blog->run_hook('before_posts_by_page', $hook_params);
//$config['total_rows'] = count($this->fuel->blog->get_posts_by_page());
$config['total_rows'] = $this->fuel->blog->get_posts_count();
// create pagination
$this->pagination->initialize($config);
$vars['pagination'] = $this->pagination->create_links();
}
// show the index page if the page doesn't have any uri_segment(3)'
$view = ($this->uri->rsegment(2) == 'index' OR ($this->uri->rsegment(2) == 'page' AND !$this->uri->segment(3))) ? 'index' : 'posts';
$output = $this->_render($view, $vars, TRUE);
$this->fuel->blog->save_cache($cache_id, $output);
}
$this->output->set_output($output);
}
function post($slug = null)
{
if (empty($slug))
{
redirect_404();
}
$this->load->library('session');
$blog_config = $this->fuel->blog->config();
// run before_posts_by_date hook
$hook_params = array('slug' => $slug);
$this->fuel->blog->run_hook('before_post', $hook_params);
$post = $this->fuel->blog->get_post($slug);
if (isset($post->id))
{
$vars = $this->_common_vars();
$vars['post'] = $post;
$vars['user'] = $this->fuel->blog->logged_in_user();
$vars['page_title'] = $post->title;
$vars['next'] = $this->fuel->blog->get_next_post($post);
$vars['prev'] = $this->fuel->blog->get_prev_post($post);
$vars['slug'] = $slug;
$vars['is_home'] = $this->fuel->blog->is_home();
$antispam = md5(random_string('unique'));
$field_values = array();
// post comment
if (!empty($_POST))
{
$field_values = $_POST;
// the id of "content" is a likely ID on the front end, so we use comment_content and need to remap
$field_values['content'] = $field_values['new_comment'];
unset($field_values['antispam']);
if (!empty($_POST['new_comment']))
{
$vars['processed'] = $this->_process_comment($post);
}
else
{
add_error(lang('blog_error_blank_comment'));
}
}
$cache_id = fuel_cache_id();
$cache = $this->fuel->blog->get_cache($cache_id);
if (!empty($cache) AND empty($_POST))
{
$output =& $cache;
}
else
{
$this->load->library('form');
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
$captcha = $this->_render_captcha();
$vars['captcha'] = $captcha;
}
$vars['thanks'] = ($this->session->flashdata('thanks')) ? blog_block('comment_thanks', $vars, TRUE) : '';
$vars['comment_form'] = '';
$this->session->set_userdata('antispam', $antispam);
if ($post->allow_comments)
{
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$this->load->library('form_builder', $blog_config['comment_form']);
$fields['author_name'] = array('label' => 'Name', 'required' => TRUE);
$fields['author_email'] = array('label' => 'Email', 'required' => TRUE);
$fields['author_website'] = array('label' => 'Website');
$fields['new_comment'] = array('label' => 'Comment', 'type' => 'textarea', 'required' => TRUE);
$fields['post_id'] = array('type' => 'hidden', 'value' => $post->id);
$fields['antispam'] = array('type' => 'hidden', 'value' => $antispam);
if (!empty($vars['captcha']))
{
$fields['captcha'] = array('required' => TRUE, 'label' => 'Security Text', 'value' => '', 'after_html' => ' <span class="captcha">'.$vars['captcha']['image'].'</span><br /><span class="captcha_text">'.lang('blog_captcha_text').'</span>');
}
// now merge with config... can't do array_merge_recursive'
foreach($blog_config['comment_form']['fields'] as $key => $field)
{
if (isset($fields[$key])) $fields[$key] = array_merge($fields[$key], $field);
}
if (!isset($blog_config['comment_form']['label_layout'])) $this->form_builder->label_layout = 'left';
if (!isset($blog_config['comment_form']['submit_value'])) $this->form_builder->submit_value = 'Submit Comment';
if (!isset($blog_config['comment_form']['use_form_tag'])) $this->form_builder->use_form_tag = TRUE;
if (!isset($blog_config['comment_form']['display_errors'])) $this->form_builder->display_errors = TRUE;
$this->form_builder->form_attrs = 'method="post" action="'.site_url($this->uri->uri_string()).'#comments_form"';
$this->form_builder->set_fields($fields);
$this->form_builder->set_field_values($field_values);
$this->form_builder->set_validator($this->blog_comments_model->get_validation());
$vars['comment_form'] = $this->form_builder->render();
$vars['fields'] = $fields;
}
$output = $this->_render('post', $vars, TRUE);
// save cache only if we are not posting data
if (!empty($_POST))
{
$this->fuel->blog->save_cache($cache_id, $output);
}
}
if (!empty($output))
{
$this->output->set_output($output);
return;
}
}
else
{
show_404();
}
}
function _process_comment($post)
{
if (!is_true_val($this->fuel->blog->config('allow_comments'))) return;
$notified = FALSE;
// check captcha
if (!$this->_is_valid_captcha())
{
add_error(lang('blog_error_captcha_mismatch'));
}
// check that the site is submitted via the websit
if (!$this->_is_site_submitted())
{
add_error(lang('blog_error_comment_site_submit'));
}
// check consecutive posts
if (!$this->_is_not_consecutive_post())
{
add_error(lang('blog_error_consecutive_comments'));
}
$this->load->module_model(BLOG_FOLDER, 'blog_users_model');
$user = $this->blog_users_model->find_one(array('fuel_users.email' => $this->input->post('author_email', TRUE)));
// create comment
$this->load->module_model(BLOG_FOLDER, 'blog_comments_model');
$comment = $this->blog_comments_model->create();
$comment->post_id = $post->id;
$comment->author_id = (!empty($user->id)) ? $user->id : NULL;
$comment->author_name = $this->input->post('author_name', TRUE);
$comment->author_email = $this->input->post('author_email', TRUE);
$comment->author_website = $this->input->post('author_website', TRUE);
$comment->author_ip = $_SERVER['REMOTE_ADDR'];
$comment->content = trim($this->input->post('new_comment', TRUE));
$comment->date_added = NULL; // will automatically be added
//http://googleblog.blogspot.com/2005/01/preventing-comment-spam.html
//http://en.wikipedia.org/wiki/Spam_in_blogs
// check double posts by IP address
if ($comment->is_duplicate())
{
add_error(lang('blog_error_comment_already_submitted'));
}
// if no errors from above then proceed to submit
if (!has_errors())
{
// submit to akisment for validity
$comment = $this->_process_akismet($comment);
// process links and add no follow attribute
$comment = $this->_filter_comment($comment);
// set published status
if (is_true_val($comment->is_spam) OR $this->fuel->blog->config('monitor_comments'))
{
$comment->published = 'no';
}
// save comment if saveable and redirect
if (!is_true_val($comment->is_spam) OR (is_true_val($comment->is_spam) AND $this->fuel->blog->config('save_spam')))
{
if ($comment->save())
{
$notified = $this->_notify($comment, $post);
$this->load->library('session');
$vars['post'] = $post;
$vars['comment'] = $comment;
$this->session->set_flashdata('thanks', TRUE);
$this->session->set_userdata('last_comment_ip', $_SERVER['REMOTE_ADDR']);
$this->session->set_userdata('last_comment_time', time());
redirect($post->url);
}
else
{
add_errors($comment->errors());
}
}
else
{
add_error(lang('blog_comment_is_spam'));
}
}
return $notified;
}
// check captcha validity
function _is_valid_captcha()
{
$valid = TRUE;
// check captcha
if (is_true_val($this->fuel->blog->config('use_captchas')))
{
if (!$this->input->post('captcha'))
{
$valid = FALSE;
}
else if (!is_string($this->input->post('captcha')))
{
$valid = FALSE;
}
else
{
$post_captcha_md5 = $this->_get_encryption($this->input->post('captcha'));
$session_captcha_md5 = $this->session->userdata('comment_captcha');
if ($post_captcha_md5 != $session_captcha_md5)
{
$valid = FALSE;
}
}
}
return $valid;
}
// check to make sure the site issued a session variable to check against
function _is_site_submitted()
{
return ($this->session->userdata('antispam') AND $this->input->post('antispam') == $this->session->userdata('antispam'));
}
// disallow multiple successive submissions
function _is_not_consecutive_post()
{
$valid = TRUE;
$time_exp_secs = $this->fuel->blog->config('multiple_comment_submission_time_limit');
$last_comment_time = ($this->session->userdata('last_comment_time')) ? $this->session->userdata('last_comment_time') : 0;
$last_comment_ip = ($this->session->userdata('last_comment_ip')) ? $this->session->userdata('last_comment_ip') : 0;
if ($_SERVER['REMOTE_ADDR'] == $last_comment_ip AND !empty($time_exp_secs))
{
if (time() - $last_comment_time < $time_exp_secs)
{
$valid = FALSE;
}
}
return $valid;
}
// process through akisment
function _process_akismet($comment)
{
if ($this->fuel->blog->config('akismet_api_key'))
{
$this->load->module_library(BLOG_FOLDER, 'akismet');
$akisment_comment = array(
'author' => $comment->author_name,
'email' => $comment->author_email,
'body' => $comment->content
);
$config = array(
'blog_url' => $this->fuel->blog->url(),
'api_key' => $this->fuel->blog->config('akismet_api_key'),
'comment' => $akisment_comment
);
$this->akismet->init($config);
if ( $this->akismet->errors_exist() )
{
if ( $this->akismet->is_error('AKISMET_INVALID_KEY') )
{
log_message('error', 'AKISMET :: Theres a problem with the api key');
}
elseif ( $this->akismet->is_error('AKISMET_RESPONSE_FAILED') )
{
log_message('error', 'AKISMET :: Looks like the servers not responding');
}
elseif ( $this->akismet->is_error('AKISMET_SERVER_NOT_FOUND') )
{
log_message('error', 'AKISMET :: Wheres the server gone?');
}
}
else
{
$comment->is_spam = ($this->akismet->is_spam()) ? 'yes' : 'no';
}
}
return $comment;
}
// strip out
function _filter_comment($comment)
{
$this->load->helper('security');
$comment_attrs = array('content', 'author_name', 'author_email', 'author_website');
foreach($comment_attrs as $filter)
{
$text = $comment->$filter;
// first remove any nofollow attributes to clean up... not perfect but good enough
$text = preg_replace('/<a(.+)rel=["\'](.+)["\'](.+)>/Umi', '<a$1rel="nofollow"$3>', $text);
// $text = str_replace('<a ', '<a rel="nofollow"', $text);
$text = strip_image_tags($text);
$comment->$filter = $text;
}
return $comment;
}
function _notify($comment, $post)
{
// send email to post author
if (!empty($post->author))
{
$config['wordwrap'] = TRUE;
$this->load->library('email', $config);
$this->email->from($this->fuel->config('from_email'), $this->fuel->config('site_name'));
$this->email->to($post->author->email);
$this->email->subject(lang('blog_comment_monitor_subject', $this->fuel->blog->config('title')));
$msg = lang('blog_comment_monitor_msg');
$msg .= "\n".fuel_url('blog/comments/edit/'.$comment->id)."\n\n";
$msg .= (is_true_val($comment->is_spam)) ? lang('blog_email_flagged_as_spam')."\n" : '';
$msg .= lang('blog_email_published').": ".$comment->published."\n";
$msg .= lang('blog_email_author_name').": ".$comment->author_name."\n";
$msg .= lang('blog_email_author_email').": ".$comment->author_email."\n";
$msg .= lang('blog_email_author_website').": ".$comment->author_website."\n";
$msg .= lang('blog_email_author_ip').": ".gethostbyaddr($comment->author_ip)." (".$comment->author_ip.")\n";
$msg .= lang('blog_email_content').": ".$comment->content."\n";
$this->email->message($msg);
return $this->email->send();
}
else
{
return FALSE;
}
}
function _render_captcha()
{
$this->load->library('captcha');
$blog_config = $this->config->item('blog');
$assets_folders = $this->config->item('assets_folders');
$blog_folder = MODULES_PATH.BLOG_FOLDER.'/';
$captcha_path = $blog_folder.'assets/captchas/';
$word = strtoupper(random_string('alnum', 5));
$captcha_options = array(
'word' => $word,
'img_path' => $captcha_path, // system path to the image
'img_url' => captcha_path('', BLOG_FOLDER), // web path to the image
'font_path' => $blog_folder.'fonts/',
);
$captcha_options = array_merge($captcha_options, $blog_config['captcha']);
if (!empty($_POST['captcha']) AND $this->session->userdata('comment_captcha') == $this->input->post('captcha'))
{
$captcha_options['word'] = $this->input->post('captcha');
}
$captcha = $this->captcha->get_captcha_image($captcha_options);
$captcha_md5 = $this->_get_encryption($captcha['word']);
$this->session->set_userdata('comment_captcha', $captcha_md5);
return $captcha;
}
function _get_encryption($word)
{
$captcha_md5 = md5(strtoupper($word).$this->config->item('encryption_key'));
return $captcha_md5;
}
}
My goal is:
1.) Enable 'Blog' Module / template / functionality and understand how I did it. I find the docs lacking, I'm also new at code igniter so that could be why. I just want the most basic way to do this for now.
And 2.) I want to create a page 'from scratch' that resolves on the dashboard side as well. I have created pages in /views/ but they resolve with that whole string /fuel/application/views/page/ I want to create a normal page without all that in the URL. I have tried creating corresponding controllers even variables and haven't had much luck!!!!!!!
As of FUEL CMS 1.0 the blog module is no longer bundled with the CMS by default. You would need to do the following:
Download & setup FUEL CMS per the install instructions here: https://github.com/daylightstudio/FUEL-CMS
Next, once you've got that up and running you can download & setup the blog module per the instructions here: https://github.com/daylightstudio/FUEL-CMS-Blog-Module
Once the blog is setup, you should be able to access it at "yourdomain.com/blog". As far as creating themes, there is a views/themes folder in the blog module which contains a default theme and also where you can setup your custom theme. Additional information about the blog module & theming can be found here http://docs.getfuelcms.com/modules/blog
It seems I've hit a wall here and could use some help
Would like to pass a MySql variable to a Joomla Module
Im using Yootheme's Widget-kit to display tweets from a search term. Works great and all but you need to enter the twitter search term in the Module back end.
Instead I would like to use a variable ( already used on the page) and pass that variable to the Twitter module so it can display the tweets I want
Here are some lines of PHP with the variable I'd like to use
$document->setTitle(JText::sprintf('COVERAGE_DATA_PLACE', $this->country->country_name, $this->city->city_name));
$text = JString::str_ireplace('%city_name%',$this->city->city_name,$text);
$this->setBreadcrumbs(array('country','city'));
Is there any way to take the "City" variable and send it to the 'word" field found in the twitter module?
Here is the Code for the twitter module
<?php
Class: TwitterWidgetkitHelper
Twitter helper class
*/
class TwitterWidgetkitHelper extends WidgetkitHelper {
/* type */
public $type;
/* options */
public $options;
/*
Function: Constructor
Class Constructor.
*/
public function __construct($widgetkit) {
parent::__construct($widgetkit);
// init vars
$this->type = strtolower(str_replace('WidgetkitHelper', '', get_class($this)));
$this->options = $this['system']->options;
// create cache
$cache = $this['path']->path('cache:');
if ($cache && !file_exists($cache.'/twitter')) {
mkdir($cache.'/twitter', 0777, true);
}
// register path
$this['path']->register(dirname(__FILE__), $this->type);
}
/*
Function: site
Site init actions
Returns:
Void
*/
public function site() {
// add translations
foreach (array('LESS_THAN_A_MINUTE_AGO', 'ABOUT_A_MINUTE_AGO', 'X_MINUTES_AGO', 'ABOUT_AN_HOUR_AGO', 'X_HOURS_AGO', 'ONE_DAY_AGO', 'X_DAYS_AGO') as $key) {
$translations[$key] = $this['system']->__($key);
}
// add stylesheets/javascripts
$this['asset']->addFile('css', 'twitter:styles/style.css');
$this['asset']->addFile('js', 'twitter:twitter.js');
$this['asset']->addString('js', sprintf('jQuery.trans.addDic(%s);', json_encode($translations)));
// rtl
if ($this['system']->options->get('direction') == 'rtl') {
$this['asset']->addFile('css', 'twitter:styles/rtl.css');
}
}
/*
Function: render
Render widget on site
Returns:
String
*/
public function render($options) {
if ($tweets = $this->_getTweets($options)) {
// get options
extract($options);
return $this['template']->render("twitter:styles/$style/template", compact('tweets', 'show_image', 'show_author', 'show_date', 'image_size'));
}
return 'No tweets found.';
}
/*
Function: _getURL
Create Twitter Query URL
Returns:
String
*/
protected function _getURL($options) {
// get options
extract($options);
// clean options
foreach (array('from_user', 'to_user', 'ref_user', 'word', 'nots', 'hashtag') as $var) {
$$var = preg_replace('/[##]/', '', preg_replace('/\s+/', ' ', trim($$var)));
}
// build query
$query = array();
if ($from_user) {
$query[] = 'from:'.str_replace(' ', ' OR from:', $from_user);
}
if ($to_user) {
$query[] = 'to:'.str_replace(' ', ' OR to:', $to_user);
}
if ($ref_user) {
$query[] = '#'.str_replace(' ', ' #', $ref_user);
}
if ($word) {
$query[] = $word;
}
if ($nots) {
$query[] = '-'.str_replace(' ', ' -', $nots);
}
if ($hashtag) {
$query[] = '#'.str_replace(' ', ' #', $hashtag);
}
$limit = min($limit ? intval($limit) : 5, 100);
// build timeline url
if ($from_user && !strpos($from_user, ' ') && count($query) == 1) {
$url = 'http://twitter.com/statuses/user_timeline/'.strtolower($from_user).'.json';
if ($limit > 15) {
$url .= '?count='.$limit;
}
return $url;
}
// build search url
if (count($query)) {
$url = 'http://search.twitter.com/search.json?q='.urlencode(implode(' ', $query));
if ($limit > 15) {
$url .= '&rpp='.$limit;
}
return $url;
}
return null;
}
/*
Function: _getTweets
Get Tweet Object Array
Returns:
Array
*/
protected function _getTweets($options) {
// init vars
$tweets = array();
// query twitter
if ($url = $this->_getURL($options)) {
if ($path = $this['path']->path('cache:twitter')) {
$file = rtrim($path, '/').sprintf('/twitter-%s.php', md5($url));
// is cached ?
if (file_exists($file)) {
$response = file_get_contents($file);
}
// refresh cache ?
if (!file_exists($file) || (time() - filemtime($file)) > 300) {
// send query
$request = $this['http']->get($url);
if (isset($request['status']['code']) && $request['status']['code'] == 200) {
$response = $request['body'];
file_put_contents($file, $response);
}
}
}
}
// create tweets
if (isset($response)) {
$response = json_decode($response, true);
if (is_array($response)) {
if (isset($response['results'])) {
foreach ($response['results'] as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['from_user'];
$tweet->name = $res['from_user'];
$tweet->image = $res['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
} else {
foreach ($response as $res) {
$tweet = new WidgetkitTweet();
$tweet->user = $res['user']['screen_name'];
$tweet->name = $res['user']['name'];
$tweet->image = $res['user']['profile_image_url'];
$tweet->text = $res['text'];
$tweet->created_at = $res['created_at'];
$tweets[] = $tweet;
}
}
}
}
return array_slice($tweets, 0, $options['limit'] ? intval($options['limit']) : 5);
}
}
class WidgetkitTweet {
public $user;
public $name;
public $image;
public $text;
public $created_at;
public function getLink() {
return 'http://twitter.com/'.$this->user;
}
public function getText() {
// format text
$text = preg_replace('#(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)#', '$1', $this->text);
$text = preg_replace('/#(\w+)/', '#$1', $text);
$text = preg_replace('/\s+#(\w+)/', ' #$1', $text);
return $text;
}
}
// bind events
$widgetkit = Widgetkit::getInstance();
$widgetkit['event']->bind('site', array($widgetkit['twitter'], 'site'));
I believe you can do what you want with this:
http://www.j-plant.com/joomla-extensions/free-extensions/26-module-plant.html
This plugin supports module parameters overriding. Use the next code
for overriding parameters:
[moduleplant id="77" <param_name_1>="<param_value_1>" <param_name_N>="<param_value_N>"]
replace and with the necessary parameter name and value.
You can override as many parameters as you want.
Available module parameters can be found in module XML manifest
file. A manifest file is usually located in the next path:
modules/<module_type>/<module_type>.xml