Amazon ECS API to fetch 1000 top selling books - amazon-web-services

I need the API to fetch the top selling books on Amazon. By default it only fetches the top 10 items, but I need more than 10, near about 1000 items content by using single hit.
OR
I need the way to scrape the 1000 top selling books using the Amazon ECS API.
OR
Is there any way except the Amazon API to scrape all of the top selling books on Amazon?

To get the 100 bestselling books you have to specify the ItemPage parameter:
http://ecs.amazonaws.com/onca/xml?
Service=AWSECommerceService&
AWSAccessKeyId=[AWS Access Key ID]&
Operation=ItemSearch&
BrowseNode=17&
SearchIndex=Books&
ItemPage=2
&Sort=salesrank
&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
&Signature=[Request Signature]
Problem: The maximum ItemPage number that can be returned is 10. So you cant get past 100 books.
Reference: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?ItemSearch.html

here's how I do it - but it won't work for more than 100 items after the end of this month as Amazon are limiting ItemPage to 10.
rescheck = Amazon::Ecs.item_search("search term here", :response_group => 'Large', :country => 'uk')
n=0
rescheck.total_pages.times do |n|
n=n+1
if n <= rescheck.total_pages
res = Amazon::Ecs.item_search("search term here", :response_group => 'Large', :item_page =>n, :country => 'uk')
res.items.each do |item|
asin = item.get('ASIN')
title = item.get('ItemAttributes/Title')
brand = item.get('ItemAttributes/Brand')
#etc

Using previous comment, I scrap from DOM of documentation for IN this categories:
[
{
"index":"All",
"node":""
},
{
"index":"Baby",
"node":"1571275031"
},
{
"index":"Beauty",
"node":"1355017031"
},
{
"index":"Books",
"node":"976390031"
},
{
"index":"Automotive",
"node":"4772061031"
},
{
"index":"Apparel",
"node":"1571272031"
},
{
"index":"PCHardware",
"node":"976393031"
},
{
"index":"Electronics",
"node":"976420031"
},
{
"index":"GiftCards",
"node":"3704983031"
},
{
"index":"Grocery",
"node":"2454179031"
},
{
"index":"HealthPersonalCare",
"node":"1350385031"
},
{
"index":"HomeGarden",
"node":"2454176031"
},
{
"index":"Industrial",
"node":"5866079031"
},
{
"index":"Jewelry",
"node":"1951049031"
},
{
"index":"KindleStore",
"node":"1571278031"
},
{
"index":"Luggage",
"node":"2454170031"
},
{
"index":"DVD",
"node":"976417031"
},
{
"index":"Music",
"node":"976446031"
},
{
"index":"MusicalInstruments",
"node":"3677698031"
},
{
"index":"OfficeProducts",
"node":"2454173031"
},
{
"index":"PetSupplies",
"node":"4740420031"
},
{
"index":"Shoes",
"node":"1571284031"
},
{
"index":"Software",
"node":"976452031"
},
{
"index":"SportingGoods",
"node":"1984444031"
},
{
"index":"Toys",
"node":"1350381031"
},
{
"index":"VideoGames",
"node":"976461031"
},
{
"index":"Watches",
"node":"1350388031"
}
]

