How do I call this function in CodeIgniter controller? - php

I've got this code, but I'm not sure I make it work:
/**
* Function: youtube data grabber
*
* #description :
* #param $ : video code, url type (embed/url)
* #return : data array
* #author : Mamun.
* #last -modified-by: Mamun.
*/
if (! function_exists('youtube_data_grabber'))
{
function youtube_data_grabber($video_code, $link_type = "embed")
{
if ($video_code != '')
{
if ($link_type == "embed")
{
$splited_data = explode("=",$video_code);
$video_unique_code = substr(strrchr($splited_data[4],"/"),1,-strlen(strrchr($splited_data[4],"&")));
}
else if ($link_type == "url")
{
$splited_data = explode("=",$video_code);
$video_unique_code = substr($splited_data[1],0,-strlen(strrchr($splited_data[1],"&")));
}
else
{
return;
}
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$video_unique_code;
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
return $sxml;
}
}
} // End Youtube Function
I'm not sure how to activate it is what I'm trying to say. I placed it in the controller and it's within a function for one of my pages. I don't have any syntax errors. I just don't know how to wake it up and make it work. I thought I could just put youtube_data_grabber('http://www.youtube.com/watch?v=LAcrFym10ZI', 'url'); but that didn't work.
I got the code from this blog, and I have the zend functionality working. I tested it earlier and had no errors. I'm just having trouble with this youtube part.
Any ideas?

That code should go in a helper or plugin not in the controller. The first part of the code on that page should be in your controller. The one you pasted is just an alternate version.

Save your code to application/helpers/youtube_helper.php, then in your controller go ahead and call $this->load->helper('youtube').
Only then will your youtube_data_grabber() function be available.

Related

OctoberCMS Translate plugin redirect with hash

