0

私のウェブサイトからユーザーの Facebook アカウントに画像をアップロードするこのスクリプトを購入しましたが、残念ながらこのスクリプトはサポートされておらず、スクリプトに問題があります。リンクをクリックして画像をアップロードするたびに、画像はユーザーのアカウントに正常にアップロードされますが、アップロード後にページを更新するか、他のリンクをクリックすると、画像が再度アップロードされます。ここに私のindex.phpとfb_wrapper_class.phpコードがあります

<?php

/* =============================================================================

    Example 1: This example covers the basics of uploading a photo to facebook.
        It uses the same code covered in part B, "Usage", of the guide.

    In order to run this example on your own system, be sure to update the 
    App id & secret id in the config.php and the $redirectURL variable, below,
    to your own path.


                                PLEASE NOTE:

    !!!!  This example is basic and offers no feedback of the results.  !!!!
                It's purpose is to show the minimal code required

============================================================================= */


    // *** Use these for development only   
    ini_set('display_errors',1);
    error_reporting(E_ALL | E_STRICT);

    // *** Include these files
    require_once('fb-image-upload/config.php');
    require_once('fb-image-upload/fb_wrapper_class.php');

    /* 
     *  You would normally use redirect URL from the config.php (REDIRECT_URL).
     *  But as I'm using various different example files, each needs there own
     *  redirect URL so I've defined each one in their own file.
     */
    $redirectURL = "http://localhost/playground/fb-class-final/1_example_documentation_basics.php";

    // *** Create object
    $fbObj = new FaceBookWrapper(APP_ID, SECRET_ID, $redirectURL);

    // *** Include a login button
    echo '<a href="' . $fbObj->getLoginURL() . '">Login</a>'; 

    // *** Add photo
    $fbObj->addPhoto('fb-image-upload/assets/test.jpg', 'test image', 'Test album', 'Testing 1, 2, 3');

    // *** Show any errors 
    echo $fbObj->getError();
?>

fb_wrapper_class.php

<?php


class FaceBookWrapper
{
    // *** Required settings
    private $_appId;
    private $_secretId;
    private $_redirectURL;
    private $_userId;

    // *** Facebook Object
    private $_facebookObj;

    private $_user;

    private $_errorArray = array();
    private $_debugArray = array();

    private $permissions = 'user_about_me, user_photos, friends_photos, publish_stream, publish_actions';

    /*
        Thanks to DMGV for this one: I put “publish_stream and publish_actions” together in $permissions and now i can post without approve!
    */
## _____________________________________________________________________________    
## ________                _____________________________________________________
## ________ PUBLIC METHODS _____________________________________________________
## _____________________________________________________________________________
##      

    public function __construct($appId, $secretId, $redirectURL, $userId='me', $cookies=true)
    {
        $this->_appId = $appId;
        $this->_secretId = $secretId;
        $this->_redirectURL = $redirectURL;
        $this->_userId = $userId;


        // *** Unset facebook user id
        $user = null; 

        // *** include the facebook api class
        require_once('fb-image-upload/facebook.php');

        // *** Create our Application instance.
        $this->_facebookObj = new Facebook(array(
          'appId'  => $appId,
          'secret' => $secretId,
          'cookie' => $cookies,
        )); 

        // *** This ensures we're logged in.
        $this->_user = $this->_facebookObj->getUser();

        // *** The user to lookup
        if ($userId == 'me') {
            $this->_userId = $this->_user;
        } else {
            $this->_userId = $userId;
        }
    }


    /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 
     *  Login / Logout Methods
     *  
     */

    public function getLoginURL()
    # Return the login URL link
    {
        $loginUrl = $this->_facebookObj->getLoginUrl(
                array(
                    'scope'         => $this->permissions,
                    'redirect_uri'  => $this->_redirectURL
                )
        );      

        return $loginUrl;
    }

    ## --------------------------------------------------------

    public function loginRedirect()
    # Automatically redirect you to the facebook login page
    {
        if (!$this->_user) {                
            header("Location:{$this->_facebookObj->getLoginUrl(array('scope' => $this->permissions, 'redirect_uri'  => $this->_redirectURL))}");
            exit;
        }
    }

    ## --------------------------------------------------------

    public function getLogoutURL()
    # Return the logout URL link. Doesn't remove the cookie
    {
        $logoutUrl  = $this->_facebookObj->getLogoutUrl();
        return $logoutUrl;
    }

    ## --------------------------------------------------------

    public function logout()
    {
        // *** Remove the cookie
        if (isset($_SERVER['HTTP_COOKIE'])) {
            $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
            foreach($cookies as $cookie) {
                $parts = explode('=', $cookie);
                $name = trim($parts[0]);
                setcookie($name, '', time()-1000);
                setcookie($name, '', time()-1000, '/');
            }
        }
    }

    ## --------------------------------------------------------

    public function getLogInOutLink()
    # Show link depending on the users login/logout status
    {
        if ($this->_user) {
          return $this->_facebookObj->getLogoutUrl();
        } else {
          return $this->_facebookObj->getLoginUrl();
        }       
    }

