Advertisement
Guest User

Instapress - How to Show Image's Hashtag

a guest
Jun 21st, 2012
1,316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 33.46 KB | None | 0 0
  1. <?php
  2.     /*
  3.     Plugin Name: Instapress
  4.     Plugin URI: http://instapress.it
  5.     Description: <b>Highly customizable</b> plugin to display a feed of pictures uploaded via <a href="http://instagr.am" target="_blank">Instagram</a>. Display a users media, your own media or the popular media feed. Choose whether to integrate the Instagrams as a widget or directly in your posts.
  6.     Version: 1.5.3
  7.     Author: Thomas Krammer
  8.     Author URI: http://liechtenecker.at/unternehmen/
  9.     License: GPL2
  10.     */
  11.  
  12.     define('INSTAPRESS_VERSION', '1.5.3');
  13.  
  14.     /*  Copyright 2011 Thomas Krammer  (email : t.krammer@liechtenecker.at)
  15.  
  16.         This program is free software; you can redistribute it and/or modify
  17.         it under the terms of the GNU General Public License, version 2, as
  18.         published by the Free Software Foundation.
  19.    
  20.         This program is distributed in the hope that it will be useful,
  21.         but WITHOUT ANY WARRANTY; without even the implied warranty of
  22.         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  23.         GNU General Public License for more details.
  24.    
  25.         You should have received a copy of the GNU General Public License
  26.         along with this program; if not, write to the Free Software
  27.         Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  28.     */
  29.  
  30.     /**
  31.      * Sprachdatei laden
  32.      */
  33.     if(!load_plugin_textdomain('instagram','/wp-content/languages/')) // Nach Sprachdatei im wp-languages-Ordner suchen
  34.         load_plugin_textdomain('instagram','/wp-content/plugins/instapress/languages/'); // Default Sprachdatei laden
  35.        
  36.        
  37.     $instapressIncludePath = get_include_path().PATH_SEPARATOR.
  38.                             plugin_dir_path(__FILE__).'instagram-php-api/'.PATH_SEPARATOR.
  39.                             plugin_dir_path(__FILE__).'classes/'.PATH_SEPARATOR.
  40.                             plugin_dir_path(__FILE__).'PowerHour_Geocoder/';
  41.        
  42.     // Include-Path für Zend-Library, Geocoder oder API setzen
  43.     if(!set_include_path($instapressIncludePath)) // Wenn set_include_path nicht funktioniert
  44.         ini_set('include_path', $instapressIncludePath); // ini_set versuchen
  45.    
  46.     require_once 'Instagram_XAuth.php';
  47.    
  48.     require_once 'Instapress_TinyMCE.php';
  49.  
  50.     class InstagramPlugin
  51.     {
  52.                
  53.         // Key in der Tabelle wp_options, unter dem die Einstellungen gespeichert werden
  54.         var $dbOptionKey = 'InstagramPlugin_Options';
  55.        
  56.         // Pfad in dem die Cache-Dateien liegen
  57.         var $cachePath = '';
  58.        
  59.         // Nummer der aktuellen Instanz
  60.         static $CURRENTINSTANCENUMBER = 1;
  61.        
  62.        
  63.         /**
  64.          * Constructor
  65.          */
  66.         function InstagramPlugin()
  67.         {
  68.             // Menü im Backend hinzufügen
  69.             add_action('admin_menu', array(&$this, 'admin_menu'));
  70.            
  71.             // Shortcode registrieren
  72.             add_shortcode('instapress', array(&$this, 'shortcode'));
  73.            
  74.             // Link in der Plugins-Liste zu den Einstellungen
  75.             add_filter('plugin_action_links', array(&$this, 'plugin_page_link'), 5, 2);
  76.            
  77.             // Links unterhalb der Plugin-Beschreibung
  78.             add_filter('plugin_row_meta', array(&$this, 'plugin_row_meta'), 10, 2);
  79.            
  80.             // Pfad in dem Cache-Dateien abgespeichert werden
  81.             $this->cachePath = ABSPATH.'wp-content/cache/';
  82.            
  83.             // Javascripts ergänzen
  84.             add_action('init', array(&$this, 'javascript'));
  85.            
  86.             add_action('wp_ajax_instapress_paging', array(&$this, 'ajax_instapress_paging'));
  87.             add_action('wp_ajax_nopriv_instapress_paging', array(&$this, 'ajax_instapress_paging'));
  88.         }
  89.        
  90.         /**
  91.          * @return InstagramPlugin Die aktive Instanz des Plugins
  92.          */
  93.         function getInstance()
  94.         {
  95.             global $InstagramPlugin;
  96.             if(!isset($InstagramPlugin))
  97.             {
  98.                 $InstagramPlugin = new InstagramPlugin();
  99.             }
  100.            
  101.             return $InstagramPlugin;
  102.         }
  103.        
  104.         /**
  105.          * @return Instagram eine konfigurierte Instanz der API
  106.          */
  107.         function getAPIInstance()
  108.         {
  109.             // Konfiguration laden
  110.             $config = InstagramPlugin::getConfiguration();
  111.                    
  112.             // API instanzieren
  113.             $instagram = new Instagram_XAuth($config);
  114.            
  115.             $instagram->setAccessToken(InstagramPlugin::getAccessToken());
  116.            
  117.             return $instagram;
  118.         }
  119.        
  120.         /**
  121.          * Wird im register_actication_hook aufgerufen
  122.          */
  123.         function install()
  124.         {
  125.             $this->getOptions();
  126.         }
  127.        
  128.         /**
  129.          * Wird bei der Implementierung von shortcode aufgerufen
  130.          */
  131.         function shortcode($params)
  132.         {
  133.             $values = shortcode_atts(array
  134.                                     (
  135.                                         'userid' => '',
  136.                                         'size' => 85,
  137.                                         'piccount' => 9,
  138.                                         'effect' => false,
  139.                                         'url' => false,
  140.                                         'title' => 0,
  141.                                         'paging' => 0,
  142.                                         'max_id' => '',
  143.                                         'like' => 0,
  144.                                         'tag' => '',
  145.                                         'instanceid' => null
  146.                                     ),
  147.                                     $params);
  148.            
  149.             // Wenn für die Instanz noch keine ID angegeben/vergeben wurde
  150.             if(empty($values['instanceid']))
  151.             {
  152.                 // Neue Instanz-ID zuweisen
  153.                 $values['instanceid'] = self::$CURRENTINSTANCENUMBER++;
  154.             }
  155.            
  156.             $instanceId = $values['instanceid'];
  157.            
  158.             // Default-Groesse ist 150x150
  159.             $picSize = (intval($values['size']) > 0) ? intval($values['size']) : 150;
  160.             // Seite die gezeigt werden soll
  161.             $page = intval($values['paging']);
  162.            
  163.             // HTML das vor dem Image eingefügt wird
  164.             $beforeImage = '<div class="instapress-shortcode-image %1$s" id="instapress-shortcode-'.$instanceId.'-image-%2$d">';
  165.             // HTML in dem URL des Images und die gewünschte Größe eingefügt werden
  166.             $imageHtml = '<img src="%1$s" ';
  167.             // width und height aktiviert
  168.             if(!$this->imageAttributesDisabled())
  169.             {
  170.                 $imageHtml .= 'width="%2$d" height="%2$d" ';
  171.             }
  172.             $imageHtml .= 'border="0" /></a></div>';
  173.             // HTML für den Paginator
  174.             $paginatorHtml = '<div class="instapress-shortcode-pager">%s</div>';
  175.             // HTML für den Weiter-Button
  176.             $buttonNextHtml = '<a href="'.get_bloginfo( 'wpurl' ).'" class="next-page-instapress next-page-instapress-'.$instanceId.'" rel="%d-'.$instanceId.'">'.__('Next', 'instagram').' &gt;&gt;</a>';
  177.             // HTML für den Zurück-Button
  178.             $buttonPrevHtml = '<a href="'.get_bloginfo( 'wpurl' ).'" class="prev-page-instapress prev-page-instapress-'.$instanceId.'" rel="%d-'.$instanceId.'">&lt;&lt; '.__('Previous', 'instagram').'</a>';
  179.            
  180.             // Attribut id=instapress-shortcode-page-$page nur zuweisen, wenn Paging aktiviert ist
  181.             $result = '<div class="instapress-shortcode version-'.InstagramPlugin::getVersion().($page ? ' instapress-shortcode-page" id="instapress-shortcode-'.$instanceId.'-page-'.$page.'' : '').'">';
  182.            
  183.             if(!$values['url']) // Nicht via oEmbed?
  184.             {
  185.                 //MODIFIED
  186.                 $data = $this->getFeed($values, $imageHtml, $beforeImage, $picSize, $values['max_id']);
  187.                 //MODIFIED
  188.                 $result .= $data['data'];
  189.                 //var_dump($result);               
  190.                 // Paging aktiviert und Intialer Request (kein AJAX-Request) ==> keine max_id
  191.                 if($page && strlen($values['max_id']) == 0)
  192.                 {
  193.                     $buttons = '';
  194.                     //if($page > 1)
  195.                         $buttons .= sprintf($buttonPrevHtml, $page-1);
  196.                     $buttons .= sprintf($buttonNextHtml, $page+1);
  197.                    
  198.                     $paginator = sprintf($paginatorHtml, $buttons);
  199.                    
  200.                    
  201.                     // Script vor dem Container
  202.                     $result =   '<script type="text/javascript">var instapressConfig'.$instanceId.' = '.json_encode($values).';</script>'.
  203.                                 $paginator.
  204.                                 '<div class="instapress-gallery" id="instapress-gallery-'.$instanceId.'">'.
  205.                                 $result;
  206.                 }
  207.             }
  208.             else // via oEmbed
  209.             {
  210.                 $oEmbed = $this->getOEmbedImage($values['url']);
  211.                
  212.                 $result .= sprintf($beforeImage, 'oembed', 0);
  213.                
  214.                 // Auf aktivierte Effekte überprüfen
  215.                 switch($values['effect'])
  216.                 {
  217.                     // jQuery Fancybox
  218.                     case 'fancybox':
  219.                         $result .= '<a href="'.$oEmbed->url.'" rel="instagram-sc-images" title="'.htmlentities($oEmbed->title).'">';
  220.                         break;
  221.                     case 'highslide':
  222.                         $result .= '<a href="'.$oEmbed->url.'" class="highslide instapress-highslide" title="'.htmlentities($oEmbed->title).'">';
  223.                         break;
  224.                     // Ohne Effekt
  225.                     default:
  226.                         $result .= '<a href="'.$values['url'].'" target="_blank">';
  227.                         break;
  228.                 }
  229.                
  230.                 $result .= sprintf($imageHtml, $oEmbed->url, $picSize);
  231.             }
  232.            
  233.             if(InstagramPlugin::getInstance()->mayShowBacklink())
  234.             {
  235.                 $result .= InstagramPlugin::getBacklink();
  236.             }
  237.             //MODIFIED
  238.             foreach($data['tags'] as $tag) {
  239.                 $result .= '#'.$tag.' ';
  240.             }
  241.             $result .= '</div>';
  242.                        
  243.             if($page)
  244.             {
  245.                 $result .= '</div>'.$paginator;
  246.             }
  247.            
  248.             return $result;
  249.         }
  250.        
  251.         /**
  252.          * Funktion die beim AJAX-Request für die Gallery-Funktion
  253.          */
  254.         function ajax_instapress_paging()
  255.         {
  256.             $values = $_POST['config'];
  257.             if(is_array($values))
  258.             {
  259.                 foreach($values as $key=>$value)
  260.                 {
  261.                     if(is_numeric($value))
  262.                     {
  263.                         $values[$key] = intval($value);
  264.                     }
  265.                 }
  266.                 $values['url'] = false;
  267.                 $values['max_id'] = $_POST['nextMaxId'];
  268.                
  269.                 echo $this->shortcode($values);
  270.             }
  271.             else
  272.             {
  273.                 _e("Your jQuery version seems to be out of date. Please update jQuery at least to version 1.4.", 'instagram');
  274.             }
  275.            
  276.             die(); // this is required to return a proper result
  277.         }
  278.        
  279.         /**
  280.          * Erstellt den HTML-Quelltext für den Fotofeed mit den angegebenen Parametern
  281.          * @param $values array         Siehe Instapress-shortcode-Parameter
  282.          * @param $imageHtml string     HTML-Template für das Image
  283.          * @param $beforeImage string   HTML das vor dem Image gezeigt werden soll
  284.          * @param $picSize int          Größe des Fotos in Pixel
  285.          * @param $nextMaxId int        ID des Fotos, ab dem der Feed erstellt werden soll (Default: 0)
  286.          *
  287.          * @todo Für Multiple Instanzen kompatibel machen (duplicate ID-Attrbiutes...)
  288.          */
  289.         function getFeed($values, $imageHtml, $beforeImage, $picSize, $nextMaxId = '')
  290.         {
  291.             $tagFeed = (!empty($values['tag']));
  292.             $result = "";
  293.             if(isset($values['userid']) && !empty($values['userid']))
  294.             {
  295.                 $userid = $values['userid'];
  296.                 if(!is_numeric($values['userid']) && $values['userid'] != 'self' && $values['userid'] != 'myfeed' && strlen($values['userid']))
  297.                     $userid = InstagramPlugin::getUserIdByName($values['userid']);
  298.             }
  299.                
  300.             $piccounter = 1;
  301.        
  302.             // "Ungerades" Bild
  303.             $odd = true;
  304.            
  305.             $lastShownId = $nextMaxId;
  306.            
  307.             do
  308.             {
  309.                 $max_id = $nextMaxId;
  310.                 // Feed eines Users ab der gegebenen max_id laden und nächsten max_id holen
  311.                 if(!$tagFeed)
  312.                     $data = InstagramPlugin::getFeedByUserId($userid, $max_id, &$nextMaxId, intval($values['piccount']));
  313.                 // Feed eines Users nach Tag gefiltert ab der gegebenen max_id laden und nächsten max_id holen
  314.                 else if($tagFeed && $userid)
  315.                     $data = InstagramPlugin::getFeedByUserId($userid, $max_id, &$nextMaxId, intval($values['piccount']), new InstapressFeedFilter('tags', $values['tag'], InstapressFeedFilter::IN_ARRAY));
  316.                 else // Feed nach angegebenem Tag laden
  317.                     $data = InstagramPlugin::getFeedByTag($values['tag'], $max_id, &$nextMaxId, intval($values['piccount']));
  318.                
  319.                 $result['tags'] = $data['tags'];
  320.                 // Daten im Feed gefunden
  321.                 //MODIFIED
  322.                 if(count($data['results']) > 0)
  323.                 {
  324.                     //MODIFIED
  325.                     foreach($data['results'] as $obj)
  326.                     {
  327.                         // Nur die ersten X Bilder anzeigen?
  328.                         if(intval($values['piccount']) > 0 && $piccounter > $values['piccount'])
  329.                             break;
  330.                            
  331.                         // Image-Titel anzeigen, wenn title auf 1 gesetzt wurde
  332.                         $title = (intval($values['title']) == 1) ? $obj->caption->text : "";
  333.                         $title = htmlentities(utf8_decode($title));
  334.                        
  335.                         // Klasse für gerade/ungerade und ID mit Index hinzufügen
  336.                         $result['data'] .= sprintf($beforeImage, (($odd) ? 'odd' : 'even'), $piccounter++);
  337.                        
  338.                         $odd = !$odd;
  339.                        
  340.                         // Welche Property soll für das Image verwendet werden
  341.                         $imageKey = InstagramPlugin::getImageKey($picSize);
  342.                        
  343.                         // Auf aktivierte Effekte überprüfen
  344.                         switch($values['effect'])
  345.                         {
  346.                             // jQuery Fancybox
  347.                             case 'fancybox':
  348.                                 $result['data'] .= '<a href="'.$obj->images->standard_resolution->url.'" rel="instagram-sc-images" title="'.$title.'">';
  349.                                 break;
  350.                             case 'highslide':
  351.                                 $result['data'] .= '<a href="'.$obj->images->standard_resolution->url.'" class="highslide instapress-highslide" title="'.$title.'">';
  352.                                 break;
  353.                             // Ohne Effekt
  354.                             default:
  355.                                 $result['data'] .= '<a href="'.$obj->link.'" target="_blank">';
  356.                                 break;
  357.                         }
  358.                        
  359.                         $result['data'] .= sprintf($imageHtml, $obj->images->$imageKey->url, $picSize);
  360.                                                
  361.                         if($nextMaxId)
  362.                             $lastShownId = $obj->id;
  363.                         else
  364.                             $lastShownId = '';
  365.                     }
  366.                 }
  367.                 else
  368.                 {
  369.                     break;
  370.                 }
  371.             }
  372.             while($nextMaxId && ($piccounter <= $values['piccount'] || intval($values['piccount']) == 0));
  373.            
  374.             $result['data'] .= '<input type="hidden" id="instapress-'.$values['instanceid'].'-next-max-id-'.(intval($values['paging'])+1).'" value="'.$nextMaxId.'" />';
  375.            
  376.             return $result;
  377.         }
  378.        
  379.         /**
  380.          * Lädt eine einzelnes Image anhand der Instagram-URL
  381.          * @param $url string Instagram-URL des Images
  382.          */
  383.         function getOEmbedImage($url)
  384.         {
  385.             $json = @file_get_contents('http://api.instagram.com/oembed?url='.$url);
  386.             return json_decode($json);
  387.         }
  388.        
  389.         /**
  390.          * Lädt den Feed für den angegebenen User
  391.          * @param $userid mixed     User-Id, 'self' oder 0/null/false
  392.          * @param $max_id int       ID ab der der Feed geladen werden soll
  393.          * @param &$nextMaxId int   max_id die für den Aufruf der nächsten Seite des Feeds benötigt wird
  394.          * @param $filter array     Liste mit Filter (z.B. 'tag' => 'myhashtag')
  395.          *
  396.          * @return array der Feed (siehe Instagram API Dokumentation)
  397.          */
  398.         function getFeedByUserId($userid, $max_id = '', $nextMaxId = 0, $count = 0, $filter = null)
  399.         {  
  400.             $writeToCache = true;
  401.                                    
  402.             $cacheid = $userid.($max_id ? "_".$max_id : "");
  403.            
  404.             if(InstagramPlugin::getInstance()->getFeedFromCache($cacheid))
  405.             {
  406.                 $json = InstagramPlugin::getInstance()->getFeedFromCache($cacheid);
  407.                 $writeToCache = false;
  408.             }
  409.             // Wenn es eine User-Id gibt bzw. 'self' hinterlegt wurde, diesen Feed laden
  410.             else if(intval($userid) != 0 || $userid == 'self')
  411.             {
  412.                 $json = InstagramPlugin::getAPIInstance()->getUserRecent($userid, $max_id, $count);
  413.             }
  414.             // Wenn statt der UserId 'myfeed' eingetragen wurde, den Feed des Users laden
  415.             else if($userid == 'myfeed')
  416.             {
  417.                 $json = InstagramPlugin::getAPIInstance()->getUserFeed($max_id);
  418.             }
  419.             // ansonsten einfach den Popular-Media-Feed laden
  420.             else
  421.             {
  422.                 $json = InstagramPlugin::getAPIInstance()->getPopularMedia();
  423.             }
  424.                        
  425.             $response = json_decode($json);
  426.            
  427.             //MODIFIED
  428.             $result['results'] = null;
  429.            
  430.             //MODIFIED
  431.             $result['tags'] = $response->data[0]->tags;
  432.  
  433.             if($response->data)
  434.             {
  435.                 //MODIFIED
  436.                 $result['results'] = $response->data;
  437.             }
  438.            
  439.             // Wenn ein Filter definiert wurde
  440.             if(!empty($filter))
  441.             {
  442.                 // diesen anwenden
  443.                 //MODIFIED
  444.                 $result['results'] = $filter->filter($result);
  445.             }
  446.            
  447.             if($writeToCache && $result)
  448.                 InstagramPlugin::getInstance()->writeFeedToCache($cacheid, $json);
  449.                
  450.             // Wenn es noch weitere Fotos gibt
  451.             if($response->pagination)
  452.                 $nextMaxId = $response->pagination->next_max_id; // max_id für nächsten Request setzen
  453.             else // Keine weiteren Fotos mehr
  454.                 $nextMaxId = null;
  455.                
  456.                
  457.             return $result;
  458.         }
  459.        
  460.         /**
  461.          * Lädt den Feed für den angegebenen Tag
  462.          * @param $tag string       Hashtag nach dem gesucht werden soll
  463.          * @param $max_id int       ID ab der der Feed geladen werden soll
  464.          * @param &$nextMaxId int   max_id die für den Aufruf der nächsten Seite des Feeds benötigt wird
  465.          *
  466.          * @return array der Feed (siehe Instagram API Dokumentation)
  467.          */
  468.         function getFeedByTag($tag, $max_id = '', $nextMaxId = 0, $count = 0)
  469.         {  
  470.             $writeToCache = true;
  471.                                    
  472.             $cacheid = $tag.($max_id ? "_".$max_id : "");
  473.            
  474.             if(InstagramPlugin::getInstance()->getFeedFromCache($cacheid))
  475.             {
  476.                 $json = InstagramPlugin::getInstance()->getFeedFromCache($cacheid);
  477.                 $writeToCache = false;
  478.             }
  479.             else
  480.             {
  481.                 $json = InstagramPlugin::getAPIInstance()->getRecentTags($tag, $max_id);
  482.             }
  483.                        
  484.             $response = json_decode($json);
  485.            
  486.             if($writeToCache && $response->data)
  487.                 InstagramPlugin::getInstance()->writeFeedToCache($cacheid, $json);
  488.                
  489.             // Wenn es noch weitere Fotos gibt
  490.             if($response->pagination)
  491.                 $nextMaxId = $response->pagination->next_max_id; // max_id für nächsten Request setzen
  492.             else // Keine weiteren Fotos mehr
  493.                 $nextMaxId = null;
  494.                
  495.             return $response->data;
  496.         }
  497.        
  498.         function getCacheFilename($cachename)
  499.         {
  500.             if(!$cachename)
  501.                 $cachename = 'popular-media';
  502.             return $this->cachePath.'cache-'.$cachename.'.json';
  503.         }
  504.        
  505.         function getDataFromCache($cachename)
  506.         {
  507.             // Dateiname der Cache-Datei
  508.             $cacheFile = $this->getCacheFilename($cachename);
  509.            
  510.             // Wenn die Cache-Datei lesbar ist und nicht �lter als die maximal erlaubte Cache-Zeit
  511.             if($this->cacheIsEnabled() && is_readable($cacheFile) && filemtime($cacheFile) > strtotime('- '.$this->getOption('app_cache_time').' Minutes', time()))
  512.             {
  513.                 // Cache laden
  514.                 return @file_get_contents($cacheFile); 
  515.             }
  516.            
  517.             return false;  
  518.         }
  519.        
  520.         /**
  521.          * Versucht die angegebenen Daten in den Cache zu schreiben
  522.          * @param $cachename string Name des Caches
  523.          * @param $json string JSON-Daten
  524.          *
  525.          * @return bool true = in Cache geschrieben, false = Fehler beim Cache schreiben
  526.          */
  527.         function writeDataToCache($cachename, $json)
  528.         {
  529.             // Dateiname der Cache-Datei
  530.             $cacheFile = $this->getCacheFilename($cachename);
  531.            
  532.             // Beschreibbarer Cache?
  533.             if($this->cacheIsEnabled())
  534.             {
  535.                 @file_put_contents($cacheFile, $json);
  536.                 return true;
  537.             }
  538.            
  539.             return false;
  540.         }
  541.        
  542.         /**
  543.          * Überprüft ob der Inhalt gecached werden soll und kann
  544.          *
  545.          * @return bool true = Cache aktiv, false = Cache inaktiv
  546.          */
  547.         function cacheIsEnabled()
  548.         {
  549.             if($this->getOption('app_cache_time') == 0)
  550.                 return false;
  551.            
  552.             return $this->cacheIsWritable();
  553.         }
  554.        
  555.         /**
  556.          * Überprüft ob der Inhalt gecached werden kann bzw. es ein beschreibbares Cache-Verzeichnis gibt
  557.          * http://codex.wordpress.org/Changing_File_Permissions
  558.          *
  559.          * @return bool true = Cache beschreibbar, false = Cache nicht beschreibbar
  560.          */
  561.         function cacheIsWritable()
  562.         {
  563.             // Wenn es das Cache-Verzeichnis noch nicht gibt und wp-content aber beschreibbar ist
  564.             if(!is_dir($this->cachePath) && is_writable(ABSPATH.'wp-content/'))
  565.             {
  566.                 // Versuchen Cache-Verzeichnis mit Schreibrechten anzulegen
  567.                 return @mkdir($this->cachePath, 0755);
  568.             }
  569.            
  570.             // Beschreibbares Cache-Verzeichnis
  571.             return is_writable($this->cachePath);
  572.         }
  573.        
  574.         /**
  575.          * Lädt einen Feed aus dem Cache
  576.          * @param $cachename
  577.          */
  578.         function getFeedFromCache($cachename)
  579.         {
  580.             return $this->getDataFromCache($cachename);
  581.         }
  582.        
  583.         /**
  584.          * Speichert einen Feed im Cache
  585.          * @param $cachename string
  586.          * @param $json string
  587.          */
  588.         function writeFeedToCache($cachename, $json)
  589.         {
  590.             return $this->writeDataToCache($cachename, $json);
  591.         }
  592.        
  593.         /**
  594.          * Lädt ein Image aus dem Cache
  595.          * @param $mediaId int ID des Images
  596.          */
  597.         function getMediaFromCache($mediaId)
  598.         {
  599.             return $this->getDataFromCache('media-'.$mediaId);
  600.         }
  601.        
  602.         /**
  603.          * Speichert ein Image im Cache
  604.          * @param $mediaId int ID des Images
  605.          * @param $json string JSON-Daten
  606.          */
  607.         function writeMediaToCache($mediaId, $json)
  608.         {
  609.             return $this->writeDataToCache('media-'.$mediaId, $json);
  610.         }
  611.        
  612.         /**
  613.          *
  614.          * @param $coordinates array Koordinaten
  615.          *
  616.          * @return array Feed mit Bildern
  617.          */
  618.         function getLocationBasedFeed($coordinates)
  619.         {
  620.             // Wenn Koordinaten gespeichert wurden
  621.             if(!empty($coordinates))
  622.             {
  623.                 // Name für den Cache erstellen
  624.                 $cachename = implode('-', $coordinates);
  625.                 $cachename = str_replace('.', '_', $cachename);
  626.                
  627.                 // Versuchen Feed aus dem Cache zu laden
  628.                 if(InstagramPlugin::getInstance()->getFeedFromCache($cachename))
  629.                 {
  630.                     $json = InstagramPlugin::getInstance()->getFeedFromCache($cachename);
  631.                 }
  632.                 else // Wenn kein passender Feed im Cache war
  633.                 {
  634.                     // Feed von dem API laden
  635.                     $json = InstagramPlugin::getAPIInstance()->mediaSearch($coordinates[0], $coordinates[1], null, null, 250);
  636.                     // Im Cache speichern
  637.                     InstagramPlugin::getInstance()->writeFeedToCache($cachename, $json);
  638.                 }
  639.                
  640.                 $response = json_decode($json);
  641.                
  642.                 return $response->data;
  643.             }
  644.            
  645.             return array();
  646.         }
  647.        
  648.         /**
  649.          * Lädt den Titel des Bildes
  650.          * @param $imageId int ID des Bildes, von dem der Titel geladen werden soll
  651.          *
  652.          * @return string Titel des Bildes
  653.          */
  654.         function getImageTitle($imageId)
  655.         {
  656.             // Image aus Cache laden
  657.             $json = $this->getMediaFromCache($imageId);
  658.            
  659.             // Noch nicht im Cache?
  660.             if(!$json)
  661.             {
  662.                 $json = $this->getAPIInstance()->getMedia($imageId);
  663.                 $writeToCache = true;
  664.             }
  665.            
  666.             $media = json_decode($json);
  667.            
  668.             if($writeToCache && $media->data)
  669.                 InstagramPlugin::getInstance()->writeMediaToCache($imageId, $json);
  670.            
  671.             return $media->data->caption->text;
  672.         }
  673.        
  674.         /**
  675.          *
  676.          * @param $name string Instagram-Username
  677.          *
  678.          * @return int User-Id des gesuchten Users, 'self' oder 0, wenn kein passender User gefunden wurde
  679.          */
  680.         function getUserIdByName($name)
  681.         {          
  682.             if($name && $name != 'self')
  683.             {
  684.                 $json = InstagramPlugin::getAPIInstance()->searchUser($name);
  685.                
  686.                 $response = json_decode($json);
  687.                                
  688.                 $data = $response->data;
  689.                
  690.                 if(count($data) > 0)
  691.                 {
  692.                     return $data[0]->id;
  693.                 }
  694.             }
  695.             else if($name == 'self')
  696.             {
  697.                 return $name;
  698.             }
  699.             return 0;
  700.         }
  701.        
  702.         /**
  703.          * Lädt die gespeicherten Einstellungen bzw. die Standardeinstellungen
  704.          *
  705.          * @return array Gespeicherte Einstellungen
  706.          */
  707.         function getOptions()
  708.         {
  709.             // Default-Werte
  710.             $options = array
  711.             (
  712.                 'app_access_token' => '',
  713.                 'app_cache_time' => 30
  714.             );
  715.            
  716.             // Gespeicherte Werte laden
  717.             $saved = get_option($this->dbOptionKey);
  718.            
  719.             // Wenn es gespeicherte Werte gibt
  720.             if(!empty($saved))
  721.             {
  722.                 // Gespeicherte Werte über Default-Werte schreiben
  723.                 foreach($saved as  $key => $option)
  724.                 {
  725.                     $options[$key] = $option;
  726.                 }
  727.             }
  728.            
  729.             //
  730.             if($saved != $options)
  731.                 update_option($this->dbOptionKey, $options);
  732.                
  733.             return $options;
  734.         }
  735.        
  736.         function getPluginUrl()
  737.         {
  738.             return get_admin_url(null, 'options-general.php?page=instagram.php');
  739.         }
  740.        
  741.         function getPluginDirUrl()
  742.         {
  743.             return trailingslashit(plugins_url('', __FILE__));
  744.         }
  745.        
  746.         function getPluginDirPath()
  747.         {
  748.             return trailingslashit(plugin_dir_path(__FILE__));
  749.         }
  750.        
  751.         /**
  752.          * Lädt eine einzelne Einstellung
  753.          *
  754.          * @param $key string Key der Option
  755.          *
  756.          * @return mixed
  757.          */
  758.         function getOption($key)
  759.         {
  760.             $options = $this->getOptions();
  761.            
  762.             return $options[$key];
  763.         }
  764.        
  765.         /**
  766.          * Handelt das Formular
  767.          */
  768.         function handleOptions()
  769.         {
  770.             $options = $this->getOptions();
  771.            
  772.             //Formular abgesendet
  773.             if(isset($_POST['instagram-update-auth-settings']))
  774.             {          
  775.                 $options = array();
  776.                 //$options['app_client_id'] = trim($_POST['instagram-app-client-id']);
  777.                 //$options['app_client_secret'] = trim($_POST['instagram-app-client-secret']);
  778.                 $options['app_user_username'] = trim($_POST['instagram-app-user-username']);
  779.                 $options['app_user_password'] = trim($_POST['instagram-app-user-password']);
  780.                
  781.                 // Einstellungen in der DB speichern
  782.                 update_option($this->dbOptionKey, $options);
  783.                
  784.                 // API instanzieren
  785.                 $instagram = InstagramPlugin::getAPIInstance();
  786.                
  787.                 // Wenn es noch keinen Token gibt
  788.                 if(!$options['app_access_token'])
  789.                 {
  790.                     // In dieser Variable werden eventuelle Fehlermeldungen während der Autorisierung gespeichert
  791.                     $errorMessage = "";
  792.                     // Request an das API schicken, um einen Access-Token zu erhalten
  793.                     $token = $instagram->getAccessToken(&$errorMessage);
  794.                
  795.                     // Wenn es einen Access-Token gibt
  796.                     if($token)
  797.                     {
  798.                         // Access-Token speichern
  799.                         $options['app_access_token'] = $token;
  800.                         // Einstellungen in der DB speichern
  801.                         update_option($this->dbOptionKey, $options);
  802.                         //
  803.                         echo '<div class="updated"><p>'.__('Settings saved.', 'instagram').'</p></div>';
  804.                     }
  805.                     else if($errorMessage) // Es ist ein Fehler aufgetreten
  806.                     {
  807.                         echo '<div class="error"><p>'.__('Instagram API reported the following error', 'instagram').': <b>';
  808.                         echo $errorMessage;
  809.                         echo '</b></p></div>';
  810.                     }
  811.                 }
  812.             }
  813.             // Einstellung zurücksetzen
  814.             else if(isset($_POST['instagram-reset-settings']))
  815.             {
  816.                 // Einstellungen in der DB zurücksetzten / löschen
  817.                 delete_option($this->dbOptionKey);
  818.             }
  819.            
  820.             // Allgemeine Einstellungen
  821.             if(isset($_POST['instagram-update-settings']))
  822.             {
  823.                 // Cache-Interval speichern
  824.                 $cacheTime = intval($_POST['instagram-cache-time']);
  825.                 $options['app_cache_time'] = $cacheTime;
  826.                 $options['app_disable_effects'] = isset($_POST['instagram-disable-fancybox']);
  827.                 $options['app_disable_image_attributes'] = isset($_POST['instagram-disable-image-attr']);
  828.                 $options['app_show_backlink'] = isset($_POST['instagram-show-backlink']);
  829.                 // Einstellungen in der DB speichern
  830.                 update_option($this->dbOptionKey, $options);
  831.             }
  832.            
  833.             // Die Instagram-Authorize-URI
  834.             $authorizeUrl = $this->getOAuthRedirectUrl();
  835.            
  836.             include('instagram-options.php');
  837.         }
  838.        
  839.         /**
  840.          * @return array Gibt die Einstellungen für die API zurück
  841.          */
  842.         function getConfiguration()
  843.         {
  844.             $options = InstagramPlugin::getInstance()->getOptions();
  845.             return array(
  846.                             'site_url'      => 'https://api.instagram.com/oauth/access_token',
  847.                             'client_id'     => '0a344b64448b43e5bb8e1c22acffc0ef',
  848.                             'client_secret' => 'ff62e43965be4a48b83a32261cd540bc',
  849.                             'username'      => $options['app_user_username'],
  850.                             'password'      => $options['app_user_password'],
  851.                             'grant_type'    => 'password',
  852.                             'redirect_uri'  => InstagramPlugin::getOAuthRedirectUrl()
  853.                         );
  854.         }
  855.        
  856.         /**
  857.          * Fügt den Menüpunkt Instapress im Backend hinzu
  858.          */
  859.         function admin_menu()
  860.         {
  861.             add_options_page('Instapress '.__('Settings', 'instagram'), 'Instapress', 8, basename(__FILE__), array(&$this, 'handleOptions'));
  862.         }
  863.        
  864.         /**
  865.          * @return string Name des Plugins
  866.          */
  867.         function getPluginName()
  868.         {
  869.             return plugin_basename(__FILE__);
  870.         }
  871.        
  872.         /**
  873.          * Hook für die Link in der Plugin-Liste
  874.          * @param $links
  875.          * @param $file
  876.          */
  877.         function plugin_page_link($links, $file)
  878.         {          
  879.             // Wenn es dieses Plugin ist
  880.             if($file == $this->getPluginName())
  881.             {
  882.                 // Link zu Einstellungs-Seite
  883.                 $settingsLink = '<a href="'.$this->getOAuthRedirectUrl().'">'.__('Settings', 'instagram').'</a>';
  884.                 // Vorne anhängen
  885.                 array_unshift( $links, $settingsLink );
  886.             }
  887.            
  888.             return $links;
  889.         }
  890.        
  891.         /**
  892.          * Hook für Daten unterhalb der Plugin-Becshreibung in der Plugin-Liste
  893.          * @param $links
  894.          * @param $file
  895.          */
  896.         function plugin_row_meta($links, $file)
  897.         {
  898.             // Wenn es dieses Plugin ist
  899.             if($file == $this->getPluginName())
  900.             {
  901.                 // Facebook Page
  902.                 $links[] = '<a href="http://www.facebook.com/instapress" target="_blank">'.__('Like it on Facebook', 'instagram').'</a>';
  903.                 // Blog-Beitrag
  904.                 $links[] = '<a href="http://liechtenecker.at/instapress-das-instagram-plugin-fur-wordpress/" target="_blank">'.__('Visit our blog', 'instagram').'</a>';
  905.             }
  906.            
  907.             return $links;
  908.         }
  909.        
  910.         /**
  911.          * @return bool     true = Fancybox-Effekt aktiviert, false = Fancybox-Effekt deaktiviert
  912.          */
  913.         function effectsEnabled()
  914.         {
  915.             return (!$this->getOption('app_disable_effects'));
  916.         }
  917.        
  918.         /**
  919.          * @return bool     true = Darf Backlink anzeigen, false = keinen Backlink anzeigen
  920.          */
  921.         function mayShowBacklink()
  922.         {
  923.             return ($this->getOption('app_show_backlink'));
  924.         }
  925.        
  926.         function getBacklink()
  927.         {
  928.             return '<a class="instagram-backlink" href="http://instapress.it" target="_blank">Powered by Instapress</a>';
  929.         }
  930.        
  931.         /**
  932.          * @return bool     true = width und height für img-Tags deaktivieren, false = width und height in img-Tag setzen
  933.          */
  934.         function imageAttributesDisabled()
  935.         {
  936.             return $this->getOption('app_disable_image_attributes');   
  937.         }
  938.        
  939.         function javascript()
  940.         {
  941.             if($this->effectsEnabled())
  942.             {
  943.                 if(!is_admin())
  944.                 {
  945.                     // Fancybox
  946.                     wp_register_script('fancybox', plugins_url('/fancybox/jquery.fancybox-1.3.4.pack.js', __FILE__), array('jquery'), "1.3.4");
  947.                     // Default JS
  948.                     wp_enqueue_script('instapress', plugins_url('/instapress.js', __FILE__), array('jquery', 'fancybox'), InstagramPlugin::getVersion(), true);
  949.                 }
  950.             }
  951.             else // Wenn Effekte deaktiviert wurden, muss die Gallery trotzdem noch funktionieren
  952.             {
  953.                 //wp_enqueue_script('instapress', plugins_url('/instapress.js', __FILE__), array('jquery'), InstagramPlugin::getVersion(), true);
  954.             }
  955.         }
  956.        
  957.         /**
  958.          * @return string die URI an die nach der Autorisierung weitergeleitet wird
  959.          */
  960.         function getOAuthRedirectUrl()
  961.         {
  962.             return get_admin_url().'options-general.php?page=instagram.php';//.'instagram/oauth.php';
  963.         }
  964.        
  965.         /**
  966.          * @return string Access-Token der in der Datenbank gespeichert ist bzw. null
  967.          */
  968.         function getAccessToken()
  969.         {
  970.             $options = InstagramPlugin::getInstance()->getOptions();
  971.            
  972.             return $options['app_access_token'];
  973.         }
  974.        
  975.         function getVersion()
  976.         {
  977.             return INSTAPRESS_VERSION;
  978.         }
  979.        
  980.         /**
  981.          * Gibt den Namen der JSON-Eigenschaft zurück, die für die angegebenen Bildergröße verwendet werden sollte
  982.          * @param $size
  983.          */
  984.         function getImageKey($size)
  985.         {
  986.             if($size <= 150)
  987.                 return 'thumbnail';
  988.             if($size <= 306)
  989.                 return 'low_resolution';
  990.            
  991.             return 'standard_resolution';
  992.         }
  993.        
  994.         /**
  995.          * @return array Liste mit verfügbaren Lightbox-Effekten
  996.          */
  997.         function getAvailableEffects()
  998.         {
  999.             return array(   'fancybox' => 'Fancybox',
  1000.                             'highslide' => 'Highslide (plugin required)');
  1001.         }
  1002.                
  1003.         function isCurlInstalled()
  1004.         {
  1005.             return in_array('curl', get_loaded_extensions());
  1006.         }
  1007.        
  1008.         /**
  1009.          * @return array|bool   Liste mit Fehlermeldungen oder false wenn es keine Probleme gibt
  1010.          */
  1011.         function getErrors()
  1012.         {
  1013.             $errors = array();
  1014.             if(!InstagramPlugin::getInstance()->cacheIsWritable())
  1015.                 $errors[] = sprintf(__('To improve performance of this plugin, it is highly recommended to make the directory wp-content or wp-content/cache writable. For further information click <a target="_blank" href="%s">here</a>' , 'instagram'), 'http://codex.wordpress.org/Changing_File_Permissions');
  1016.             if(!InstagramPlugin::getInstance()->isCurlInstalled())
  1017.                 $errors[] = __('Instapress requires <a href="http://php.net/manual/en/book.curl.php" target="_blank">PHP cURL</a> extension to work properly', 'instagram');
  1018.             if(!function_exists('mb_detect_encoding'))
  1019.                 $errors[] = __('Instapress Geocoding won\'t work unless <a href="http://www.php.net/manual/en/mbstring.installation.php" target="_blank">mbstring</a> is activated', 'instagram');
  1020.             if(!extension_loaded('openssl'))
  1021.                 $errors[] = sprintf(__('Instapress needs to communicate with Instagram\'s API via SSL. If you are having troubles, please %sread that topic.%s'), '<a href="http://wordpress.org/support/topic/fatal-error-plugin-instapress-version-131?replies=6" target="_blank">', '</a>');
  1022.                
  1023.             return (count($errors) > 0 ? $errors : false);
  1024.         }
  1025.        
  1026.     }
  1027.    
  1028.     /**
  1029.      * Repräsentiert einen Filter um die Ergebnisse des Instagram API zu filtern
  1030.      * @author tkrammer
  1031.      *
  1032.      */
  1033.     class InstapressFeedFilter
  1034.     {
  1035.         /**
  1036.          * verwendet in_array() zum filtern
  1037.          * @var int
  1038.          */
  1039.         const IN_ARRAY = 0;
  1040.         /**
  1041.          * verwendet == zum Filtern
  1042.          * @var int
  1043.          */
  1044.         const EQUALS = 1;
  1045.        
  1046.         protected $type = null;
  1047.        
  1048.         protected $filter = null;
  1049.        
  1050.         protected $filterName = "";
  1051.        
  1052.         public function __construct($filterName = null, $filter = null, $type = null)
  1053.         {
  1054.             $this->filterName = $filterName;
  1055.             $this->filter = $filter;
  1056.             $this->type = $type;
  1057.         }
  1058.        
  1059.         public function setType($type)
  1060.         {
  1061.             $this->type = $type;
  1062.         }
  1063.        
  1064.         public function setFilter($filter)
  1065.         {
  1066.             $this->filter = $filter;
  1067.         }
  1068.        
  1069.         public function setFilterName($name)
  1070.         {
  1071.             $this->filterName = $name;
  1072.         }
  1073.        
  1074.         /**
  1075.          * Filtert das angegebene Array (aus z.B. $response->data) nach den angegeben Kriterien
  1076.          * @param array $data
  1077.          */
  1078.         public function filter(array $data)
  1079.         {
  1080.             $result = array();
  1081.             // Name der zu filternden Eigenschaft
  1082.             $filterName = $this->filterName;
  1083.             // Bild im Ergebnis behalten?
  1084.             $keepImage = false;
  1085.             // Alle Images durchgehen
  1086.             foreach($data as $image)
  1087.             {
  1088.                 // Filter je nach Typ anwenden
  1089.                 switch($this->type)
  1090.                 {
  1091.                     case self::IN_ARRAY:
  1092.                         $keepImage = (in_array($this->filter, $image->$filterName));
  1093.                         break;
  1094.                        
  1095.                     case self::EQUALS:
  1096.                         $keepImage = ($this->filter == $image->$filterName);
  1097.                         break;
  1098.                 }
  1099.                
  1100.                 if($keepImage)
  1101.                 {
  1102.                     $result[] = $image;
  1103.                 }
  1104.             }
  1105.            
  1106.             return $result;
  1107.         }
  1108.     }
  1109.        
  1110.     /**
  1111.      * Widget registrieren und laden
  1112.      */
  1113.     if(!function_exists('load_instagram')):    
  1114.         add_action( 'widgets_init', 'load_instagram' );
  1115.         function load_instagram()
  1116.         {
  1117.             register_widget( 'Instagram_Widget' );
  1118.         }
  1119.     endif;
  1120.        
  1121.     /**
  1122.      * Plugin instanzieren
  1123.      */
  1124.     if (class_exists('InstagramPlugin')):
  1125.         $InstagramPlugin = InstagramPlugin::getInstance();
  1126.         if (isset($InstagramPlugin))
  1127.         {
  1128.             register_activation_hook(__FILE__, array(&$InstagramPlugin, 'install'));
  1129.         }
  1130.     endif;
  1131.    
  1132.  
  1133.     include('widget.php');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement