Site map generator in laravel 5 with RoumenDianoff sitemap - php

Im implementing the laravel RoumenDianoff Sitemap in my application
https://github.com/RoumenDamianoff/laravel-sitemap/wiki/Dynamic-sitemap
And im really confused on this part of the code
Route::get('sitemap', function(){
// create new sitemap object
$sitemap = App::make("sitemap");
// set cache key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean)
$sitemap->setCache('laravel.sitemap', 60);
$posts = DB::table('posts')->orderBy('created_at', 'desc')->get();
foreach ($posts as $post)
{
$sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
}
As I understand i'm creating a route to use sitemap as that function so the part I don't get is when do I iterate trough every link of my website, or how do i get this links from my website to add then to the for each on that function, i mean it looks like that $posts variable but I don't have record of my links on any database so how can i get this links.

What I would do is generate the links dynamically (probably using values from the database). Then create a sitemap object that will be populated with all the links (use foreach loop) and finally store this. Check out the code fragment below:
Route::get('sitemap',function(){
// Generate your links dynamically here
$link = [];
$locations = DB::locations(); /** some database values **/
foreach($locations as $location){
$link = route('home') . '/shoes-for-sale-in-' . strtolower($location);
// create new sitemap object
$sitemap = \App::make("sitemap");
// Add link, priority,last modified and change frequency
$sitemap->add($link, null, 0.5, 'monthly');
}
// generate sitemap (format, filename)
$sitemap->store('xml', 'commercial');
});

Related

How can I automatically HREF the articles of my MongoDB database to each article specific page?

I'm working on a site which is more of a DB project that anything else. Currently I mainly using my mongoDB database to show the previews of those articles after querying them with these functions (which are in 2 different files)
//this one is from the functions file which i load in all the various pages of the site
function article_recordset() {
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
$i = 0;
$SiteArticles = $client->SiteArticles;
$articoli=$SiteArticles->Articles;
$cursor = $articoli->find();
return $cursor;
foreach ($cursor as $articolo) {
$recordset = array(
$i=$i+1 => array(
"title" => $articolo["title"],
"description" => $articolo["content"],
"article" => "",
)
);
}
}
//this is the index.php file so the homepage where i display the articles which i stored into an array and then i display with an echo later
include("funzioni.inc.php");//name of the functions file
$ARR_articles = article_recordset();
$STR_article = NULL;
foreach($ARR_articles as $index => $article){
$STR_article .= get_article_item_html(
$img_path = "img/article/".$index.".jpg",
$title = $article["title"],
$description = $article["content"]
);
}
The display works fine and all but what I'm trying to do is to HREF each displayed article preview to their own article page
So article 1 is displayed and is linked to the page of localhost/folder/article1.php for example
Now the href I want to do is somewhat automatic so it links to each article page which I manually created already just like it does the foreach for the query of all the article contents
So like it's going to store each article in the array which I display later while also like setting an href to each one
For example:
Query article 1, store into array, display that array content for article 1 and href it to it's own page, and so on for each article
Note: I want to ""automate"" just the HREF of each queried article not automate the article page creation since I have those pages already created and it's for a small project and nothing too serious

OctoberCMS get list of content files

Trying to get content files started with cont*
using :
Content::loadCached('theme', 'listOfContentFiles');
And getting an error.
I can get one but not the list.
Seems there is no direct way of doing it, you can use this code to get list manually and filter it by your self
use Cms\Classes\Content;
use Cms\Classes\Theme;
$activeTheme = Theme::getActiveTheme();
$instance = Content::inTheme($activeTheme);
$items = $instance->newQuery()->lists('fileName');
$loadedItems = [];
foreach ($items as $item) {
// we need to manually filter data you can
// add more logic here for sub directory parsing etc
if(starts_with($item, 'cont_')) {
$loadedItems[] = Content::loadCached($activeTheme, $item);
}
}
dd($loadedItems);
// if you want to make it collection
$result = $instance->newCollection($loadedItems);
it will return you list of content files in active theme by our filter logic.

Azure PHP SDK: get the asset by asset name

Is it possible to get the asset details using asset name with Azure PHP sdk. I can get all the asset list, but it's loading first 1000 assets only.
getAssetList();
I can get single asset details using asset id.
getAsset($asset);
But in my case, I don't have asset id with me. I just have asset name alone. Now how do I get the asset details using this?
EDIT:
I got some help from Azure support saying that, we can use $skip parameter for pagination. I got code snippet in c#
for (int i = 0; i < _context.Assets.Count(); i += 1000 )
{
var assets = _context.Assets.Skip(i);
foreach (IAsset objIAsset in assets)
{
Console.WriteLine(objIAsset.Name.ToString());
}
}
How can I use this param in PHP SDK.
It seem that Azure SDK for PHP don't support skip method. However, I used the fiddler to monitor C# skip method and got the URL like this:
https://***-hs.cloudapp.net/api/Assets()?$skip=1000
So I think we can bulid up the request path like above in our PHP project and we can modify the getAssetList method in "MediaServicesRestProxy" file.
I add a function named "getAssetListBySkip($number)" into "MediaServicesRestProxy" class, the code like this:
/**
* Get asset list using skip number
*
* */
public function getAssetListBySkip($number)
{
$propertyList = $this->_getEntityList("Assets()?".'$skip='.$number);
$result = array();
foreach ($propertyList as $properties) {
$result[] = Asset::createFromOptions($properties);
}
return $result;
}
We can call this method like this:
$mediaServiceProxy = ServicesBuilder::getInstance()->createMediaServicesService(
new MediaServicesSettings("**","**/**="));
$result=$mediaServiceProxy->getAssetListBySkip(1000);
Azure Media services supports filtering by name. You can construct web request to be like
/api/assets()?$filter=Name%20eq%20'Your Name'&$top=1
You can also filter by other properties
Have you tried REST API that are used when creating, processing, managing, and delivering Assets. https://msdn.microsoft.com/en-us/library/azure/hh974277.aspx#list_an_asset but I do think we can list asset via a name directly since id is an unique indentifier of asset entity. PHP Azure SDK leverages assetId to get an Asset as well:
public function getAsset($asset)
{
$assetId = Utilities::getEntityId(
$asset,
'WindowsAzure\MediaServices\Models\Asset'
);
return Asset::createFromOptions($this->_getEntity("Assets('{$assetId}')"));
}
But in my case, I don't have asset id with me. I just have asset name
alone. Now how do I get the asset details using this?
Here are some test function code snippets for your reference:
public function testListAllAssets(){
// Setup
$asset1 = new Asset(Asset::OPTIONS_NONE);
$asset1->setName(TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix());
$asset2 = new Asset(Asset::OPTIONS_NONE);
$asset2->setName(TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix());
// Test
$asset1 = $this->createAsset($asset1);
$asset2 = $this->createAsset($asset2);
$result = $this->restProxy->getAssetList();
// Assert
$this->assertCount(2, $result);
$names = array(
$result[0]->getName(),
$result[1]->getName()
);
$id = array(
$result[0]->getId(),
$result[1]->getId()
);
$this->assertContains($asset1->getName(), $names);
$this->assertContains($asset2->getName(), $names);
$this->assertContains($asset1->getId(), $id);
$this->assertContains($asset2->getId(), $id);
}
public function testGetAnAssetReference(){
// Setup
$assetName = TestResources::MEDIA_SERVICES_ASSET_NAME . $this->createSuffix();
$asset = new Asset(Asset::OPTIONS_NONE);
$asset->setName($assetName);
$asset = $this->createAsset($asset);
// Test
$result = $this->restProxy->getAsset($asset);
// Assert
$this->assertEquals($asset->getId(), $result->getId());
$this->assertEquals($asset->getName(), $result->getName());
}
From: https://github.com/Azure/azure-sdk-for-php/blob/master/tests/functional/WindowsAzure/MediaServices/MediaServicesFunctionalTest.php
According to my testing, it seems that we can’t use Asset’s name to get the information of asset in Media Service.
$mediaServiceProxy = ServicesBuilder::getInstance()->createMediaServicesService(
new MediaServicesSettings("**","******"));
$asset = new Asset(Asset::OPTIONS_NONE);
$asset->setName('For-Test-wmv-Source');
//$asset don't have the value of id,
// unless execute ‘createAsset($asset)’, "$asset1" will be set the ID
$asset1 =$mediaServiceProxy->createAsset($asset);
$result2=$mediaServiceProxy->getAsset($asset1);
PHP SDK support the method named “getAsset($asset)”. Actually, the method get the Asset information by Asset id, just like the Aka's reference code.And Azure REST API don’t support the method queried by Asset’s name.
Please refer to the official document.
Alternative approach is that you can store your assets information (such as Id,URl,name and ect.) into Azure table storage when you upload them into media service. If you want to use it, you can fetch and filter the data of Asset’s name you wants from table storage.

setting persistent plugin parameters in Joomla 3

I'm developing a Joomla 3.x plugin, and want to be able to change the plugin parameter set in the plugin's manifest file programmatically. I believe I need to use a JRegistry object, but I'm not sure about the syntax.
Here's the issue:
// token A is set in plugin params as defined in plugin's XML manifest
var_dump($this->params->get('token')); // prints token "A" as expected
// do some stuff to get a fresh access token, called token "B"
$tokenB = $function_to_get_fresh_token();
// set the new token
if ($tokenB) $this->params->set('token', $tokenB);
var_dump($this->params->get('apptoken')); // prints token "B" as expected
the problem is that on subsequent page reloads, the token reverts to tokenA rather than what I assumed would be the stored value of tokenB.
How do I store the tokenB value in the plugin's parameters in the database?
This is a working example of how to change plugin params from within the plugin (J! 3.4):
// Load plugin called 'plugin_name'
$table = new JTableExtension(JFactory::getDbo());
$table->load(array('element' => 'plugin_name'));
// Params can be changed like this
$this->params->set('new_param', 'new value'); // if you are doing change from a plugin
$table->set('params', $this->params->toString());
// Save the change
$table->store();
Note: If new params are added by plugin dynamically and the plugin is saved afterwards, these new params gets deleted. So one way to deal with it is to add those params as hidden fields to plugin's config XML.
This is just an outline, but something along these lines
$extensionTable = new JtableExtension();
$pluginId = $extensionTable->find('element', 'my_plugin');
$pluginRow = $extensionTable->load($pluginId);
// Do the jregistry work that is needed
// do some stuff to get a fresh access token, called token "B"
$tokenB = $function_to_get_fresh_token();
// set the new token
if ($tokenB) $this->params->set('token', $tokenB);
// more stuff
$extensionTable->save($pluginRow);
I spent a lot of time googling and reading and found no real answer to this. Oddly enough this doesn't seem to have been provided for in Joomla. So here's what I ended up doing:
1) build a function to get your plugin ID, since it will change from one installation to another
private function getPlgId(){
// stupid hack since there doesn't seem to be another way to get plugin id
$db = JFactory::getDBO();
$sql = 'SELECT `extension_id` FROM `#__extensions` WHERE `element` = "my_plugin" AND `folder` = "my_plugin_folder"'; // check the #__extensions table if you don't know your element / folder
$db->setQuery($sql);
if( !($plg = $db->loadObject()) ){
return false;
} else {
return (int) $plg->extension_id;
}
}
2) use the plugin id to load the table object:
$extension = new JTableExtension($db);
$ext_id = $this->getPlgId();
// get the existing extension data
$extension->load($ext_id);
3) when you're ready to store the value, add it to the params, then store it:
$this->params->set('myvalue', $newvalue);
$extension->bind( array('params' => $this->params->toString()) );
// check and store
if (!$extension->check()) {
$this->setError($extension->getError());
return false;
}
if (!$extension->store()) {
$this->setError($extension->getError());
return false;
}
If anyone knows a better way to do this please let me know!