<?php
namespace MarcL;
use MarcL\CurlHttpRequest;
use MarcL\AmazonUrlBuilder;
use MarcL\Transformers\DataTransformerFactory;
class AmazonAPI
{
private $urlBuilder = NULL;
private $dataTransformer = NULL;
public $item=0;
public $perRequest=0;
public function IND_money_format($money)
{
$len = strlen($money);
$m = '';
$money = strrev($money);
for($i=0;$i<$len;$i++){
if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$len){
$m .=',';
}
$m .=$money[$i];
}
return strrev($m);
}
// Valid names that can be used for search
private $mValidSearchNames = array(
'All',
'Apparel',
'Appliances',
'Automotive',
'Baby',
'Beauty',
'Blended',
'Books',
'Classical',
'DVD',
'Electronics',
'Grocery',
'HealthPersonalCare',
'HomeGarden',
'HomeImprovement',
'Jewelry',
'KindleStore',
'Kitchen',
'Lighting',
'Marketplace',
'MP3Downloads',
'Music',
'MusicTracks',
'MusicalInstruments',
'OfficeProducts',
'OutdoorLiving',
'Outlet',
'PetSupplies',
'PCHardware',
'Shoes',
'Software',
'SoftwareVideoGames',
'SportingGoods',
'Tools',
'Toys',
'VHS',
'Video',
'VideoGames',
'Watches'
);
private $mErrors = array();
public function __construct($urlBuilder, $outputType) {
$this->urlBuilder = $urlBuilder;
$this->dataTransformer = DataTransformerFactory::create($outputType);
}
public function GetValidSearchNames() {
return $this->mValidSearchNames;
}
/**
* Search for items
*
* #param keywords Keywords which we're requesting
* #param searchIndex Name of search index (category) requested. NULL if searching all.
* #param sortBy Category to sort by, only used if searchIndex is not 'All'
* #param condition Condition of item. Valid conditions : Used, Collectible, Refurbished, All
*
* #return mixed SimpleXML object, array of data or false if failure.
*/
public function ItemSearch($keywords,$itemPage, $searchIndex = NULL, $sortBy = NULL, $condition = 'All',$minPrice=50000,$maxPrice=55000) {
?>
<table cellpadding="5">
<thead>
<tr>
<td>Title</td>
<td>List Price</td>
<td>Offer Price</td>
<td>Offer Selling Price</td>
<td>Amount Saved</td>
<td>Brand Name</td>
<td>Size</td>
<td>Color</td>
<td>Manufacturer</td>
</tr>
</thead>
<tbody>
<?php
$totalPages=0;
while($maxPrice<=100000)
{
$finished=false;
$itemPage=0;
while(!$finished)
{
$itemPage=$itemPage+1;
sleep(1);
$mer="MerchantId";
$merVal="Amazon";
$params = array(
'Operation' => 'ItemSearch',
'ResponseGroup' => 'Small,ItemAttributes,Offers,OfferSummary',
'Keywords' => $keywords,
'Condition' => $condition,
'ItemPage' => $itemPage,
'ListPrice' => $itemPage,
'MinimumPrice' => $minPrice,
'MaximumPrice' => $maxPrice,
'SearchIndex' => empty($searchIndex) ? 'All' : $searchIndex,
'Sort' => $sortBy && ($searchIndex != 'All') ? $sortBy : NULL
);
$totalPages=$this->FetchItems($params,$itemPage,$maxPrice,false);
if(($itemPage)==1)
{
$finished=true;
$itemPage=0;
}
}
$minPrice=$maxPrice;
$maxPrice=$maxPrice+5000;
}
//echo "<br/>total Records : ".$this->item;
?>
</tbody>
</table>
<br/><br/>
<?php
$style="";
for($looper=1;$looper<=$totalPages;$looper++)
{
if($looper>($itemPage-3) && $looper<($itemPage+3))
{
if($looper==$itemPage)
{
$style="style='color:red;'";
echo "".$looper." ";
}
else
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}
}else if($looper>($totalPages-3))
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}else if($looper>(($totalPages/2)-3) && $looper<(($totalPages/2)+3))
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}
}
die();
//return $this->MakeAndParseRequest($params,$itemPage);
}
/**
* Lookup items from ASINs
*
* #param asinList Either a single ASIN or an array of ASINs
* #param onlyFromAmazon True if only requesting items from Amazon and not 3rd party vendors
*
* #return mixed SimpleXML object, array of data or false if failure.
*/
public function ItemLookup($asinList,$itemPage, $onlyFromAmazon = false) {
$asinList="B01D0XDW1C";
if (is_array($asinList)) {
$asinList = implode(',', $asinList);
}
$params = array(
'Operation' => 'ItemLookup',
'ResponseGroup' => 'ItemAttributes,Offers,Images',
'ReviewSort' => '-OverallRating',
'ItemId' => $asinList,
'MerchantId' => ($onlyFromAmazon == true) ? 'Amazon' : 'All'
);
return $this->MakeAndParseRequest($params,$itemPage,true);
}
public function GetErrors() {
return $this->mErrors;
}
private function AddError($error) {
array_push($this->mErrors, $error);
}
public function FetchItems($params,$itemPage,$maxPrice,$lookup=false)
{
$signedUrl = $this->urlBuilder->generate($params);
if($lookup)
{
try
{
$request = new CurlHttpRequest();
$response = $request->execute($signedUrl);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $response);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$decodedJson=json_decode($json,true);
//print_r($decodedJson);
print_r($decodedJson);
die();
$parsedXml = simplexml_load_string($response);
if ($parsedXml === false) {
return false;
}
return $this->dataTransformer->execute($parsedXml);
} catch(\Exception $error) {
$this->AddError("Error downloading data : $signedUrl : " . $error->getMessage());
return false;
}
}
else
{
try
{
$request = new CurlHttpRequest();
$response = $request->execute($signedUrl);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $response);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
$decodedJson=json_decode($json,true);
//print_r($decodedJson);
//die();
if(isset($decodedJson['Items']))
{
$this->perRequest=0;
foreach($decodedJson['Items']['Item'] as $itm)
{
if(isset($itm['ItemAttributes']['ListPrice']['FormattedPrice']))
{
$this->item=$this->item+1;
$this->perRequest=$this->perRequest+1;
?>
<tr>
<td>
<?php
if(isset($itm['ItemAttributes']['Title']))
echo $itm['ItemAttributes']['Title'];
else
echo "N/A";
?>
</td>
<td>
<?php
if(isset($itm['ItemAttributes']['ListPrice']['FormattedPrice']))
echo $itm['ItemAttributes']['ListPrice']['FormattedPrice'];
else
echo "N/A";
?>
</td>
<?php
$savedAmount=0;
if(isset($itm['Offers']['Offer']['OfferListing']['Price']['FormattedPrice']))
{
?>
<td><?php echo $itm['Offers']['Offer']['OfferListing']['Price']['FormattedPrice']; ?></td>
<?php
if(isset($itm['Offers']['Offer']['OfferListing']['SalePrice']['FormattedPrice']))
{
$total=(int)($itm['ItemAttributes']['ListPrice']['Amount']);
$offer=(int)($itm['Offers']['Offer']['OfferListing']['SalePrice']['Amount']);
$savedAmount=$total-$offer;
$savedAmount=$savedAmount/100;
$savedAmount=$this->IND_money_format($savedAmount);
$savedAmount="INR ".$savedAmount.".00";
?>
<td><?php echo $itm['Offers']['Offer']['OfferListing']['SalePrice']['FormattedPrice']; ?></td>
<td><?php echo $savedAmount; ?></td>
<?php
}
else
{
$total=(int)($itm['ItemAttributes']['ListPrice']['Amount']);
$offer=(int)($itm['Offers']['Offer']['OfferListing']['Price']['Amount']);
$savedAmount=$total-$offer;
$savedAmount=$savedAmount/100;
$savedAmount=$this->IND_money_format($savedAmount);
$savedAmount="INR ".$savedAmount.".00";
?>
<td><?php echo $itm['Offers']['Offer']['OfferListing']['Price']['FormattedPrice']; ?></td>
<td><?php echo $savedAmount; ?></td>
<?php
}
}
else if(isset($itm['OfferSummary']['LowestNewPrice']['FormattedPrice']))
{
$total=(int)($itm['ListPrice']['Amount']);
$offer=(int)($itm['Offers']['Offer']['OfferListing']['SalePrice']['Amount']);
$savedAmount=$total-$offer;
$savedAmount=$savedAmount/100;
$savedAmount=$this->IND_money_format($savedAmount);
$savedAmount="INR ".$savedAmount.".00";
?>
<td><?php echo $itm['OfferSummary']['LowestNewPrice']['FormattedPrice']; ?></td>
<td><?php echo $itm['OfferSummary']['LowestNewPrice']['FormattedPrice']; ?></td>
<td><?php echo $savedAmount; ?></td>
<?php
}
else
{
?>
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
<?php
}
?>
<td>
<?php
if(isset($itm['ItemAttributes']['Brand']))
echo $itm['ItemAttributes']['Brand'];
else
echo "N/A";
?>
</td>
<td>
<?php
if(isset($itm['ItemAttributes']['Size']))
echo $itm['ItemAttributes']['Size'];
else
echo "N/A";
?>
</td>
<td>
<?php
if(isset($itm['ItemAttributes']['Color']))
echo $itm['ItemAttributes']['Color'];
else
echo "N/A";
?>
</td>
<td>
<?php
if(isset($itm['ItemAttributes']['Manufacturer']))
echo $itm['ItemAttributes']['Manufacturer'];
else
echo "N/A";
?>
</td>
</tr>
<?php
}
}
//return
//echo $maxPrice." : ".$decodedJson['Items']['TotalPages']."<br/>";
}
//echo "PerRequest : ".$this->perRequest."<br/>";
//die();
//$parsedXml = simplexml_load_string($response);
//if ($parsedXml === false) {
// return false;
//}
//return $this->dataTransformer->execute($parsedXml);
} catch(\Exception $error) {
$this->AddError("Error downloading data : $signedUrl : " . $error->getMessage());
return false;
}
}
}
private function MakeAndParseRequest($params,$itemPage,$lookup=false)
{
$this->item=0;
/*$style="";
for($looper=1;$looper<=$totalPages;$looper++)
{
if($looper>($itemPage-3) && $looper<($itemPage+3))
{
if($looper==$itemPage)
{
$style="style='color:red;'";
echo "".$looper." ";
}
else
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}
}else if($looper>($totalPages-3))
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}else if($looper>(($totalPages/2)-3) && $looper<(($totalPages/2)+3))
{
echo "<a href='examples.php?itemPage=".$looper."'>".$looper."</a> ";
}
}
*/
}
}
?>

