Joomla 2.5 plugin wont work - plugins

I'm beginner and I wanna write a simple plugin for my website but I have some problems.
When I trying to import my plugin through the div into the article
<div id="locker-464" class="like-dl blue"> </div>
I only get the css frame no js.
jimport('joomla.plugin.plugin');
$document = & JFactory::getDocument();
$document->addStyleSheet(JURI::root() . 'plugins/content/plugin/tmpl/css/style.css', 'text/css', null, array() );
$document->addScript(JURI::root() . 'plugins/content/plugin/tmpl/js/liketodownlad.js');
$document->addScript ("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js");
$document->addScript ("http://connect.facebook.net/en_US/all.js#xfbml=1");
class plgContentLiketoDownload extends JPlugin {
function plgContentLiketoDownload( &$subject, $params )
{
parent::__construct( $subject, $params );
}
function onContentPrepare($context, &$params)
{
global $mainframe;
$app = JFactory::getApplication();
$plugin = & JPluginHelper::getPlugin('content', 'plugin');
echo "<script type=\"text/javascript\">
var $jx = jQuery.noConflict();
$jx(document).ready(function(){
$jx('#locker-464').liketodl({
download_url: 'http://website.com/sampleDownload.zip',
like_url: 'https://www.facebook.com/FBpage',
like_colorscheme: 'light'
});
$jx('#locker-564').liketodl({
download_url: 'sampleDownload.zip',
like_url: 'http://google.com',
like_colorscheme: 'list'
});
});";
</script>";
return true;
}
}
?>

The onContentPrepare method signature is:
public function onContentPrepare($context, &$row, &$params, $page = 0)
{
... your stuff
}
If you are replacing content of an article, assigning to $row->text will alter the output. Check /plugins/content/pagebreak/pagebreak.php for an example.
If you are using PHP 5.x don't use plgContentLikeToDownload as your constructor:
public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
$this->loadLanguage(); // if needed
}
See http://docs.joomla.org/J2.5:Creating_a_Plugin_for_Joomla
EDIT
Remove all the code outside the class declaration and try this:
jimport('joomla.plugin.plugin');
class plgContentLiketoDownload extends JPlugin {
function plgContentLiketoDownload( &$subject, $params )
{
parent::__construct( $subject, $params );
}
public function onContentPrepare($context, &$row, &$params, $page = 0)
{
$row->text = "Hello world!";
return true;
}
}
END EDIT
Regards

Related

How do I write unit tests for a REST API built in Slim Framework?

I have an API built in Slim like this:
$app->group('/'.$endpoint, function () use ($app, $endpoint) {
$handler = Api\Rest\Handlers\Factory::load($endpoint);
if (is_null($handler)) {
throw new \Exception('No REST handler found for '.$endpoint);
}
$app->get('(/:id)', function ($id) use ($app, $handler) {
echo json_encode($handler->get($id));
});
$app->post('', function () use ($app, $handler) {
echo json_encode($handler->post($app->request->post()));
});
$app->put(':id', function ($id) use ($app, $handler) {
echo json_encode($handler->put($id, $app->request->put()));
});
$app->delete(':id', function ($id) use ($app, $handler) {
echo json_encode($handler->delete($id));
});
});
$endpoint is a string, for example 'user';
How do I go about writing unit tests for it?
Ideally;
class RestUserTest extends PHPUnitFrameworkTestCase
{
public function testGet()
{
$slim = ''; // my slim app
// set route 'api/user/1' with method GET
// invoke slim
// ensure that what we expected to happen did
}
}
(The REST handler class would make it trivial to mock the results that would ordinarily be backed by a DB.)
It's the nitty gritty of how to spoof the request into Slim that I don't know how to do.
You can have a try with this guidelines. It may help you. I tried it for one of my slim project.
Let me know if that helps.
Codes
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Slim\Environment;
class RoutesTest extends PHPUnit_Framework_TestCase
{
public function request($method, $path, $options = array())
{
// Capture STDOUT
ob_start();
// Prepare a mock environment
Environment::mock(array_merge(array(
'REQUEST_METHOD' => $method,
'PATH_INFO' => $path,
'SERVER_NAME' => 'slim-test.dev',
), $options));
$app = new \Slim\Slim();
$this->app = $app;
$this->request = $app->request();
$this->response = $app->response();
// Return STDOUT
return ob_get_clean();
}
public function get($path, $options = array())
{
$this->request('GET', $path, $options);
}
public function testIndex()
{
$this->get('/');
$this->assertEquals('200', $this->response->status());
}
}
full code hosted in Gist . see this

Zend Framework route/redirect

