forked from Muskie/MashupCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mCollection.php
730 lines (587 loc) · 29.3 KB
/
mCollection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
<?php
/**
* Class to facilitate the creation of web mashups using various APIs.
* @author Muskie McKay <andrew@muschamp.ca>
* @link http://www.muschamp.ca
* @version 1.6.1
* @copyright Muskie McKay
* @license MIT
*
* This started as a simple class to represent a collection of music,
* a physical collection or virtual that then can be easily manipulated just like a crate of LPs.
* However due to unending unemployment I decided to make an even more versatile class to represent a collection of
* anything you might want to make a mashup of: music, movies, quotations etc.
*
* There are subclasses musicCollection.php, albumCollection.php, dvdCollection.php, movieCollection.php , and
* quotationCollection.php that should do the heavy lifting as I try to get PHP to be even more OOP. Instructions and examples
* are found:
* http://www.muschamp.ca/Muskie/webMashups.html
*
*/
/**
The MIT License
Copyright (c) 2010 Andrew "Muskie" McKay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*/
require_once('AmazonAPI/amazon_api_class.php'); // Amazon API by Sameer Borate, extended by yours truely
require_once('phpflickr/phpFlickr.php');
require_once('myInfo.php'); // This is where all your API keys and user names and what not go as constants, should be .inc?
require_once('muskLib.php'); // A few little helper functions I wrote or acquired online
require_once('caching.php'); // This is my DIY caching of XML and other data returned from APIs
require_once('facebookLib.php'); // This only slightly makes my life easier, the author had big plans so I included support...
require_once('BestBuy/Service/Remix.php'); // I prefer Amazon, BestBuy integration is not very useful, use Amazon
require_once ('codebird.php'); // This helps with Oauth for Twitter
class mCollection
{
/**
* This will be a multi-dimensional array originally consisting of arrays containing an artist in the first cell
* and an album title in the second cell. That is the simplest way to represent the collection of albums.
* @access protected
* @var array
*/
protected $theCollection = array();
/**
* This is a simple index of which member from theCollection array is being displayed or otherwise manipulated.
* This is often useful information to have, but it will also let me use the array as a circular linked list
* Which will open up some interesting options graphically.
* @access protected
* @var int
*/
protected $currentMemberIndex = 0;
/**
* This is an instance of tha Amazon API we need it to fetch data
* @access protected
* @var AmazazonAPI Object
*/
protected $amazonAPI;
/**
* This is an instance of facebookLib an extension to the official facebook open graph class
* @access protected
* @var Facebook object
*/
protected $facebook;
/**
* This is an instance of the official Facebook access token, you need this to make some requests
* @access private
* @var Facebook object
*/
private $facebookAccessToken;
const TWEETS_PER_PAGE = 5;
/**
* This is an instance of tha phpFlickr API we need it to fetch data
* @access protected
* @var phpFlickr Object
*/
protected $flickrAPI;
/**
* This is an instance of the BestBuy Remix API wrapper class. It is similar to the Amazon API but less popular and less well documented.
* @access protected
* @var Best Buy Remix API Object
*/
protected $bestBuyRemix;
/**
* This is an instance of CodeBird a wrapper class for Twitter.
* @access protected
* @var Best Buy Remix API Object
*/
protected $codeBird;
// PHP doesn't support multiple constructors so like everything they have a work around or two...
public function __construct($input)
{
if (is_array($input))
{
// Initialize the collection array with input.
// This seems the most obvious way to initialize the class so I need to create the array I want outside the class.
$this->theCollection = $input;
}
else if ($input instanceof SimpleXMLElement) {
// Initialize the collection array by parsing the XML.
// Not implemented yet but a decent idea to support eventually
}
else if(is_string($input))
{
// Initialize collection array by reading from CSV file
$this->theCollection = createArrayFromCSVFile($input);
}
else
{
throw new Exception('Wrong input type, passed to mCollection constructor.');
}
if(! $this->hasMembers())
{
//The collection should not be empty after the constructor is called...
throw new Exception('The Collection should not be empty after calling the constructor. Please check when and how you create an mCollection object');
}
else
{
// Finish setting up the mCollection object
$this->initializeAPIs();
}
}
// This initializes the APIs this object/class uses to do stuff
protected function initializeAPIs()
{
$this->amazonAPI = new AmazonProductAPI();
$this->bestBuyRemix = new BestBuy_Service_Remix(myInfo::MY_BESTBUY_PUBLIC_KEY); //New API which may become more useful
$this->facebook = new facebookLib(array(
'appId' => myInfo::MY_FACEBOOK_PUBLIC_KEY,
'secret' => myInfo::MY_FACEBOOK_PRIVATE_KEY,
'cookie' => true
));
facebookLib::$CURL_OPTS[CURLOPT_CAINFO] = './ca-bundle.crt';
facebookLib::$CURL_OPTS[CURLOPT_FRESH_CONNECT] = 1;
facebookLib::$CURL_OPTS[CURLOPT_PORT] = 443;
$this->facebookAccessToken = $this->facebook->getAccessToken();
$this->flickrAPI = new phpFlickr(myInfo::MY_FLICKR_PUBLIC_KEY, myInfo::MY_FLICKR_PRIVATE_KEY);
$this->flickrAPI->enableCache("fs", "./" . myInfo::CACHING_DIRECTORY . "/Flickr"); // This class came with it's own caching system, now I'm using at least three. Last.fm PHP API has one too but it requires a database.
// Twitter's API now requires Oauth, GData wants you to use this too, but currently it is still possible to search Google (YouTube) without Oauth
Codebird::setConsumerKey(myInfo::MY_TWITTER_PUBLIC_KEY, myInfo::MY_TWITTER_PRIVATE_KEY);
$this->codeBird = Codebird::getInstance();
$this->codeBird->setToken(myInfo::MY_TWITTER_ACCESS_TOKEN, myInfo::MY_TWITTER_ACCESS_TOKEN_SECRET);
}
// This should probably be private, but it is mainly for debugging my constructor, constructors shouldn't be this problematic...
protected function dumpArrayContents()
{
if( ! empty($this->theCollection))
{
print_r('These are the contents of theCollection array currently:');
print('<br />');
print('<pre>');
print_r($this->theCollection);
print('</pre>');
}
else
{
// Will this ever happen now that I got my constructor and private variable accessing correct, shouldn't!
print_r('There is nothing in the albums array right now.' . '<br />');
}
}
/**
* Returns true if we have some members in the collection
*
* @return boolean
*/
public function hasMembers()
{
return ( ! empty($this->theCollection));
}
protected function isCurrentMemberTheLast()
{
$isCurrentMemberTheLast = false;
if ( $this->currentMemberIndex == ($this->collectionSize() - 1))
{
$isCurrentMemberTheLast = true;
}
return $isCurrentMemberTheLast;
}
protected function isCurrentMemberTheFirst()
{
$isCurrentMemberTheFirst = false;
if ( $this->currentMemberIndex == 0)
{
$isCurrentMemberTheFirst = true;
}
return $isCurrentMemberTheFirst;
}
/**
* Returns the number of members in our collection
*
* @return int
*/
public function collectionSize()
{
return count($this->theCollection);
}
/**
* Returns the current member in array form based on currentMemberIndex
*
* @return array
*/
public function currentMemberAsArray()
{
return $this->theCollection[$this->currentMemberIndex];
}
/**
* Sets $currentMemberIndex to be a random number.
* I return the information as an array but with minimal information contained currently.
* Once it is the the current member you can fetch lots of info.
*
* @return array
*/
public function randomMember()
{
$oldIndex = $this->currentMemberIndex;
if ($this->collectionSize() < 3)
{
throw new Exception("This collection is less than three, why are you wasting time calling randomMember on a collection this small?");
}
else
{
$newIndex = rand(0, ($this->collectionSize() - 1));
while($newIndex == $oldIndex)
{
// I want it random, but I don't want it to ever return the same member
$newIndex = rand(0, ($this->collectionSize() - 1));
}
$this->currentMemberIndex = $newIndex;
}
return $this->currentMemberAsArray();
}
/**
* This method was created primarily for debugging. This method sets the currentMemberIndex to be the last item in the collection and
* then returns the now currentMemberAsArray.
*
* @return array
*/
public function lastMember()
{
$newIndex = $this->collectionSize() - 1;
$this->currentMemberIndex = $newIndex;
return $this->currentMemberAsArray();
}
/**
* Finally decided to add accessors for the array index, this method lets you set the currentMemberIndex
*
*/
public function setCurrentMemberIndex($newIndex)
{
if( ($newIndex >= 0) && ($newIndex <= ($this->collectionSize() - 1)))
{
$this->currentMemberIndex = $newIndex;
}
else
{
throw new Exception("New Index is not valid");
}
}
/**
* Finally decided to add accessor to array index, this method lets you get the value of the currentMemberIndex
*
*/
public function getCurrentMemberIndex()
{
return $this->currentMemberIndex;
}
/**
* This method uses Facebook's Open Graph format to search for a page or more likely pages
* corresponding to the string passed in, in Facebook's social graph.
* The most likely URL is chosen and then we creat the HTML tag(s) necessary to display a fully functional like button
*
* @return string
*/
public function facebookLikeButtonFor($somethingILike)
{
// Needs to produce HTML that looks like this:
/*
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fexample.com%2Fpage%2Fto%2Flike&layout=button_count&show_faces=true&width=200&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:21px;" allowTransparency="true"></iframe>
*/
$htmlTag = null;
$this->facebook->setDecodeJson(true);
$possiblePages = $this->facebook->search('page', $somethingILike);
if( ! empty($possiblePages->data))
{
$firstID = $possiblePages->data[0]->id;
$graphURL = Facebook::$DOMAIN_MAP['graph'] . $firstID;
$resultingString = fetchThisURL($graphURL);
if(is_string($resultingString))
{
$facebookPage = json_decode($resultingString);
$strippedURL = urlencode($facebookPage->link);
$openLinkTag = '<iframe src="http://www.facebook.com/plugins/like.php?href=';
$closeLinkTag = '%2F&layout=button_count&show_faces=true&width=200&action=like&colorscheme=light&height=32" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:32px;" allowTransparency="true"></iframe>';
$htmlTag = $openLinkTag . $strippedURL . $closeLinkTag;
}
else
{
// We're not getting a string in JSON format
print('<pre>');
print_r($resultingString); // nor is this...
print('</pre>');
}
}
return $htmlTag;
}
/**
* Searches Twitter for mentions of the string passed in, now uses CodeBird and Twitter API version 1.1
* Twitter Display Requirements are not optional so I recommend not calling this method and instead call
* displayRecentTweetsFor($searchString) Towards that end I made this protected.
*
* @param search string
*
* @return Object
*/
protected function searchTwitterFor($searchString)
{
$searchResults;
// To improve search results call this method with a string of keywords like this "keyword one two three"
$encodedQuery = urlencode( $searchString );
$params = array(
'q' => $encodedQuery,
'count' => mCollection::TWEETS_PER_PAGE,
'lang' => 'en',
'result_type' => 'recent'
);
// Should this be search_tweets instead of just search? YES! Do my arguments have to be in an array? Not necessarily...
$searchResults = $this->codeBird->search_tweets($params);
return $searchResults;
}
/**
* Searches the Twitter API for recent tweets about the passed in search string. More importantly formats the resulting tweets
* in order to meet the display requirements with valid HTML. Still need to include CSS rules in client code. This solution is based on:
* http://oikos.org.uk/2013/02/tech-notes-displaying-twitter-statuses-using-api-v1-1-and-oath/
*
* You also need to possibly includ the Twitter javascript call somewhere to use this method and resulting HTML code. Read the Twitter
* documentation: https://dev.twitter.com/terms/display-requirements
*
* @param search string
*
* @return null
*/
public function displayRecentTweetsFor( $searchString )
{
// Another method handles the searching but displaying the results just the way Twitter wants is work, hence this method
$tweets = $this->searchTwitterFor( $searchString );
// Now I have to loop through the results and display them as per the standard.
if (count($tweets->statuses) > 0)
{
print('<div class="tweets">');
foreach ($tweets->statuses as $this_tweet)
{
// Following Ross's example I'm close to meeting the display requirements. Timestamp may be incorrectly formatted.
// Do I need little logos for Reply, Retweet, and Favourite?
// https://dev.twitter.com/terms/display-requirements
print('<div class="tweet-container">');
print('<a class="tweet-user-avatar" href="https://twitter.com/intent/user?user_id=' . $this_tweet->user->id_str . '">');
print('<img width="32" height="32" src="' . $this_tweet->user->profile_image_url . '" /></a>');
print('<p class="tweet-user-names">');
print('<a class="tweet-display-name" href="https://twitter.com/intent/user?user_id=' . $this_tweet->user->id_str . '">');
print($this_tweet->user->name . '</a>');
print('<a class="tweet-account-name" href="https://twitter.com/intent/user?user_id=' . $this_tweet->user->id_str . '">');
print('@' . $this_tweet->user->screen_name . '</a></p>');
print('<a href="https://twitter.com/' . $this_tweet->user->screen_name . '" class="twitter-follow-button" data-show-count="false" data-dnt="true">Follow @' . $this_tweet->user->name . '</a>');
print('<div class="tweet-text">');
print(linkify_tweet( $this_tweet->text, $this_tweet ));
print('</div>');
print('<div class="tweet-time">');
print('<a href="http://twitter.com/' . $this_tweet->user->screen_name . '/status/' . $this_tweet->id_str . '">');
print(relativeTime( strtotime( $this_tweet->created_at))); // Couldn't I just print the time string?
print('</a></div>');
print('<div class="tweet-intents">');
// Web Intents aren't working perfectly or at least I have no little images. Could switch to UL LI and unique bullet
// Complete with fancy CSS roll over Eric Meyer style.
// Extra attributes in tag remove:
/*
class="intent-reply" title="Reply to this Tweet"
class="intent-retweet" title="Retweet this Tweet"
class="intent-favorite" title="Favourite this Tweet"
*/
print('<a href="https://twitter.com/intent/tweet?in_reply_to=' . $this_tweet->id_str . '">Reply</a>');
print('<a href="https://twitter.com/intent/retweet?tweet_id=' . $this_tweet->id_str . '">Retweet</a>');
print('<a href="https://twitter.com/intent/favorite?tweet_id=' . $this_tweet->id_str . '">Favourite</a>');
print('</div></div>');
}
print('</div>');
}
// Don't need to return anything not even null in PHP apparently, I really am not a PHP guy, I don't know best practices at all.
}
/**
* This method creates a fully functional "Tweet This" button. You don't need to register an app at Twitter to just do this.
* It uses Twitter's Javascript but it passes in text and variables concerning the current member and pulls information from
* myInfo.php specifically MY_TWITTER_ACCOUNT and MY_HOME_PAGE
*
* @return string
*/
public function tweetThisButton($tweet = myInfo::DEFAULT_TWEET)
{
// This method needs to produce HTML that looks like this:
/*
<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.test.com" data-text="test title" data-count="none" data-via="MuskieMcKay">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
*/
// Maybe it should look like this, I switch to this second format for quotations...
/*
<a href="https://twitter.com/share" class="twitter-share-button" data-via="MuskieMcKay">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
*/
$tweetThisButtonCode = null;
$twitterDataURL = myInfo::MY_HOME_PAGE;
// Just in case I started stripping HTML from passed in Tweets...
$twitterDataBy = myInfo::MY_TWITTER_ACCOUNT;
$openingTag = '<a href="http://twitter.com/share" class="twitter-share-button" data-url="' . $twitterDataURL . '" data-text="' . strip_tags($tweet) . '" data-via="' . $twitterDataBy . '">';
$closingTag = '</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
$tweetThisButtonCode = $openingTag . "Tweet" . $closingTag;
return $tweetThisButtonCode;
}
/**
* This method produces a working Pin It button. It requires three arguments none of which should be empty or null. It also requires similar to
* the latest greatest Facebook button that a second bit of Javascript be placed just inside the body tag, failure to do that will result in a
* non-funtioning Pin It button. I like how in the past I could have one method per button, but if you want to play with Pinterest you have
* to play by their rules, so include this:
*
* <script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
*
* More information can be found here:
* https://support.pinterest.com/entries/21101982-adding-the-pin-it-button-to-your-website
*
* @param string
* @param string
* @param string
* @return string
*/
public function pinItButton($pageURL, $imageURL, $text)
{
$html = '<!-- Pin It Button Not Possible -->';
// Should probably assert that no data passed in is empty, checking valid URLs would be even better...
/*
Pinterest requires two bits of code, something like this:
<a href="http://pinterest.com/pin/create/button/?url=http%3A%2F%2Fwww.muschamp.ca%2F&media=http%3A%2F%2Fwww.muschamp.ca%2Fimage.jpg&description=whatever" class="pin-it-button" count-layout="horizontal"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>
Where you want the button ie here, and
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
elsewhere near where <head> meets <body>
*/
// Not sure if the first two tests are necessary, they were necessary in my news aggregator, so I'm leaving them in for now...
if(( ! strpos($imageURL, '+')) && ( ! strpos($imageURL, '%'))
&& (preg_match('|^http?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $imageURL)) && (preg_match('|^http?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $pageURL)))
{
// If I don't display a valid image, no sense in showing a Pin It button
// I now think I should urlencode() the three PHP varialbes...
$html = '<a href="http://pinterest.com/pin/create/button/?url=' . urlencode($pageURL) . '&media=' . urlencode($imageURL) . '&description=' . urlencode(strip_tags($text)) . '" class="pin-it-button" count-layout="horizontal" target="_blank"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
}
return $html;
}
/**
* This method returns a valid product URL with the Associate referral for the passed in ASIN
*
* @param string product ASIN
* @return string URL
*/
public function amazonProductURLFor($productASIN)
{
$amazonProductURL = 'https://www.amazon.com/dp/' . $productASIN . '?tag=' . myInfo::MY_AMAZON_ASSOCIATE_ID;
return $amazonProductURL;
}
/**
* This method returns the Klout score for the past in Twitter account.
*
* @param string
* @return numberic score
*/
public function kloutScoreFor($twitterAccount)
{
if(strlen($twitterAccount) > 0)
{
// This is based on the documentation here:
// http://developer.klout.com/docs/read/api/API
$q = urlencode($twitterAccount);
$query = 'http://api.klout.com/1/klout.xml?key=' . myInfo::MY_KLOUT_KEY . '&users=' . $q;
$returnedXML = simplexml_load_file($query); // Simple but with less error checking perhaps
}
return $returnedXML->user->kscore;
}
/**
* This method searches Topsy to find the biggest expert on the social web for the passed in subject.
*
* @param string subject
* @return string the experts Twitter account
*/
public function topsyExpertOn($subject)
{
$expert = NULL;
// First we need to encode the passed in string
$q = urlencode($subject);
// Need to create a URL as per instructions http://code.google.com/p/otterapi/wiki/Resources#/experts
// Now need to attach an API key, which is only free for 30 days, otherwise you get NULL back for the expert.
$query = 'http://otter.topsy.com/experts.json?q=' . $q . '&apikey=' . myInfo::MY_TOPSY_KEY;
$lookUpResult = fetchThisURL($query);
// decode the json data to make it easier to parse the php
$searchResults = json_decode($lookUpResult);
$expert = $searchResults->response->list[0]->nick;
return $expert;
}
/**
* This method returns a valid link to the Twitter account passed in.
*
* @param string Twitter Account
* @return string link to the experts Twitter account
*/
public function linkToTwitterAccountFor($id)
{
// Check for '@'
$validID = str_replace('@', '', $id);
return '<a href="http://twitter.com/#!/' . $validID . '">' . $id . '</a>';
}
/**
* This method searches YouTube and potentially eventually other video services for a video clip featurning the passed in subject. Then
* it returns the HTML for an embeddable player to play that video.
*
* @param string
*
* @return string
*/
public function embeddableVideoClipFor($searchString)
{
// Previous experience revealed that video search is not perfect, in that for given keywords the top result isn't always accurate.
$embeddableVideoClipHTML = NULL;
// Further details on searching YouTube http://www.ibm.com/developerworks/xml/library/x-youtubeapi/
// This was working well for over two years but had to be revised to use version 2 of the API
// May switch to Zend or version 3.0 of Google/YouTube API but this is working again... I even asked Stack Overflow for advice
// http://stackoverflow.com/questions/14915298/searching-youtube-and-displaying-first-video-in-php-advice-needed
$vq = $searchString;
$vq = preg_replace('/[[:space:]]+/', ' ', trim($vq));
$vq = urlencode($vq);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos?q=' . $vq . '&safeSearch=moderate&orderby=relevance&v=2'; // Added version 2 argument
// read feed into SimpleXML object
try
{
$youTubeXML = simplexml_load_file($feedURL);
}
catch(Exception $e)
{
// This rarely throws an error, but when it does, I just want to pretend I can't find a video clip
$youTubeXML = NULL;
}
if(($youTubeXML != NULL) && ( ! empty($youTubeXML->entry->link[0]['href'])))
{
$videoLink = $youTubeXML->entry->link[0]['href']; // This is not enough, I need to trim the beginning and end off this to just get the video code
$trimedURL = str_replace('http://www.youtube.com/watch?v=', '' , $videoLink);
$videoCode = str_replace('&feature=youtube_gdata', '', $trimedURL);
// Google wants a totally new way of displaying videos, which I think I need for the Google+ button to work.
// Was Using:
//$embeddableVideoClipHTML = '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube.com/embed/' . $videoCode . '"frameborder="0" allowfullscreen>';
// Now follow this: https://developers.google.com/youtube/js_api_reference#Embedding
$embeddableVideoClipHTML .= '<object width="640" height="360">';
$embeddableVideoClipHTML .= '<param name="movie" value="https://www.youtube.com/v/' . $videoCode .'?version=3"></param>';
$embeddableVideoClipHTML .= '<param name="allowFullScreen" value="true"></param>';
$embeddableVideoClipHTML .= '<param name="allowScriptAccess" value="always"></param>';
$embeddableVideoClipHTML .= '<embed src="https://www.youtube.com/v/' . $videoCode . '?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="640" height="360"></embed>';
$embeddableVideoClipHTML .= '</object>';
}
return $embeddableVideoClipHTML;
}
/**
* This method searches the Wikipedia for the passed in string. Not sure what format I'll return probably SimpleXML object.
*
* @param string the search query
* @return the number one result for the search in Wikipedia
*/
public function searchWikipediaFor($searchString)
{
// My Wikipedia search code is based on this example: http://adamzwakk.com/?p=383
$searchResults = fetchThisURL('http://en.wikipedia.org/w/api.php?action=opensearch&search=' . urlencode($searchString) . '&format=xml&limit=1');
$wikiXML = simplexml_load_string($searchResults);
return $wikiXML;
}
}
?>