    ## --------------------------------------------------------

    public function isLoggedIn()
    # Test if user is logged in and authenticated
    {
        if ($this->_user) {
            return true;
        } else {
            return false;
        }
    }


    /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 
     *  Facebook Get Info Methods
     *  
     */

    public function getUserProfile()
    #
    #   Author:     Jarrod Oberto
    #   Date:       Jun 11
    #   Purpose:    Get user profile information
    #   Params in:
    #   Params out:
    #   Notes:  
    #
    {   
        if ($this->_user) {
            $userProfileArray = $this->_facebookObj->api('/' . $this->_userId);
            return $userProfileArray;
        } else {
            $this->_errorArray[] = 'Could not get user profile. User possibly not logged in.';
            $user = null;
            return false;
        }               
    }       

    ## --------------------------------------------------------

    public function getProfileImageURL()
    #
    #   Author:     Jarrod Oberto
    #   Date:       Jun 11
    #   Purpose:    Get the profile image URL
    #   Params in:
    #   Params out:
    #   Notes:  
    #
    {
        if ($this->_user) {
            try {
                return 'http://graph.facebook.com/' . $this->_userId . '/picture';
            } catch (FacebookApiException $e) {
                $this->_errorArray[] = 'Could not get profile image URL.';
                $this->_debugArray[] = $e;
                return false;
            }           
        }   
    }

    ## --------------------------------------------------------

    public function getAlbumNames($includeProfileAlbum = false)
    #
    #   Author:     Jarrod Oberto
    #   Date:       June 11
    #   Purpose:    Get an array of album names
    #   Params in:  (bool) $includeProfileAlbum: if set to true, the users profile pictures album will be returned, too.
    #   Params out: (array) Associate array of album id's / names
    #   Notes:  
    #
    {
        // *** Get album data
        $albumsData = $this->_getAlbumData();

        $albumNamesArray = array();

        if (count($albumsData['data']) > 0) {

            // *** Loop through album data
            foreach ($albumsData['data'] as $album) {

                // *** Test if we want to include the Profile Pictures album
                if (($includeProfileAlbum || strtolower($album['name']) != 'profile pictures')) {

                    $albumNamesArray[$album['id']] = $album['name'];
                }
            }
        }

        return $albumNamesArray;
    }

    ## --------------------------------------------------------

    public function getAlbumId($albumName)
    #
    #   Author:     Jarrod Oberto
    #   Date:       June 11
    #   Purpose:    Get the id of an album
    #   Params in:  (str) $albumName: the name of the album to return the id for.
    #   Params out: Returns an albums id.
    #   Notes:  
    #
    {
        // *** Test if already an id
        if ($this->_testIfId($albumName)) {
            return $albumName;
        }

        $id = 0;

        // *** Get album names
        $albumNamesArray = $this->getAlbumNames();

        if (count($albumNamesArray) > 0) {

            // *** Loop through each album
            foreach ($albumNamesArray as $albumId => $value) {

                // *** If the name already exists...
                if (strtolower($albumName) == strtolower($value)) {

                    // *** ...return the id
                    return $albumId;
                }
            }
        }   
        return $id;
    }


    /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 
     *  Facebook Update/Add Methods
     *  
     */

    public function addPhoto($img, $caption='', $album='', $albumDescription='', $createAlbum=true)
    #
    #   Author:     Jarrod Oberto
    #   Date:       Jun 11
    #   Purpose:    Add photos to an album on Facebook
    #   Params in:  (str) $img: the image and path to upload
    #               (str) $caption: a caption for the image
    #               (str) $album: an album name or id. Will be created if
    #                   it doesn't exist
    #               (str) $albumDescription: the description to give the album.
    #               (bool) $createAlbum: if true, create the album if it doesn't 
    #                   already exist. If false, if the album doesn't exist,
    #                   don't upload the photo.
    #   Params out:
    #   Notes:  
    #
    {

        // *** Get absolute path
        $img = realpath($img);
        if (!file_exists($img)) {
            $this->_errorArray[] = 'Image cannot be found.';        
            return false;           
        }

        // *** If setting is to NOT create the album should it not exist...
        if (!$createAlbum) {

            // *** Let's make sure it does exist. If album id=0 then it doesn't
            if ($this->getAlbumId($album) == 0) {
                return false;
            }
        }

        // *** Default ("me")
        $obj = $this->_userId;      

        // *** Has an album been specified?
        if ($album != '') {

            // *** Check if we passed in an album id
            $usingAlbumId = $this->_testIfId($album);

            // *** If we've passed in the album id, no need to get it - we already got it!
            if (!$usingAlbumId) {

                // *** Get album id, or create if it doesn't exist
                $albumId = $this->addAlbum($album, $albumDescription);

                // *** Set as album id
                $obj = $albumId;
            } else {
                $obj = $album;
            }
        }

        // *** Enable upload support
        $this->_facebookObj->setFileUploadSupport(true);

        if ($this->_user) {
            try {               
                $photo = $this->_facebookObj->api('/' . $obj . '/photos', 'POST',
                    array(
                        'picture' => '@' . $img,
                        'message' => $caption
                    )
                );
                return $photo['id'];
            } catch (FacebookApiException $e) {
                $this->_errorArray[] = 'Image could not be added.';
                $this->_debugArray[] = $e;      
                return false;
            }
        }           
    }

    ## --------------------------------------------------------

    public function addAlbum($name, $description='', $allowDuplicates=false)
    #
    #   Author:     Jarrod Oberto
    #   Date:       Jun 11
    #   Purpose:    Create an album if it doesn't exist (or if we don't mind 
    #               duplicates).            
    #               If it does exist, just return the id of the album           
    #   Params in:
    #   Params out: (int) the album of the id (regardless if we created it or 
    #                   if it already existed.
    #   Notes:  
    #
    {
        // *** If we don't want duplicate album names...
        if (!$allowDuplicates) {

            // *** ...we check if the album name exists already
            $id = $this->getAlbumId($name);

            // *** An id of greater than 0 means it does already exist
            if ($id > 0) {

                // *** So let leave and return the existing id
                return $id;
            }
        }

        // *** Else create the album if it doesn't exist
        if ($this->_user) {
            try {       
                $album = $this->_facebookObj->api('/' . $this->_userId . '/albums', 'POST', array(
                        'name' => $name,
                        'message' => $description
                    )
                );  
                return $album['id'];
            } catch (FacebookApiException $e) {
                $this->_errorArray[] = 'Album could not be created.';
                $this->_debugArray[] = $e;      
                return false;
            }
        }   
    }

    ## --------------------------------------------------------


    public function getAlbumSelectOptions($selectedId=0, $addBlank=false, $includeProfileAlbum=false)
    {
        $assocArray = $this->getAlbumNames($includeProfileAlbum);
        return Helper::dropdown($assocArray, $selectedId, $addBlank);
    }   


    /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 
     *  Error Handling Methods
     *  
     */

    ## --------------------------------------------------------

    public function getErrors()
    {
        return $this->_errorArray;
    }

    ## --------------------------------------------------------

    public function getError()
    {
        if (isset($this->_errorArray[0])) {
            return  $this->_errorArray[0];
        } else {
            return '';
        }
    }

    ## --------------------------------------------------------

    public function getDebugErrors()
    {
        return $this->_debugArray;
    }


## _____________________________________________________________________________    
## ________                 ____________________________________________________
## ________ PRIVATE METHODS ____________________________________________________
## _____________________________________________________________________________
##  


    private function _getAlbumData()
    #
    #   Author:     Jarrod Oberto
    #   Date:       Jun 11
    #   Purpose:    Get the RAW data
    #   Params in:
    #   Params out:
    #   Notes:  
    #
    {

        if ($this->_user) {
            try {       
                return $this->_facebookObj->api('/' . $this->_userId . '/albums');
            } catch (FacebookApiException $e) {
                $this->_errorArray[] = 'Could not get album data.';
                $this->_debugArray[] = $e;      
                return false;
            }
        }                   
    }   

    ## --------------------------------------------------------

    private function _testIfId($value)
    # helper
    {
        if ((strlen($value) >= 10 && strlen($value) <= 20) && is_numeric($value)) {
            return true;
        } else {
            return false;
        }
    }
    ## --------------------------------------------------------
}



class Helper {

    ## --------------------------------------------------------

    public static function dropdown($assocArray, $selectedId=0, $addBlank=false)
    #
    #   Author:     Jarrod Oberto
    #   Date:       19 Mar 2011
    #   Purpose:    Generate HTML dropdown code
    #   Params in:  (array) $assocArray: An associate array of value (id)/text.
    #               (mixed) $selectedId: The value to select. Usually an id.
    #               (bool)  $addBlank: First entry empty or not.
    #   Params out: The select HTML code
    #   Notes:
    #
    #   Usage:
    #           PHP:    $resultSet = $dbObj -> selectTable('branch', array('id','name'));
    #                   $branchArray = $dbObj -> recordsToArray($resultSet, false, true);
    #                   $branchHTMLOptions = FormHelper::dropdown($branchArray, $id);
    #
    #           HTML:   <select id="branch" name="branch" class="text">
    #                       <?php echo $branchHTMLOptions ? >
    #                   </select>
    #
    {

        $HTMLOptions = '';
        if ($assocArray) {

            if ($addBlank) {
                $HTMLOptions = '<option></option>';
            }

            foreach ($assocArray as $id => $name) {
                $selected = '';
                if (($selectedId == $id) && ($selectedId != '')){
                    $selected = 'selected="selected"';
                }
                $HTMLOptions .= '<option value="' . $id . '" ' . $selected . '>' . $name . '</option>';
            }
        } else {
            $HTMLOptions = '<option></option>';
        }

        return $HTMLOptions;

    }

    ## -------------------------------------------------------- 

}
?>
4

1 に答える 1