I am trying to redirect the user to a registered page once they have registered but its not doing so..
<?php
class RegisterController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$form = new Application_Form_Register();
$form->submit->setLabel('Register');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$first_name = $form->getValue('first_name');
$surname = $form->getValue('surname');
$email = $form->getValue('email');
$username = $form->getValue('username');
$password = $form->getValue('password');
$is_admin = $form->getValue('is_admin');
$age = $form->getValue('age');
$gender = $form->getValue('gender');
$uni = $form->getValue('uni');
$register = new Application_Model_DbTable_Users();
$register->addUser($first_name, $surname, $email, $username, $password, $is_admin, $age, $gender, $uni);
} else {
$form->populate($formData);
}
$route = array('controller'=>'Register', 'action'=>'registered');
$this->_helper->redirector->gotoRoute($route);
}
}
public function registeredAction()
{
// action body
}
}
This is what I have
Thanks
In the controller you can to the following:
$this->_redirect('/controller/action');
I usually don't use gotoRoute() therefore I am not sure if this is the cause of your problem, but your controller-name should be all lowercased, i.e. Register should be register or maybe gotoRouteAndExit() will solve your problem (just picked it up from a quick glance at the API)
You could try an alternative: For routing between actions/controllers I find the following most convenient:
$this->_helper->redirector('registered');
Which will redirect you to registeredAction in the same controller. If you want to go to an action in a different controller, just add the controller as 2nd argument like this:
$this->_helper->redirector('registered', 'register');

Zend Framework query db and getParam

At the moment I have a page where I have retrieved information on a club by the id of that club. I now have a comments box where I want to retrieve the comments about that club, in the comments table I have the club_id and the parameter "club_id" is passed into this page. At the moment I am retrieving all of the comments from the table but I want just the comments for that club. A point in the right direction would be great!
Controller:
class ClubDescriptionController extends Zend_Controller_Action
{
public $auth = null;
public function init()
{
$this->auth=Zend_Auth::getInstance();
}
http://pastebin.com/m66Sg26x
protected function authoriseUser()
{
if (!$this->auth->hasIdentity()) {
$route = array('controller'=>'auth', 'action'=>'index');
$this->_helper->redirector->gotoRoute($route);
}
}
}
Model:
class Application_Model_DbTable_Comments extends Zend_Db_Table_Abstract
{
protected $_name = 'comments';
public function getComment($id) {
$id = (int) $id;
$row = $this->fetchRow('id = ' . $id);
if (!$row) {
throw new Exception("Count not find row $id");
}
return $row->toArray();
}
public function addComment($comment, $club_id) {
$data = array(
'comment' => $comment,
'club_id' => $club_id,
'comment_date' => new Zend_Db_Expr('NOW()'),
);
$this->insert($data);
}
public function deleteComment($id) {
$this->delete('id =' . (int) $id);
}
}
The view:
<div id="view-comments">
<?php foreach($this->comments as $comments) : ?>
<p id="individual-comment">
<?php echo $this->escape($comments->comment);?> -
<i><?php echo $this->escape($comments->comment_date);?></i>
</p>
<?php endforeach; ?>
</div>
I realise I am going to have to use the getComment(); function in my model and query it by the id but I'm getting confused on exactly how...
Thanks
It's been a while since I used Db_Table but I think you want to create a select object, which allows you to build a query that will select comments with the correct club_id:
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$this->view->comments = $comments->fetchAll($select);
you may want to order the comments by date, if so, you can do this by adding an order clause to the select:
$select->order('comment_date ASC');
take a look at the docs for Zend_Db_Table_Select, which has quite a few examples: http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.fetch-all
In your controller you are calling
$this->view->comments = $comments->fetchAll();
it should be
$this->view->comments = $comments->getComment($this->_request->getParam('club_id'));
where id variable will be fetched from url.
Here is the working controller:
public function indexAction() {
//authorisation
$this->authoriseUser();
//to get the paramter club_id to query for specific club information
$id = (int) $this->_request->getParam('club_id', 0);
//submit a comment
$form = new Application_Form_Comment();
$form->submit->setLabel('Comment');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$comment = new Application_Model_DbTable_Comments();
$comment->addComment($formData['comment'], $id);
} else {
$form->populate($formData);
}
}
//initialise table
$clubs = new Application_Model_DbTable_Clubs();
$clubs = $clubs->getClub($id);
$this->view->clubs = $clubs;
//to get the comments for the club
$comments = new Application_Model_DbTable_Comments();
$select = $comments->select();
$select->where('club_id = ?', $id);
$select->order('comment_date ASC');
$this->view->comments = $comments->fetchAll($select);
}

Appending scripts from view helper method not working in zend framework

I have a view helper method which is like this
class Zend_View_Helper_LoginForm extends Zend_View_Helper_Abstract
{
public function loginForm()
{
$script = "<script type='text/javascript'>(function (){ $('#submit').click(function (){alert('hello'); return false;})})</script>";
$this->view->headScript()->appendScript($script, $type = 'text/javascript');
$login = new Application_Form_User();
return $login;
}
}
But this is not working. I also tried
$this->view->headScript()->appendFile($this->view->baseUrl('/js/jquery.js'), 'text/javascript');
but this is not working either. If i try this code in layout.phtml then it works.Any Idea?
In view file:
<?php $this->headScript()->appendFile('your/sript/file.js') ?>
In your layout:
<?php echo $this->headScript() ?>
You have to add setView method:
class My_View_Helper_ScriptPath
{
public $view;
public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}
public function scriptPath($script)
{
return $this->view->getScriptPath($script);
}
}

Problem With View Helpers

I wrote few custom view helpers but I have a little trouble using them. If I add the helper path in controller action like this:
public function fooAction()
{
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
Then I can use the views from that path without a problem. But when I add the path in the bootstrap file like this:
protected function _initView()
{
$this->view = new Zend_View();
$this->view->doctype('XHTML1_STRICT');
$this->view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$this->view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$this->view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$this->view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
Then the view helpers don't work. Why is that? It's too troublesome to add the path in every controller action. Here is an example of how my custom view helpers look:
class My_View_Helper_FooBar
{
public function fooBar() {
return 'hello world';
}
}
I use them like this in views:
<?php echo $this->fooBar(); ?>
Should I post my whole bootstrap file?
UPDATE:
Added complete bootstrap file just in case:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initFrontController()
{
$this->frontController = Zend_Controller_Front::getInstance();
$this->frontController->addModuleDirectory(APPLICATION_PATH
. '/modules');
Zend_Controller_Action_HelperBroker::addPath(
'My/Controller/Action/Helper',
'My_Controller_Action_Helper'
);
$this->frontController->registerPlugin(new My_Controller_Plugin_Auth());
$this->frontController->setBaseUrl('/');
}
protected function _initView()
{
$this->view = new Zend_View();
$this->view->doctype('XHTML1_STRICT');
$this->view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$this->view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$this->view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$this->view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$this->view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
protected function _initDb()
{
$this->configuration = new Zend_Config_Ini(APPLICATION_PATH
. '/configs/application.ini',
APPLICATION_ENVIRONMENT);
$this->dbAdapter = Zend_Db::factory($this->configuration->database);
Zend_Db_Table_Abstract::setDefaultAdapter($this->dbAdapter);
$stmt = new Zend_Db_Statement_Pdo($this->dbAdapter,
"SET NAMES 'utf8'");
$stmt->execute();
}
protected function _initAuth()
{
$this->auth = Zend_Auth::getInstance();
}
protected function _initCache()
{
$frontend= array('lifetime' => 7200,
'automatic_serialization' => true);
$backend= array('cache_dir' => 'cache');
$this->cache = Zend_Cache::factory('core',
'File',
$frontend,
$backend);
}
public function _initTranslate()
{
$this->translate = new Zend_Translate('Array',
BASE_PATH . '/languages/Slovak.php',
'sk_SK');
$this->translate->setLocale('sk_SK');
}
protected function _initRegistry()
{
$this->registry = Zend_Registry::getInstance();
$this->registry->configuration = $this->configuration;
$this->registry->dbAdapter = $this->dbAdapter;
$this->registry->auth = $this->auth;
$this->registry->cache = $this->cache;
$this->registry->Zend_Translate = $this->translate;
}
protected function _initUnset()
{
unset($this->frontController,
$this->view,
$this->configuration,
$this->dbAdapter,
$this->auth,
$this->cache,
$this->translate,
$this->registry);
}
protected function _initGetRidOfMagicQuotes()
{
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
}
public function run()
{
$frontController = Zend_Controller_Front::getInstance();
$frontController->dispatch();
}
}
Solved. I just needed to add these lines at the end of _initView() method:
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($this->view);
I in my _initView() have something like this:
protected function _initView() {
$view = new Zend_View();
#some view initialization ...
$view->addHelperPath(APPLICATION_PATH . '/views/helpers', 'My_View_Helper');
return $view;
}
Then in a view I can execute:
<?php echo $this->fooBar(); ?>
Without APPLICATION_PATH it does not work in my case.
Just a thought: are you sure that the view that you are creating in your bootstrap ($this->view = new Zend_View();) is the same as '$this' in your view file?
I think you would need to change your initView code to the following:
protected function _initView()
{
$view = new Zend_View();
$view->doctype('XHTML1_STRICT');
$view->headScript()->appendFile($this->view->baseUrl()
. '/js/jquery-ui/jquery.js');
$view->headMeta()->appendHttpEquiv('Content-Type',
'text/html; charset=UTF-8');
$view->headMeta()->appendHttpEquiv('Content-Style-Type',
'text/css');
$view->headMeta()->appendHttpEquiv('Content-Language', 'sk');
$view->headLink()->appendStylesheet($this->view->baseUrl()
. '/css/reset.css');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
return $view;
}
If you have some View related settings in your config.ini file, you might want to change your code a little bit:
protected function _initMyView()
{
$view = $this->bootstrap('view')->getResource('view');
...
instead of:
protected function _initView()
{
$view = new Zend_View();
....
You might consider adding another init function just for your view helpers:
protected function _initViewHelpers()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath('My/View/Helper', 'My_View_Helper');
}
This way the built in view setup is not overridden.
If you add only $this->view->addHelperPath('My/View/Helper', 'My_View_Helper');
in your bootstrap use this format:
class Zend_View_Helper_FooBar extends Zend_View_Helper_Abstract {
public function fooBar() {
return 'hello world';
}
}