I am using OctoberCMS Translate plugin (https://octobercms.com/plugin/rainlab-translate) and its working as per my expectations.
However, I have one custom requirement in which I am generating hash in url (i.e. http://localhost/ibis/whats-on/details#2020-sydney-international-whitewater-event - #2020-sydney-international-whitewater-event).
Now the thing is, when I am supposed to redirect using below code,
{% for code, name in locales %}
<a class="dropdown-item" href="#" data-request="onSwitchLocale" data-request-data="locale: '{{ code }}'">
{{ name |upper }}
</a>
I am able to redirect, however, my url looses its hash tag and it becomes something like http://localhost/ibis/fr/whats-on/details (fr is my selected french language).
Here below is my overwrite code in my layout's code tab to onSwitchLocale method which is provided by Translate plugin.
use RainLab\Translate\Models\Locale as LocaleModel;
use RainLab\Translate\Classes\Translator;
use October\Rain\Router\Router as RainRouter;
function onSwitchLocale()
{
$this->translator = Translator::instance();
$locale = post('locale');
if (!$locale = post('locale')) {
return;
}
$this->translator->setLocale($locale);
$pageUrl = $this->translator->withPreservedQueryString($this->translator->makeLocaleUrlFromPage($locale), $locale);
if ($this->property('forceUrl')) {
return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
}
return Redirect::to($pageUrl);
}
As you can see I am trying to accomplish url redirect with hash, but I am getting error here saying
Call to undefined method RainLab\Translate\Classes\Translator::withPreservedQueryString()
And unable to proceed this request. I researched further and found withPreservedQueryString has protected method and I tried various ways to execute this method but unable to do so.
So first I need to accomplish this and second I want to append that hash tag in my url.
Can someone guide me from here on how can I achieve this ?
Thanks
I am not sure $this->translator [ Translator::instance(); ] has this method there ! its just method of LocalePicker component.
This is implemented code there, so use this and define your own method
protected function withPreservedQueryString($pageUrl, $locale)
{
$page = $this->getPage();
$query = request()->query();
/**
* #event translate.localePicker.translateQuery
* Enables manipulating the URL query parameters
*
* You will have access to the page object, the old and new locale and the URL query parameters.
*
* Example usage:
*
* Event::listen('translate.localePicker.translateQuery', function($page, $params, $oldLocale, $newLocale) {
* if ($page->baseFileName == 'your-page-filename') {
* return YourModel::translateParams($params, $oldLocale, $newLocale);
* }
* });
*
*/
$translatedQuery = Event::fire('translate.localePicker.translateQuery',
[$page, $query, $this->oldLocale, $locale], true);
$query = http_build_query($translatedQuery ?: $query);
return $query ? $pageUrl . '?' . $query : $pageUrl;
}
Use it like this
$pageUrl = $this->
withPreservedQueryString( // <- this call
$this->translator->makeLocaleUrlFromPage($locale),
$locale
);
if ($this->property('forceUrl')) {
return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
}
it should work, if any doubt please comment.

PHP issue - Unable to place static URL in code

I am frankly not into coding but need help in modifying an existing code.
As you can see in below code, the script tries to call the URL -> store or destination whichever it maybe.
I simply want to prefix a static URl before the below URL is generated.
For example - if through below code I get : www.amazon.com, I'm simply trying to find a way where instead of direct link showing up -> it should be something like:
www.domain.com/script.php?id=www.amazon.com
I think we need to modify the code somewhere here. Hence basically -> "www.domain.com/script.php?id=" should be prefixed in ALL outgoing URLs.
Any help is really appreciated!
(hope i dont get banned >_<)
/**
* Get destination url
*
* #since 1.0.0
* #param bool $store_url_if_empty
* #return bool|string
*/
public function get_destination_url( $store_url_if_empty = true ) {
$url = '';
if ( ! $this->_wpc_destination_url && $store_url_if_empty ) {
$url = $this->get_store_site_url();
} else {
$url = $this->_wpc_destination_url;
}
if ( ! $url ) {
$url = $this->store->get_url();
}
return $url;
}
Just before return statement
$static = "www.domain.com/script.php?id=";
$url =$static.$url;
return $url;

PHP include Page.php, if Page=404 { PHP include API { WRITE API as Page.php (Storing APIs on Servers)

I'm scraping data from an API. The problem is that I'm querying the data too often for each pageload, so I'd like to store the data on the server after the first query. This should be fine according to the TOS.
On example.com/page:
<?php include 'example.com/data'; ?>
On example.com/data:
<?php include 'api.com/include'; ?>
So I am including a page from my server, and that page is including the api data from the external server.
Question 1: How can I tell example.com/data to WRITE or save the information from api.com/include as a file on the server such as example.com/data1.php ?
Question 2: How can I tell example.com/page to php include example.com/data1.php, and if it's a 404 (doesn't exist) to include example.com/data instead?
With both questions 1 and 2 answered I can query the api once, store the data as a file, and if that file exists use the data from that page rather than have to query the api each time the page is loaded.
If you know of a better way of doing this I'd be grateful to learn it. Though it is important that I include from example.com/data from example.com/page rather than directly from api.com/include because example.com/data has the correct code handlers to properly interpret and filter the information from api/include.
If you can answer either of the two questions it would be a great starting ground for me solving the other problem.
Thank you!
You should use a class to decouple this behaviour. Something like this:
<?php
class ReadApiFromDomainDotCom
{
const TTL = 3600; // File is fresh for 3600 sec
const FILE_NAME = 'whatever.txt';
const API_ADDRESS = "http://api.whatever.com";
/**
* #return string
*/
public function get()
{
if ($this->isCacheValid()) {
return file_get_contents(self::FILE_NAME);
}
return $this->readApi();
}
/**
* #return bool
*/
private function isCacheValid()
{
if (!file_exists(self::FILE_NAME)) {
return false;
}
if ($this->isExpired()) {
return false;
}
return true;
}
/**
* #return bool
*/
private function isExpired()
{
return time() - filemtime(self::FILE_NAME) > self::TTL;
}
/**
* #return string
*/
private function readApi()
{
$data = file_get_contents(self::API_ADDRESS);
file_put_contents(self::FILE_NAME, $data);
return $data;
}
}
Then it will be easy as:
$apiReader = new ReadApiFromDomainDotCom();
$data $apiReader->get();
Haven't tested this code so you will have to fiddle with it a bit. Add namespace, paths and so on.

How to remove a previously added script file in a Zend Framework controller?

Is it possible to remove a script that was previously added like this?
$this->view->headScript()->appendFile("/js/my.js");
The situation here is that in my Bootstrap.php several JavaScript files are appended like in the above example but in a particular controller I want one particular JavaScript file not to be loaded. Is there a way to remove it during the initiation of the controller?
I am looking for something like this.
$this->view->headScript()->removeFile("/js/my.js");
This works, but really isn't a good practice but rather for exceptional purposes. I recommend trying to not load the unwanted scripts in the first place.
It is possible to remove scripts subsequently with a function like this one.
/**
* Removes a previously appended script file.
*
* #param string $src The source path of the script file.
* #return boolean Returns TRUE, if the removal has been a success.
*/
public function removeScript($src) {
$headScriptContainer = Zend_View_Helper_Placeholder_Registry::getRegistry()
->getContainer("Zend_View_Helper_HeadScript");
$iter = $headScriptContainer->getIterator();
$success = FALSE;
foreach ($iter as $k => $value) {
if(strpos($value->attributes["src"], $src) !== FALSE) {
$iter->offsetUnset($k);
$success = TRUE;
}
}
Zend_View_Helper_Placeholder_Registry::getRegistry()
->setContainer("Zend_View_Helper_HeadScript",$headScriptContainer);
return $success;
}
Note that the strpos function is used here. This will remove every script that has $src in its path. Of course you can change that to your needs.
It's an old question, but here is an alternative:
I used the minifyHeadScript and changed his helper adding this custom function:
/**
* Removes all script file.
*
*/
public function clearAllScripts(){
$this->getContainer()->exchangeArray(array());
$container = $this->getContainer();
Zend_View_Helper_Placeholder_Registry::getRegistry()->setContainer("Zend_View_Helper_HeadScript", $container);
}

How to retrieve the current page from Zend_Navigation within a Controller Plugin

I am working on an Authentication Plugin using a Controller Plugin. I define my navigation config within the application.ini file, and then use that and the Database user records to dynamically load the ACL and apply it to Zend_Navigation. This bit works, as it successfully loads the menu and only displays the pages the user is allowed to see.
However, this doesn't stop the user from going to the page directly. What I want to do is identify when the user is going to a page they don't have access to within the Controller Plugin so I can redirect their request to the Authentication page.
I was thinking there must be a function to retrieve the current page from Zend_Navigation, but I can't find it... so maybe it doesn't exist.
Anyway, this is my full Controller Plugin. Anyone see a solution?
<?php
class Pog_Model_AuthPlugin extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $oRequest)
{
/**
* Load user
*/
$oAuth = Zend_Auth::getInstance();
$oDbUsers = new Pog_Model_DbTable_Users();
if (!$oAuth->hasIdentity())
{
$oUser = $oDbUsers->createRow();
$oUser->name = "guest";
$oUser->setReadOnly(true);
}
else
{
$oUser = $oAuth->getIdentity();
$oUser->setTable($oDbUsers);
}
/**
* Load ACL
*/
$oAcl = new Zend_Acl();
$oAcl->addRole($oUser->name);
/**
* Add current user privileges
*/
$oPrivileges = $oUser->getPrivileges();
foreach ($oPrivileges as $oPrivilege)
{
if (!$oAcl->has($oPrivilege->resource))
$oAcl->addResource($oPrivilege->resource);
$oAcl->allow($oUser->name, $oPrivilege->resource, $oPrivilege->privilege);
}
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/**
* Add remaining Navigation resources
*/
foreach ($oNavigation->getPages() as $oPage)
{
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}
/**
* Set ACL and Role
*/
$oNavigation->setAcl($oAcl)->setRole($oUser->name);
/**
* Check if use is allowed to be here
*/
...MAGIC GOES HERE...
}
}
I think that you should be able to get current navigation page as follows:
/**
* Load Navigation view helper
*/
$oViewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$oNavigation = $oViewRenderer->view->navigation();
/*#var $active array */
$active = $oNavigation->findActive($oNavigation->getContainer());
/*#var $activePage Zend_Navigation_Page_Mvc */
$activePage = $active['page'];
// example of getting page info
var_dump($activePage->getLabel(), $activePage->getController(), $activePage->getAction());
Hope this helps.
This is the solution I used, since I can't get Marcin's solution working in my setup for some reason.
I did some more thinking and thought of a nice simple solution to the problem. Rather than use the Navigation module to find the Active page, I find it myself. Since I am already iterating through the pages, it's a piece of cake to compare the Controller and Action - if these both match I have my Active page!
The new getPages() foreach loop looks like this:
$oCurrentPage = null;
foreach ($oNavigation->getPages() as $oPage)
{
/**
* Check for Current Page
*/
if ($oPage->getController() == $oRequest->getControllerName()
&& $oPage->getAction() == $oRequest->getActionName())
$oCurrentPage = $oPage;
/**
* Add Resource, if missing
*/
if (!is_null($oPage->getResource()) && !$oAcl->has($oPage->getResource()))
$oAcl->addResource($oPage->getResource());
}

Categories