Related

laravel-filemanager, Sort by time default

I need load files order by "time DESC" when the iframe of laravel-filemanager is called.
Is posible? I read the code and see that we cant order by time DESC and the code dont have options to configure a default "sort_type"
https://github.com/UniSharp/laravel-filemanager
this is not good idea but it's work for me
i am change the code in vendor/unisharp/laravel-filemanager/public/js/script.js
var sort_type = 'alphabetic';
to
var sort_type = 'time';
if you want to sort date in desc order. change the code in
vendor/unisharp/laravel-filemanager/src/Controllers/ItemsController.php
public function getItems()
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$items = array_merge($this->lfm->folders(), $this->lfm->files());
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
with
use Illuminate\Http\Request;
public function getItems(Request $request)
{
$currentPage = self::getCurrentPageFromRequest();
$perPage = $this->helper->getPaginationPerPage();
$files = $this->lfm->files();
if($request->sort_type=='time'){
$files = array_reverse($files);
}
$items = array_merge($this->lfm->folders(), $files);
return [
'items' => array_map(function ($item) {
return $item->fill()->attributes;
}, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
'paginator' => [
'current_page' => $currentPage,
'total' => count($items),
'per_page' => $perPage,
],
'display' => $this->helper->getDisplayMode(),
'working_dir' => $this->lfm->path('working_dir'),
];
}
i'm change the code in vendor/unisharp/laravel-filemanager/src/traits/LfmHelpers.php
and it's worked
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
return strcmp($a->{$key_to_sort}, $b->{$key_to_sort});
});
return $arr_items;
}
with
public function sortFilesAndDirectories($arr_items, $sort_type)
{
if ($sort_type == 'time') {
$key_to_sort = 'updated';
} elseif ($sort_type == 'alphabetic') {
$key_to_sort = 'name';
} else {
$key_to_sort = 'updated';
}
uasort($arr_items, function ($a, $b) use ($key_to_sort) {
if ( $a->$key_to_sort == $a->$key_to_sort )
return 0;
else if ( $a->$key_to_sort > $a->$key_to_sort)
return -1;
else
return 1;
});
return $arr_items;
}
LFM 1.8:
Also, you can use this method, if you don't want to change the LFM Src code.
First use this command to generate views :
php artisan vendor:publish --tag=lfm_view
Find this file:
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
and change the cod according the follow:
#if((sizeof($files) > 0) || (sizeof($directories) > 0))
<div class="row">
<!-- -----------------------------------Begin of added block -->
<?php
$file_temp = [];
if($files != null){
foreach ($files as $key => $value) {
$file_temp[$value['updated']] = $value;
}
krsort($file_temp);
$file_temp1 = [];
$i = 0;
foreach ($file_temp as $key => $value) {
$file_temp1[$i] = $value;
$i+=1;
}
$files = $file_temp1;
}
?>
<!-- ---------------------------------------End of added block -->
#foreach($items as $item)
....
...
As you can see, the <?php ?> code block was added.You can use krsort() or ksort() as you want for descending or ascending.
In 2.3 I did next steps
php artisan vendor:publish --tag=lfm_view
Then you can find file
ROOT/resources/views/vendor/laravel-filemanager/grid-view.blade.php
And after incuding
<script>{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}</script>
I added one line of js
sort_type = 'time';
But files sorts from the oldest to the newest. Thast's why I redefined routes and ItemsController