How to create a hyperlink to a file in an array (paginated files)

I've been playing around with pagination using arrays in php.
I have an array of posts that I use to break the content of a page up into smaller chunks. It works and returns the content as I would like.
<?php
// let's paginate data from an array...
$posts = array(
// array of posts
"blog/posts/06-19-tues.php",
"blog/posts/06-16-sat.php",
"blog/posts/05-26-sat.php",
"blog/posts/05-23-wed.php",
"blog/posts/05-09-wed.php"
);
// how many records should be displayed on a page?
$records_per_page = 3;
// include the pagination class
require 'zebra/Zebra_Pagination.php';
// instantiate the pagination object
$pagination = new Zebra_Pagination();
// the number of total records is the number of records in the array
$pagination->records(count($posts));
// records per page
$pagination->records_per_page($records_per_page);
// here's the magick: we need to display *only* the records for the current page
$posts = array_slice(
$posts,
(($pagination->get_page() - 1) * $records_per_page),
$records_per_page
);
?>
<?php foreach ($posts as $index => $post):?>
<?php include $post; ?>
<?php endforeach?>
<?php
// render the pagination links
$pagination->render();
?>
My question is now how to link to the individual posts from elsewhere on the site. Since they will, ultimately move from page to page, linking directly to the static file won't work. At first, I had given each post a unique id and used that to link to the post but that won't work now since the link will change, dynamically.
I've looked at array_search() and it looks promising but I don't understand it's use enough to get it to produce a hyperlink.
I'm not sure I've phrased this question all that well. apologies if I don't make much sense.
If I understand you correctly, I think something like this will work:
if (isset($_REQUEST['page']) {
$found = array_search($_REQUEST['page'], $posts);
if ($found) {
$pagination->set_page(floor($found/$records_per_page)+1);
}
}
Then you can use a link like
$link = 'whatever';

Categories