Outputing only those rows which matches keyword

I'm trying output only those in table rows which matches keyword, but does not work. I am trying use strpos, substr and other functions. My code looks like this. Has someone idea, how to fix it and adapt that function correctly?
<?php
$start_date = strtotime($_POST['start']);
$end_date = strtotime($_POST['end']);
settype($start_date, "integ`enter code here`er");
settype($end_date, "integer");
$total = 0;
if (isset($_POST["start"]) && !empty($_POST["end"])) {
$files = glob('arch/*.log.*');
>scan files
foreach($files as $failas)
{
$file_mod_time = filemtime($failas);
if (($start_date<$file_mod_time) && ($end_date>$file_mod_time)) //looking for specific date
{
$file = #fopen($failas, "r") or die("Cannot open file!\n");
while ($filePart = fread($file, 4146)) {
preg_match_all('/(?>--\w{8}-A--).*?(?=(--\w{8}-A--)|\Z)/s', $filePart, $blockMatch, PREG_SET_ORDER);
foreach ($blockMatch as $singleBlockMatch) {
if (isset($singleBlockMatch[0])) {
preg_match_all('/.*?--\w{8}-A--\n(.*?)\s\w*?\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*?POST (\S*?) HTTP.*?--\w{8}-C--\s(.*?\s)/s', $singleBlockMatch[0], $match, PREG_SET_ORDER); // reads a blocks
/* var_dump($match); */
/* if (strpos($singleBlockMatch[0],$_POST['search'])===($match)) {*/
foreach ($match as $pos) {
$search = $_POST['search'];
$pos = strpos($singleBlockMatch[0], $search); //tries take specific rows, matching keyword
$wert = substr($singleBlockMatch[0],$pos);
} ?>
<tr>
<td><?php echo $total++; ?></td>
<td> <?php echo $wert[1]; ?></td>
<td> <?php echo $wert[2]; ?></td>
<td> <?php echo $wert[3]; ?></td>
<td> <?php echo $wert[4]; ?></td>
<?php
}
}
}
}
}
}
else {
echo "Fill a fields";
}
?>
enter image description here

PHP session name wont show and concatenation

I cant seem to figure out why my name wont show up. It is a session and everything is set right i believe. I must need a second set of eyes. Also, I cant seem to figure out how to concatenate the last part where link 1 is correct. It throws an undefined index error everytime. Anyway code is below and thanks in advance.
<?php
session_start();
//name
if(isset($_SESSION['name'])){
echo "Session Set";
}
else if(!isset($_SESSION['name']) && isset($_COOKIE['name'])){
$_SESSION['name'] = $_COOKIE['name'];
}
else{
$_SESSION['name'] = "Bill";
}
//picUrl
if(isset($_SESSION['picURL'])){
echo "Session Set";
}
else if(!isset($_SESSION['picURL']) && isset($_COOKIE['picURL'])){
$_SESSION['picURL'] = $_COOKIE['picURL'];
}
else{
$_SESSION['picURL'] = "http://www.mugshots.org/misc/bill-gates.jpg";
}
//bgColor
if(isset($_SESSION['bgColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['bgColor']) && isset($_COOKIE['bgColor'])){
$_SESSION['bgColor'] = $_COOKIE['bgColor'];
}
else{
$_SESSION['bgColor'] = "black";
}
//txtColor
if(isset($_SESSION['txtColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['txtColor']) && isset($_COOKIE['txtColor'])){
$_SESSION['txtColor'] = $_COOKIE['txtColor'];
}
else{
$_SESSION['txtColor'] = "green";
}
//hyperColor
if(isset($_SESSION['hyperColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['hyperColor']) && isset($_COOKIE['hyperColor'])){
$_SESSION['hyperColor'] = $_COOKIE['hyperColor'];
}
else{
$_SESSION['hyperColor'] = "yellow";
}
//vHyperColor
if(isset($_SESSION['vHyperColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['vHyperColor']) && isset($_COOKIE['vHyperColor'])){
$_SESSION['vHyperColor'] = $_COOKIE['vHyperColor'];
}
else{
$_SESSION['vHyperColor'] = "red";
}
//aHyperColor
if(isset($_SESSION['aHyperColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['aHyperColor']) && isset($_COOKIE['aHyperColor'])){
$_SESSION['aHyperColor'] = $_COOKIE['aHyperColor'];
}
else{
$_SESSION['aHyperColor'] = "cyan";
}
//link1
if(isset($_SESSION['bgColor'])){
echo "Session Set";
}
else if(!isset($_SESSION['bgColor']) && isset($_COOKIE['bgColor'])){
$_SESSION['bgColor'] = $_COOKIE['bgColor'];
}
else{
$_SESSION['link1'] = "http://en.wikipedia.org/wiki/Bill_Gates";
}
//link2
if(isset($_SESSION['link2'])){
echo "Session Set";
}
else if(!isset($_SESSION['link2']) && isset($_COOKIE['link2'])){
$_SESSION['link2'] = $_COOKIE['link2'];
}
else{
$_SESSION['link2'] = "http://www.usdoj.gov/atr/cases/ms_index.htm";
}
//link3
if(isset($_SESSION['link3'])){
echo "Session Set";
}
else if(!isset($_SESSION['link3']) && isset($_COOKIE['link3'])){
$_SESSION['link3'] = $_COOKIE['link3'];
}
else{
$_SESSION['link3'] = "http://www.microsoft.com";
}
//link1Name
if(isset($_SESSION['link1Name'])){
echo "Session Set";
}
else if(!isset($_SESSION['link1Name']) && isset($_COOKIE['link1Name'])){
$_SESSION['link1Name'] = $_COOKIE['link1Name'];
}
else{
$_SESSION['link1Name'] = "Bill Gates Net Worth Page";
}
//link2Name
if(isset($_SESSION['link2Name'])){
echo "Session Set";
}
else if(!isset($_SESSION['link2Name']) && isset($_COOKIE['link2Name'])){
$_SESSION['link2Name'] = $_COOKIE['link2Name'];
}
else{
$_SESSION['link2Name'] = "United States v. Microsoft";
}
//link3Name
if(isset($_SESSION['link3Name'])){
echo "Session Set";
}
else if(!isset($_SESSION['link3Name']) && isset($_COOKIE['link3Name'])){
$_SESSION['link3Name'] = $_COOKIE['link3Name'];
}
else{
$_SESSION['link3Name'] = "Microsoft Home Page";
}
?>
<html>
<head>
<title>A05_SessionColors</title>
</head>
<body bgcolor="<?php echo $_SESSION['bgColor']?>"
text="<?php echo $_SESSION['txtColor']?>"
link="<?php echo $_SESSION['hyperColor']?>"
vlink="<?php echo $_SESSION['vHyperColor']?>"
alink="<?php echo $_SESSION['aHyperColor']?>">
<center>
<h1><?php echo $_SESSION['name'] ?>'s Home Page</h1>
<p><img border="0" src=<?php echo '"'.$_SESSION['picURL'].'"'?>/></p>
<h2>My Three Favorite Links</h2>
<ul>
<li>
<p style="line-height: 150%"><a href=<?php echo '"'.$_SESSION['link1'].'"'?>/><?php echo $_SESSION['link1Name']?></a></li>
<li>
<p style="line-height: 150%"><a href=<?php echo '"'.$_SESSION['link2'].'"'?>/><?php echo $_SESSION['link2Name']?></a></li>
<li>
<p style="line-height: 150%"><a href=<?php echo '"'.$_SESSION['link3'].'"'?>/><?php echo $_SESSION['link3Name']?></a> </li>
</ul>
</center>
<h3 align="center">Click HERE to change display options.</h3>
<p> </p>
</body>
</html>
In your repetitive code you missed some array keys. I suggest rewriting it like this:
<?php
session_start();
$default_values = array(
'name' => 'Bill',
'picURL' => "http://www.mugshots.org/misc/bill-gates.jpg",
'bgColor' => "black",
...
);
foreach ($default_values as $key => $value) {
if(!isset($_SESSION[$key]) && isset($_COOKIE[$key])){
$_SESSION[$key] = $_COOKIE[$key];
}
else{
$_SESSION[$key] = $value;
}
}
?>
<html>
...
By the way, it seems a little odd that you're setting session values to cookie values, when both are persisted with the current visitor.

Issue In joomla custom dropdown list development

For the past 3 days, I've been stuck on a dropdown list development using joomla 2.5, I have to retrieve data from database and show this data in a drop down the steps I followed are mentioned below:
Inside the models folder I have created a new model inside fields folder and name this file "fieldname.php"
Now the file "Models/fields/fieldname.php" contains following source code:
<?php
defined('JPATH_BASE') or die;
jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
class JFormFieldMyCompany extends JFormFieldList
{
protected $type = 'MyCompany';
public function getOptions()
{
// Initialize variables.
$options = array();
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id As value,name As text');
$query->from('#_k2_tags AS a');
$query->order('a.name');
$db = $this->getDbo();
// Get the options.
$db->setQuery($query);
$options = $db->loadObjectList();
// Check for a database error.
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
}
print_r($options);exit;
return $options;
}
}
after that inside my model filter.php I added the following code.
Models/filter.php:
<?php
defined( '_JEXEC' ) or die;
jimport('joomla.application.component.modeladmin');
class FiltersModelFilter extends JModelAdmin
{
//Add this handy array with database fields to search in
protected $searchInFields = array('text','a.name');
//Override construct to allow filtering and ordering on our fields
public function __construct($config = array()) {
$config['filter_fields']=array_merge($this->searchInFields,array('a.name'));
parent::__construct($config);
}
public function getTable($type = 'Filter', $prefix = 'FiltersTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
protected function loadFormData()
{
$data = JFactory::getApplication()->getUserState('com_filters.edit.filter.data', array());
if (empty($data)) {
$data = $this->getItem();
}
return $data;
}
public function getForm($data = array(), $loadData = true)
{
$form = $this->loadForm('com_filters.filter', 'filter', array('control' => 'jform', 'load_data' => $loadData));
return $form;
}
protected function getListQuery(){
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//CHANGE THIS QUERY AS YOU NEED...
$query->select('id As value, name As text')
->from('#_k2_tags AS a');
// Filter search // Extra: Search more than one fields and for multiple words
$regex = str_replace(' ', '|', $this->getState('filter.search'));
if (!empty($regex)) {
$regex=' REGEXP '.$db->quote($regex);
$query->where('('.implode($regex.' OR ',$this->searchInFields).$regex.')');
}
// Filter company
$company= $db->escape($this->getState('filter.name'));
if (!empty($company)) {
$query->where('(a.name='.$company.')');
}
// Filter by state (published, trashed, etc.)
$state = $db->escape($this->getState('filter.state'));
if (is_numeric($state)) {
$query->where('a.published = ' . (int) $state);
}
elseif ($state === '') {
$query->where('(a.published = 0 OR a.published = 1)');
}
//echo $db->replacePrefix( (string) $query );//debug
return $query;
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* #since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('administrator');
// Load the filter state.
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
//Omit double (white-)spaces and set state
$this->setState('filter.search', preg_replace('/\s+/',' ', $search));
//Filter (dropdown) state
$state = $this->getUserStateFromRequest($this->context.'.filter.published', 'filter_state', '', 'string');
$this->setState('filter.state', $state);
//Filter (dropdown) company
$state = $this->getUserStateFromRequest($this->context.'.filter.name', 'filter_company', '', 'string');
$this->setState('filter.name', $state);
//Takes care of states: list. limit / start / ordering / direction
parent::populateState('a.name', 'asc');
}
}
Inside the "Views/filter/view.html.php"
<?php
defined( '_JEXEC' ) or die;
jimport( 'joomla.application.component.view');
class FiltersViewFilter extends JView
{
protected $item;
protected $form;
protected $state;
protected $sortColumn;
protected $sortDirection;
protected $searchterms;
public function display($tpl = null)
{
$this->item = $this->get('Item');
$this->state = $this->get('State');
$this->form = $this->get('Form');
$this->state= $this->get('State');
//Following variables used more than once
$this->sortColumn = $this->state->get('list.ordering');
$this->sortDirection= $this->state->get('list.direction');
$this->searchterms= $this->state->get('filter.search');
$this->addToolbar();
parent::display($tpl);
}
public function addToolbar()
{
if ($this->item->ID) {
JToolBarHelper::title(JText::_('Filter Title'));
} else {
JToolBarHelper::title(JText::_('Add Filter Title'));
}
JToolBarHelper::apply('filter.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('filter.save', 'JTOOLBAR_SAVE');
JToolBarHelper::save2new('filter.save2new', 'JTOOLBAR_SAVE_AND_NEW');
JToolBarHelper::cancel('filter.cancel');
}
}
inside the views/filter/tmpl/default.php
<?php defined( '_JEXEC' ) or die;
//Get companie options
JFormHelper::addFieldPath(JPATH_COMPONENT . '/models/fields');
$companies = JFormHelper::loadFieldType('MyCompany', false);
$companyOptions=$companies->getOptions(); // works only if you set your field getOptions on public!!
//Get companie options
?>
<form action="index.php?option=com_filters&ID=<?php echo $this->item->ID ?>"
method="post" name="adminForm" class="form-validate">
<fieldset id="filter-bar">
<div class="filter-search fltlft">
<input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->searchterms); ?>" title="<?php echo JText::_('Search in Names, etc.'); ?>" />
<button type="submit">
<?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?>
</button>
<button type="button" onclick="document.id('filter_search').value='';this.form.submit();">
<?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?>
</button>
</div>
<div class="filter-select fltrt">
<select name="filter_state" class="inputbox" onchange="this.form.submit()">
<option value="">
<?php echo JText::_('JOPTION_SELECT_PUBLISHED');?>
</option>
<?php echo JHtml::_('select.options', JHtml::_('jgrid.publishedOptions', array('archived'=>false)), 'value', 'text', $this->state->get('filter.published'), true);?>
</select>
<select name="filter_type" class="inputbox" onchange="this.form.submit()">
<option value=""> - Select Company - </option>
<?php echo JHtml::_('select.options', $companyOptions, 'value', 'text', $this->state->get('filter.name'));?>
</select>
</div>
</fieldset>
<div class="width-60 fltlft">
<fieldset class="adminform">
<ul class="adminformlist">
<?php foreach ($this->form->getFieldset() as $field): ?>
<li><?php echo $field->label; ?>
<?php echo $field->input; ?></li>
<?php endforeach ?>
</ul>
</fieldset>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
Please help me in identification of my error I need to sort out issue as soon as possible.
change this Models/fields/fieldname.php to Models/fields/mycompany.php
also change from JFormFieldMyCompany to JFormFieldMycompany
and protected $type = 'MyCompany'; to protected $type = 'mycompany';

Facebook OAuth no longer functioning

I had a script that was working perfectly up until a couple of hours ago. This script authorizes a user, checks to see if the user is logged in, and inserts data into my database.
As of now, it fails to both identify a user or insert any data. Any help will be appreciated.
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:200px;
height:198px;
z-index:1;
left: 757px;
top: 18px;
}
-->
</style>
<div id="apDiv1"><img src="../Downloads/tree06_small.png" width="188" height="250" alt="" /></div>
<?php
require ("santatree/facebook.php");
include('login.php');
$facebook = new Facebook(array(
'appId' => 'id',
'secret' => 'secret',
));
$db_select=mysql_select_db($db_database);
if (!$db_select)
{
die ("Impossible Function". mysql_error());
}
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
if ($user) {
$token = $facebook->getAccessToken();
$friends = $facebook->api('/me/friends');
$friendsData = $friends['data'];
$User = $user['data'];
for ($i = 0; $i < sizeof($friendsData); $i++)
{
$friend = $friendsData[$i];
echo $friend['name'] . ", ";
echo $friend['id'];
echo $user['id'];
$sq1 = "INSERT into tbl_Friends (Name, FriendID, Access_ID) VALUES ('".$friend['name']."', '" .$friend['id']."', '".$user_profile['id']."')";
error_log($e);
$user = null;
}
}
mysql_query($sq1);
}
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $_SESSION['fb_276853929000834_access_token'];
if (!$access_token) {
echo '<script>';
echo 'top.location.href = "'.$loginUrl.'";';
echo '</script>';
} else {
// ------ Create Drop Down Name List from Friends Table ------
$myuserid = $user_profile['id'];
echo "<html>";
echo "<form enctype='multipart/form-data' method='post' action='uploadpicture1.php' name='Giftgiver'>";
$result= #mysql_query("select Friend_ID, tbl_Friends.Name from tbl_Friends inner join tbl_Users on tbl_Friends.Access_ID=tbl_Users.Access_ID where tbl_Friends.Access_ID = $myuserid");
print "<p> Select a Friend: \n";
print "<Select name=\"Friend_ID\">\n";
while ($row=mysql_fetch_assoc($result)){
$Friend_ID=$row['Friend_ID'];
$Name =$row['Name'];
print "<option value=$Friend_ID>$Name \n";
}
print "</select>\n";
print "</p>\n";
echo "Choose a gift!";
echo "<input type='file' name='GiftChoice' value='1'>";
}
echo "</form>";
echo "</html>";
?>
Have you checked to make you you have updated to Facebook's oAuth 2.0?
All FB apps and apps using the FB api are required to upgrade to oAuth 2.0 by October 1st, 2011.