Plugin Directory

Changeset 492339


Ignore:
Timestamp:
01/19/2012 09:04:31 PM (14 years ago)
Author:
smartfin
Message:

Debug mode

Location:
ssi-sumilux/trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • ssi-sumilux/trunk/readme.txt

    r490793 r492339  
    77Stable tag: 0.5
    88
    9 Here is a short description of the plugin.  This should be no more than 150 characters.  No markup here.
     9Social Sign-In solution, allowing your WordPress site to accept users signing in with their social identities such as their Google, Yahoo, Facebook, Twitter accounts.
    1010
    1111== Description ==
    1212
    13 This is the long description.  No limit, and you can use Markdown (as well as in the following sections).
     13If you ever feel that it's too much a hassle to have your users register before they can do anything on your web site, such as leaving a comment, or interact with any other plug-ins that need user identities, we have a solution for you.
    1414
    15 For backwards compatibility, if this section is missing, the full length of the short description will be used, and
    16 Markdown parsed.
     15 The Sumilux Social Sign-In (SSI) WordPress plugin allows your to accept users signing in using their social network accounts (such as those with Google, Yahoo, Facebook, Twitter, etc.)
    1716
    18 A few notes about the sections above:
    19 
    20 *   "Contributors" is a comma separated list of wp.org/wp-plugins.org usernames
    21 *   "Tags" is a comma separated list of tags that apply to the plugin
    22 *   "Requires at least" is the lowest version that the plugin will work on
    23 *   "Tested up to" is the highest version that you've *successfully used to test the plugin*. Note that it might work on
    24 higher versions... this is just the highest one you've verified.
    25 *   Stable tag should indicate the Subversion "tag" of the latest stable version, or "trunk," if you use `/trunk/` for
    26 stable.
    27 
    28     Note that the `readme.txt` of the stable tag is the one that is considered the defining one for the plugin, so
    29 if the `/trunk/readme.txt` file says that the stable tag is `4.3`, then it is `/tags/4.3/readme.txt` that'll be used
    30 for displaying information about the plugin.  In this situation, the only thing considered from the trunk `readme.txt`
    31 is the stable tag pointer.  Thus, if you develop in trunk, you can update the trunk `readme.txt` to reflect changes in
    32 your in-development version, without having that information incorrectly disclosed about the current stable version
    33 that lacks those changes -- as long as the trunk's `readme.txt` points to the correct stable tag.
    34 
    35     If no stable tag is provided, it is assumed that trunk is stable, but you should specify "trunk" if that's where
    36 you put the stable version, in order to eliminate any doubt.
     17 It takes only a few minutes to set it up, give it a try!
    3718
    3819== Installation ==
    3920
    40 This section describes how to install the plugin and get it working.
    4121
    42 e.g.
    4322
    44231. Copy the `ssi` directory and its contents to your `/wp-content/plugins/` directory.
  • ssi-sumilux/trunk/ssi.php

    r490793 r492339  
    1414define('SSI_TEMPLATES_DIR', SSI_DIR . 'templates/');
    1515
    16 define('ENDPOINT', "http://social-sign-in.com/smx");
    17 define('APPKEY', get_option('ssi_app_key'));
    18 define('APPSECRET', get_option('ssi_app_secret'));
    19 define('APPNAME', get_option('ssi_widget_name'));
    20 define('WIDGETNAME', get_option('ssi_widget_name'));
     16
     17define('DEBUG', get_option("ssi_debug_mode"));
     18
     19if (DEBUG){
     20    define('APPKEY', get_option('ssi_debug_app_key'));
     21        define('APPSECRET', get_option('ssi_debug_app_secret'));
     22        define('APPNAME', get_option('ssi_debug_widget_name'));
     23        define('WIDGETNAME', get_option('ssi_debug_widget_name'));
     24} else {
     25    define('APPKEY', get_option('ssi_app_key'));
     26        define('APPSECRET', get_option('ssi_app_secret'));
     27        define('APPNAME', get_option('ssi_widget_name'));
     28        define('WIDGETNAME', get_option('ssi_widget_name'));
     29}
     30
     31define('ENDPOINT', "https://social-sign-in.com/smx");
     32define('ENDPOINT_DEBUG', "http://demo.sumilux.com/smx");
     33
    2134
    2235require_once SSI_DIR . 'SsiUser.php';
     
    7790            "std" => "",
    7891            "type" => "text"),
     92
     93        array("name" => "Debug mode",
     94                    "desc" => "Check it if you want to turn debug mode on",
     95                    "id" => $shortname . "_debug_mode",
     96                    "std" => "",
     97                    "type" => "checkbox"),
     98        array("name" => "Debug Widget name secret",
     99            "desc" => "Debug Widget name here",
     100            "id" => $shortname . "_widget_name",
     101            "std" => "",
     102            "type" => "text"),
     103        array("name" => "Debug App key",
     104            "desc" => "Put Debug App key here",
     105            "id" => $shortname . "_debug_app_key",
     106            "std" => "",
     107            "type" => "text"),
     108        array("name" => "Debug App secret",
     109            "desc" => "Put Debug App secret here",
     110            "id" => $shortname . "_debug_app_secret",
     111            "std" => "",
     112            "type" => "text"),
     113
    79114        array("name" => "Language",
    80                     "desc" => "Choose plugin language",
    81                     "id" => $shortname . "_lang",
    82                     "std" => "",
    83                     "type" => "select"),
     115            "desc" => "Choose plugin language",
     116            "id" => $shortname . "_lang",
     117            "std" => "",
     118            "type" => "select"),
    84119        /*array("name" => "App name",
    85120            "desc" => "Put app name here",
     
    198233                }
    199234            }
    200              wp_safe_redirect("/");
     235            wp_safe_redirect("/");
    201236
    202237
     
    226261    );
    227262        */
    228     $site_url = site_url().'/wp-login.php';
    229 
    230     $html_header_block = Services_Sumilux_SSI::generateCode(
    231         WIDGETNAME, // widget name
    232         APPKEY, // app key
    233         APPSECRET, // app secret
    234         'popup-header',
    235          $site_url
    236     );
     263    $site_url = site_url() . '/wp-login.php';
     264
     265    if (DEBUG){
     266        Services_Sumilux_SSI::setEndpoint("http://idmedemo.sumilux.com/smx/rpcService/xmlRpcService");
     267    }
     268
     269
    237270    $html_block = Services_Sumilux_SSI::generateCode(
    238271        WIDGETNAME, // widget name
    239272        APPKEY, // app key
    240273        APPSECRET, // app secret
    241         'popup-body',
     274        'small-icon',
     275        'Sign-in',
    242276        $site_url
    243277    );
    244278
    245     $html_block = str_replace('Sign-in', 'Sign In with Your Social Identity' , $html_block);
     279    $html_block = str_replace('Sign-in', 'Sign In with Your Social Identity', $html_block);
    246280    // prepare data for template
    247281    $tpl_data = array(
    248282        'url' => $authURL,
    249         'html_block' => $html_block,
    250         'html_header_block' => $html_header_block,
     283        'html_block' => $html_block['html-body-code'],
     284        'html_header_block' => $html_block['html-head-code'],
    251285    );
    252286
     
    349383                                   echo $value['std'];
    350384                               } ?>"
    351                             style="width: 300px;"
     385                               style="width: 300px;"
    352386                        />
    353387
     
    359393                </tr>
    360394                <?php
    361             } elseif ($value['type']== "select"){
    362                 if (get_option($value['id']) != "") { $selected = get_option($value['id']); }
     395            } elseif ($value['type'] == "select") {
     396                if (get_option($value['id']) != "") {
     397                    $selected = get_option($value['id']);
     398                }
    363399                ?>
    364400                <tr valign="top">
    365401
     402                    <th scope="row"><?php echo $value['name']; ?>:</th>
     403
     404                    <td>
     405                        <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
     406                            <option value="1" <?=$selected == 1 ? "selected" : ""?>>English</option>
     407                            <option value="2" <?=$selected == 2 ? "selected" : ""?>>Українська</option>
     408                            <option value="3" <?=$selected == 3 ? "selected" : ""?>>Русский</option>
     409                        </select>
     410                    </td>
     411
     412                </tr>
     413                <?
     414            } elseif ($value['type'] == "checkbox") {
     415                 if( get_option($value['id']) ) {
     416
     417                $checked = "checked=\"checked\"";
     418
     419                } else { $checked = ""; }
     420
     421                ?>
     422                <tr valign="top">
     423
    366424                                    <th scope="row"><?php echo $value['name']; ?>:</th>
    367425
    368426                                    <td>
    369                                         <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
    370                                             <option value="1" <?=$selected==1 ? "selected" : ""?>>English</option>
    371                                             <option value="2" <?=$selected==2 ? "selected" : ""?>>Українська</option>
    372                                             <option value="3" <?=$selected==3 ? "selected" : ""?>>Русский</option>
    373                                         </select>
     427                                        <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true"
     428                                        <?php echo $checked; ?> />
    374429                                    </td>
    375430
  • ssi-sumilux/trunk/ssi/vendor/ssi-client-php/Services_Sumilux_SSI.php

    r490793 r492339  
    22
    33
    4 /**
     4/**     
    55 * Services_Sumilux_SSI, a PHP5 API for accessing the Sumilux
    66 * Social Sign-In (SSI) Service.
    7  *
     7 *       
    88 * PHP version 5
    9  *
     9 *       
    1010 * LICENSE:
    11  *
    12  * Copyright (c) 2011, Sumilux Technologies, LLC
     11 *       
     12 * Copyright (c) 2011, Sumilux Technologies, LLC 
    1313 * All rights reserved.
    14  *
    15  * Redistribution and use in source and binary forms, with or without
     14 *       
     15 * Redistribution and use in source and binary forms, with or without 
    1616 * modification, are permitted provided that the following conditions
    1717 * are met:
    18  *
     18 *       
    1919 *  * Redistributions of source code must retain the above copyright
    2020 *    notice, this list of conditions and the following disclaimer.
     
    2222 *    notice, this list of conditions and the following disclaimer in
    2323 *    the documentation and/or other materials provided with the distribution.
    24  *
     24 *       
    2525 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    2626 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     
    3232 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    3333 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    36  *
     34 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
     35 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
     36 *       
    3737 * @category  Services
    3838 * @package   Services_Sumilux_SSI
    3939 * @author    Steven Li <[email protected]>
    40  * @copyright 2011 Sumilux Technologies, LLC
     40 * @copyright 2011 Sumilux Technologies, LLC 
    4141 * @license   http://www.opensource.org/licenses/bsd-license.php BSD
    4242 * @version   SVN: $Id$
    4343 * @link      http://pear.sumilux.com/
    4444 * @link      http://www.sumilux.com/ssi/
    45  *
    46  */
     45 * 
     46 */ 
    4747
    4848
    4949
    5050/**
    51  * This is the main class providing the Sumilux SSI functions.
    52  *
     51 * This is the main class providing the Sumilux SSI functions. 
     52 * 
    5353 * @package Services_Sumilux_SSI
    5454 */
    5555
    56 class Services_Sumilux_SSI
     56class Services_Sumilux_SSI 
    5757{
    58     private $appName;
    59     private $appSecret;
    60     private static $endpoint = "https://social-sign-in.com/smx";
    61 
    62     //---------- Constants ----------
    63     Const TOKEN_NAME_IN_SESSION = 'smxSessionToken';
    64 
    65     //---------- Constructor ---------
    66     /**
    67      * Constructor of the service object, you will need the "application name"
    68      * and "application secret", as generated from the main SSI site:
    69      * http://www.sumilux.com/ssi
    70      *
    71      * @param $appName
    72      * @param $appSecret
    73      */
    74     public function __construct($appName, $appSecret) {
    75         $this->appName   = $appName;
    76         $this->appSecret = $appSecret;
    77     }
    78 
    79     //---------- Private Functions ----------
    80 
    81     private function getRpcEndPoint($svcName) {
    82         return $this->getEndPoint() . '/rpcService/xmlRpcService';
    83     }
    84 
    85     // Please keep this method available from outside (public), so that ssi-website can use it.
    86     public function callRpc($serviceName, $method, $params_array)
    87     {
    88         $rpcEndPoint = $this->getRpcEndPoint($serviceName);
    89         $rpcMethod = $serviceName . "." . $method; // convention: "idme.add"
    90         $request = xmlrpc_encode_request($rpcMethod, $params_array); // RPC request ready, now where to?
    91 
    92         // $url = ConfigManager::getRpcServiceEndPoint($serviceName); // RPC End Point, a URL basically
    93         $header[] = "Content-type: text/xml";
    94         $header[] = "Content-length: ".strlen($request);
    95 
    96         $ch = curl_init();
    97         curl_setopt($ch, CURLOPT_URL, $rpcEndPoint);
    98         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    99         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    100         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    101         curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    102         // if (isset($_SERVER['HTTPS'])) {
    103         if ( strtolower(substr($rpcEndPoint,0,5)) == 'https' ) {
    104             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    105             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    106         }
    107         $data = curl_exec($ch);
    108         if (curl_errno($ch)) {
    109             //  print "Curl error: " . curl_error($ch);
    110             throw new Exception("XMLRPC failed to complete with $rpcEndPoint. "."Curl error: " . curl_error($ch) .'.');
    111         } else {
    112             curl_close($ch);
    113             // echo "Curl successful <br>" ;
    114             // var_dump($data);
    115             $aret = xmlrpc_decode($data);
    116             if ( is_array($aret) && xmlrpc_is_fault($aret) ) {
    117                 throw new Exception("XMLRPC failed - " . $aret["faultString"], $aret["faultCode"]);
    118             }
    119 
    120             // echo "do_rpc_call() returns: <br>";
    121             // var_dump($aret);
    122 
    123             return $aret;
    124         }
    125     }
    126 
    127     private function callHelper($token,
    128                                 $serviceName, $objectType, $objectID, $methodName, $methodParam)
    129     {
    130         // $sessionToken = PhpLibUtils::fetchSessionToken();
    131 
    132         // return RpcManager::callHelper($sessionToken, $serviceName,
    133         // $objectType, $objectID, $methodName, $methodParam);
    134 
    135         if ( empty($token) )
    136             throw new Exception("RPC call cannot be made without a valid SessionToken", 97);
    137 
    138         $params = array($token, $objectType, $objectID, $methodName, $methodParam);
    139         return $this->callRpc($serviceName, "dispatch", $params); //s pecific XML RPC implementation
    140     }
    141 
    142     //---------- Getter/Setter Functions ----------
    143 
    144     /**
    145      * @ignore
    146      * This is only useful when hooking up with our config manager, skipping in
    147      * for documentation.
    148      */
    149     public function setEndpoint($e) {
    150         // throw new Exception("Cannot set EP");
    151         // echo "<pre>Setting end point: $e</pre>\n";
    152         self::$endpoint = dirname(dirname($e));
    153     } // param is RPC ep
    154 
    155 
    156     /**
    157      *  @ignore
    158      * Used when get endpoint for code viewing of app.
    159      */
    160     public function getEndPoint() { return self::$endpoint; }
    161 
    162 
    163     /**
    164      * Set the access token for the SSI instance. All future interactions with the
    165      * server will be under the context of this token. This is normally done as soon
    166      * as the user signs in.
    167      *
    168      * @param $token
    169      * @throws Exception if PHP session is not enabled before this method is invoked.
    170      */
    171 
    172     public function setToken($token)
    173     {
    174         $sid = session_id();
    175         if ( empty($sid) ) {
    176             throw new Exception("Active PHP session needed to save session token");
    177         }
    178         $_SESSION[self::TOKEN_NAME_IN_SESSION] = $token;
    179     }
    180 
    181     private function getToken()
    182     {
    183         $sid = session_id();
    184         if ( empty($sid) ) {
    185             throw new Exception("Active PHP session needed to fetch session token");
    186         }
    187 
    188         if ( ! array_key_exists(self::TOKEN_NAME_IN_SESSION, $_SESSION) ) // no session entry
    189             return null;
    190 
    191         if ( empty( $_SESSION[self::TOKEN_NAME_IN_SESSION] ) ) // no actual session value
    192             return null;
    193 
    194         return $_SESSION[self::TOKEN_NAME_IN_SESSION];
    195     }
    196 
    197     //---------- Authentication/Log-in Related Functions ----------
    198 
    199     /**
    200      * Retrieve the "authentication URL". The user's browser should be directed to this
    201      * URL, and then it comes back to the "exitURL", it will be through a POST request, and
    202      * that the "token" parameter will contain a valid token as the result of the sign-in
    203      * process.
    204      *
    205      * @param $exitURL The URL to redirect the user after sign-in is completed.
    206      */
    207     public function getAuthURL($exitURL)
    208     {
    209         $sig = md5($exitURL . $this->appSecret); // signature
    210 
    211         $authURL = $this->getEndPoint()
    212             . "/owa?exitURL=" . urlencode($exitURL)
    213             . "&sig={$sig}&appName={$this->appName}";
    214         return $authURL;
    215     }
    216 
    217     /**
    218      * @ignore
    219      * This should be replaced by a call to BZFE soon.
    220      */
    221     public function getAuthID()
    222     {
    223         $token = $this->getToken();
    224         return $this->callRpc("idme", "getAuthID", array($token));
    225     }
    226 
    227     /**
    228      * Retrieve all the attributes of the current user
    229      *
    230      * @return JSON all attributes in a JSON object
    231      */
    232     public function getAttributes()
    233     {
    234         $token = $this->getToken();
    235         $str = $this->callRpc("idme", "getAttributes", array($token));
    236         return json_decode($str);
    237     }
    238 
    239     /**
    240      * Test is the current user is signed in.
    241      *
    242      * @return Boolean
    243      */
    244     public function isSignedIn()
    245     {
    246         $token = $this->getToken();
    247         return (! empty($token) );
    248     }
    249 
    250     //---------- JQForm Related Functions ------
    251     /**
    252      * Retrieve the JQForm definition of a given object, the result is suitable to feed
    253      * into the JQForm Yii extension, available separately.
    254      *
    255      * @param string $objectClass object type
    256      * @param string $oid object ID
    257      * @return string JQForm definition in text format
    258      */
    259     public function getJqFormDef($objectClass, $oid) // no object id, no parameter
    260     {
    261         $oid = (empty($oid)) ? 'current' : $oid;
    262         return $this->callHelper($this->getToken(), "idme",
    263             $objectClass, $oid, "fetchJQForm", null);
    264     }
    265 
    266     /**
    267      * Posting the JQForm data back to the server, and retrieve the response, suitable
    268      * for display in the JQForm extension.
    269      *
    270      * @param string $objectClass object type
    271      * @param string $oid object ID
    272      * @return string JQForm posting result in text format
    273      */
    274     public function postJqForm($objectClass, $oid=null)
    275     {
    276         // $sessionToken = PhpLibUtils::fetchSessionToken();
    277         $jo = $this->convertPostToJSON();
    278         $jtext = json_encode($jo);
    279         $oid = (empty($oid)) ? 'current' : $oid;
    280         $res = $this->callHelper($this->getToken(), "idme",
    281             $objectClass, $oid, "modifyOrAdd", $jtext);
    282         return $res;
    283     }
    284 
    285     /**
    286      * Converts all the parameters in the $_POST array into a JSON object, to facilitate
    287      * later invokcation of server methods.
    288      *
    289      * @return the resulting JSON object (not JSON string)
    290      */
    291     private function convertPostToJSON() // duplicated from Model class in shared.php
    292     {
    293         $ret =  array(); // for JSON converstion sake, convert to object at the end!
    294         foreach($_POST as $pkey => $pval) {
    295             $keys = explode('_', $pkey, 5);
    296             $levels = count($keys);
    297             if ( $levels == 1 ) { // clear to separate it out
    298                 $ret[$pkey] = $pval;
    299             }
    300             else {
    301                 $aref = &$ret; // pass by ref, seeding the loop
    302                 for( $i=0; $i<$levels; $i++) { //
    303                     $thisKey = $keys[$i];
    304 
    305                     if ( $i == ($levels-1) ) { // last one
    306                         $aref[$thisKey] = $pval; // actual value
    307                     }
    308                     else  { // intermediate one
    309                         if ( isset ($aref[$thisKey]) ) { // already set
    310                             // do nothing
    311                         }
    312                         else {
    313                             $aref[$thisKey] = array(); // create an empty array
    314                         }
    315                         $aref = &$aref[$thisKey]; // since it's already set
    316                     }
    317                 }
    318             }
    319         }
    320         return (object) $ret;
    321     }
    322 
    323     //---------- Role Related Functiosn ----------
    324 
    325     /**
    326      * Retrieve all of the roles defined for the current organization (defined
    327      * as the "default organization" or the current user).
    328      *
    329      * @return JSON all roles in a JSON object
    330      */
     58    private $appName;
     59    private $appSecret;
     60    private static $endpoint = "https://social-sign-in.com/smx";
     61   
     62    //---------- Constants ----------
     63    Const TOKEN_NAME_IN_SESSION = 'smxSessionToken';
     64   
     65    //---------- Constructor ---------
     66    /**
     67     * Constructor of the service object, you will need the "application name"
     68     * and "application secret", as generated from the main SSI site:
     69     * http://www.sumilux.com/ssi
     70     *
     71     * @param $appName
     72     * @param $appSecret
     73     */
     74    public function __construct($appName, $appSecret) {
     75        $this->appName   = $appName;
     76        $this->appSecret = $appSecret;
     77    }
     78   
     79    //---------- Magical methods ----------
     80   
     81    /**
     82     * Implement this method, so we can call IMDE like this:
     83     * <code>
     84     *  $appsecret = $ssi->getAppSecret(array('gnt'), false);
     85     *  // the same as
     86     *  // $appsecret = $ssi->callIDME('getAppSecret', array('gnt'), false);
     87     * </code>
     88     * @param string $method
     89     * @param array $params
     90     * @throws Exception
     91     */
     92    public function __call($method, $params) {
     93        try {
     94            array_unshift($params, $method);
     95            return call_user_func_array(array($this, 'callIDME'), $params);
     96        } catch(Exception $e) {
     97            throw $e;
     98        }
     99    }
     100   
     101    //---------- Private Functions ----------
     102   
     103    private function getRpcEndPoint($svcName) {
     104        return $this->getEndPoint() . '/rpcService/xmlRpcService';
     105    }
     106   
     107    // Please keep this method available from outside (public), so that ssi-website can use it.
     108    public function callRpc($serviceName, $method, $params_array)
     109    {
     110        $rpcEndPoint = $this->getRpcEndPoint($serviceName);
     111        $rpcMethod = $serviceName . "." . $method; // convention: "idme.add"
     112        $request = xmlrpc_encode_request($rpcMethod, $params_array); // RPC request ready, now where to?
     113
     114        // $url = ConfigManager::getRpcServiceEndPoint($serviceName); // RPC End Point, a URL basically
     115        $header[] = "Content-type: text/xml";
     116        $header[] = "Content-length: ".strlen($request);
     117
     118        $ch = curl_init();
     119        curl_setopt($ch, CURLOPT_URL, $rpcEndPoint);
     120        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     121        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     122        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
     123        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
     124        // if (isset($_SERVER['HTTPS'])) {
     125        if ( strtolower(substr($rpcEndPoint,0,5)) == 'https' ) {
     126            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);     
     127            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     128        }
     129        $data = curl_exec($ch);
     130        if (curl_errno($ch)) {
     131        //  print "Curl error: " . curl_error($ch);
     132            throw new Exception("XMLRPC failed to complete with $rpcEndPoint. "."Curl error: " . curl_error($ch) .'.');
     133        } else {
     134            curl_close($ch);
     135            // echo "Curl successful <br>" ;
     136            // var_dump($data);
     137            $aret = xmlrpc_decode($data);
     138            if ( is_array($aret) && xmlrpc_is_fault($aret) ) {
     139                throw new Exception("XMLRPC failed - " . $aret["faultString"], $aret["faultCode"]);
     140            }
     141           
     142            // echo "do_rpc_call() returns: <br>";
     143            // var_dump($aret);
     144           
     145            return $aret;
     146        }
     147    }
     148   
     149    private function callHelper($token,
     150        $serviceName, $objectType, $objectID, $methodName, $methodParam)
     151    {
     152        // $sessionToken = PhpLibUtils::fetchSessionToken();
     153       
     154        // return RpcManager::callHelper($sessionToken, $serviceName,
     155            // $objectType, $objectID, $methodName, $methodParam);
     156           
     157        if ( empty($token) )
     158            throw new Exception("RPC call cannot be made without a valid SessionToken", 97);
     159
     160        $params = array($token, $objectType, $objectID, $methodName, $methodParam);
     161        return $this->callRpc($serviceName, "dispatch", $params); //s pecific XML RPC implementation           
     162    }
     163   
     164    //---------- Getter/Setter Functions ----------
     165   
     166    /**
     167     * @ignore
     168     * This is only useful when hooking up with our config manager, skipping in
     169     * for documentation.
     170     */
     171    public static function setEndpoint($e) {
     172        // throw new Exception("Cannot set EP");
     173        // echo "<pre>Setting end point: $e</pre>\n";
     174        self::$endpoint = dirname(dirname($e));
     175    } // param is RPC ep
     176   
     177   
     178    /**
     179     *  @ignore
     180     * Used when get endpoint for code viewing of app.
     181     */
     182    public function getEndPoint() { return self::$endpoint; }
     183   
     184
     185    /**
     186     * Set the access token for the SSI instance. All future interactions with the
     187     * server will be under the context of this token. This is normally done as soon
     188     * as the user signs in.
     189     *
     190     * @param $token
     191     * @throws Exception if PHP session is not enabled before this method is invoked.
     192     */
     193
     194    public function setToken($token)
     195    {
     196        $sid = session_id();
     197        if ( empty($sid) ) {
     198            throw new Exception("Active PHP session needed to save session token");
     199        }
     200        $_SESSION[self::TOKEN_NAME_IN_SESSION] = $token;
     201    }
     202   
     203    private function getToken()
     204    {
     205        $sid = session_id();
     206        if ( empty($sid) ) {
     207            throw new Exception("Active PHP session needed to fetch session token");
     208        }
     209       
     210        if ( ! array_key_exists(self::TOKEN_NAME_IN_SESSION, $_SESSION) ) // no session entry
     211            return null;
     212           
     213        if ( empty( $_SESSION[self::TOKEN_NAME_IN_SESSION] ) ) // no actual session value
     214            return null;
     215           
     216        return $_SESSION[self::TOKEN_NAME_IN_SESSION];
     217    }
     218   
     219    //---------- Authentication/Log-in Related Functions ----------
     220   
     221    /**
     222     * Retrieve the "authentication URL". The user's browser should be directed to this
     223     * URL, and then it comes back to the "exitURL", it will be through a POST request, and
     224     * that the "token" parameter will contain a valid token as the result of the sign-in
     225     * process.
     226     *
     227     * @param $exitURL The URL to redirect the user after sign-in is completed.
     228     */
     229    public function getAuthURL($exitURL)
     230    {
     231        $sig = md5($this->appSecret); // signature
     232       
     233        $authURL = $this->getEndPoint()
     234            . "/owa?exitURL=" . urlencode($exitURL)
     235            . "&sig={$sig}&appName={$this->appName}";
     236        return $authURL;
     237    }
     238   
     239    /**
     240     * @ignore
     241     * This should be replaced by a call to BZFE soon.
     242     */
     243    public function getAuthID()
     244    {
     245        $token = $this->getToken();
     246        return $this->callRpc("idme", "getAuthID", array($token));
     247    }
     248   
     249    /**
     250     * Retrieve all the attributes of the current user
     251     *
     252     * @return JSON all attributes in a JSON object
     253     */
     254    public function getAttributes()
     255    {
     256        $token = $this->getToken();
     257        $str = $this->callRpc("idme", "getAttributes", array($token));
     258        return json_decode($str);
     259    }
     260   
     261    /**
     262     * Test is the current user is signed in.
     263     *
     264     * @return Boolean
     265     */
     266    public function isSignedIn()
     267    {
     268        $token = $this->getToken();
     269        return (! empty($token) );
     270    }
     271   
     272    //---------- JQForm Related Functions ------
     273    /**
     274     * Retrieve the JQForm definition of a given object, the result is suitable to feed
     275     * into the JQForm Yii extension, available separately.
     276     *
     277     * @param string $objectClass object type
     278     * @param string $oid object ID
     279     * @return string JQForm definition in text format
     280     */
     281    public function getJqFormDef($objectClass, $oid) // no object id, no parameter
     282    {
     283        $oid = (empty($oid)) ? 'current' : $oid;
     284        return $this->callHelper($this->getToken(), "idme",
     285            $objectClass, $oid, "fetchJQForm", null);
     286    }
     287   
     288    /**
     289     * Posting the JQForm data back to the server, and retrieve the response, suitable
     290     * for display in the JQForm extension.
     291     *
     292     * @param string $objectClass object type
     293     * @param string $oid object ID
     294     * @return string JQForm posting result in text format
     295     */
     296    public function postJqForm($objectClass, $oid=null)
     297    {
     298        // $sessionToken = PhpLibUtils::fetchSessionToken();
     299        $jo = $this->convertPostToJSON();
     300        $jtext = json_encode($jo);
     301        $oid = (empty($oid)) ? 'current' : $oid;
     302        $res = $this->callHelper($this->getToken(), "idme",
     303            $objectClass, $oid, "modifyOrAdd", $jtext);
     304        return $res;
     305    }
     306   
     307    /**
     308     * Converts all the parameters in the $_POST array into a JSON object, to facilitate
     309     * later invokcation of server methods.
     310     *
     311     * @return the resulting JSON object (not JSON string)
     312     */
     313    private function convertPostToJSON() // duplicated from Model class in shared.php
     314    {
     315        $ret =  array(); // for JSON converstion sake, convert to object at the end!
     316        foreach($_POST as $pkey => $pval) {
     317            $keys = explode('_', $pkey, 5);
     318            $levels = count($keys);
     319            if ( $levels == 1 ) { // clear to separate it out
     320                $ret[$pkey] = $pval;
     321            }
     322            else {
     323              $aref = &$ret; // pass by ref, seeding the loop
     324              for( $i=0; $i<$levels; $i++) { //
     325                $thisKey = $keys[$i];
     326               
     327                if ( $i == ($levels-1) ) { // last one
     328                    $aref[$thisKey] = $pval; // actual value
     329                }
     330                else  { // intermediate one
     331                    if ( isset ($aref[$thisKey]) ) { // already set
     332                        // do nothing
     333                    }
     334                    else {
     335                        $aref[$thisKey] = array(); // create an empty array
     336                    }
     337                    $aref = &$aref[$thisKey]; // since it's already set                 
     338                }
     339              }
     340            }
     341        }
     342        return (object) $ret;
     343    }
     344   
     345    //---------- Role Related Functiosn ----------
     346
     347    /**
     348     * Retrieve all of the roles defined for the current organization (defined
     349     * as the "default organization" or the current user).
     350     *
     351     * @return JSON all roles in a JSON object
     352     */
    331353    public function getOrgAllRoles()
    332354    {
    333         $jt = $this->callHelper($this->getToken(), 'idme',
     355        $jt = $this->callHelper($this->getToken(), 'idme',
    334356            "Org", "current", "getAllRoles", null);
    335357
    336358        return json_decode($jt);
    337359    }
    338 
     360   
    339361    /**
    340362     * Retrieve all the roles a user has with his/her default organization. This function
    341363     * call can only be successful if two conditions are met: 1. The current user is an
    342      * ADMINISTRATOR of his/her default organization, and 2. the user in question
     364     * ADMINISTRATOR of his/her default organization, and 2. the user in question 
    343365     * (identified by uid) is a member of the organization. Otherwise an exception will
    344366     * be thrown.
    345      *
     367     * 
    346368     * @param $uid The ID of the user, for whom roles are to be retrieved.
    347369     * @throws Exception, see conditions in description above.
    348370     */
    349     public function getUserRoles($uid)
     371    public function getUserRoles($uid)
     372    {
     373        $token = $this->getToken();
     374        if ( empty($token) )
     375            throw new Exception("RPC call cannot be made without a valid SessionToken");
     376
     377        $jt = $this->callRpc("idme", "dispatchOrgUser",
     378            array($token, "getRoles", $uid, null));
     379        return json_decode($jt);
     380    }
     381
     382    /**
     383     * Add a role for a given user in the user's default organization.
     384     *
     385     * @return void
     386     */
     387    public function addUserRole($uid, $role)
     388    {
     389        /*
     390        $jt = $this->callHelper($this->getToken(), 'bzfe',
     391            "Org", $oid, "getOrgUser", $uid);
     392        $ouid = json_decode($jt);
     393       
     394        $this->callHelper($this->getToken(), 'bzfe',
     395            "OrgUser", $ouid, "addRole", $role);
     396        */
     397       
     398        $token = $this->getToken();
     399        if ( empty($token) )
     400            throw new Exception("RPC call cannot be made without a valid SessionToken");
     401
     402        return $this->callRpc("idme", "dispatchOrgUser",
     403            array($token, 'addRole', $uid, $role));                 
     404    }
     405   
     406    /**
     407     * Remove a role for a user in the user's default organization.
     408     * @param String $uid UserID
     409     * @param String $role Role Name
     410     * @return void
     411     */
     412    public function removeUserRole($uid, $role)
     413    {
     414        $token = $this->getToken();
     415        if ( empty($token) )
     416            throw new Exception("RPC call cannot be made without a valid SessionToken");
     417
     418        return $this->callRpc("idme", "dispatchOrgUser",
     419            array($token, 'removeRole', $uid, $role));
     420    }
     421   
     422   
     423    //---------- Other Functions ----------
     424
     425    /**
     426     * Retrieve a user's profile. Condition: ???
     427     *
     428     * @param $uid
     429     */
     430    public function getUserProfile($uid)
     431    {
     432        $jt = $this->callHelper($this->getToken(), 'idme',
     433            "UserProfile", $uid, "fetchObject", null);
     434        return json_decode($jt);
     435    }
     436
     437   
     438    /**
     439     * Creating an empty organization for the current user, setting him/her as the Administrator.
     440     *
     441     * @return void
     442     */
     443    public function createEmptyOrg()
     444    {
     445        $this->callHelper($this->getToken(), 'idme',
     446            "User", "current", "createEmptyOrg", null);
     447    }
     448   
     449    /**
     450     * Retrieve a list of all the organizations in the system.
     451     *
     452     * @return JSON JSON array all organizations
     453     */
     454    public function getAllOrgs()
     455    {
     456        $jt = $this->callHelper($this->getToken(), 'idme',
     457            "Org", null, "fetchAll", null);
     458        return json_decode($jt);
     459    }
     460   
     461    /**
     462     * Retrieve the list of all the organizations that matches the name.
     463     *
     464     * @param string $orgName
     465     * @return JSON JSON array all matched organizations
     466     */
     467    public function getOrgByName($orgName){
     468        $jt = $this->callHelper($this->getToken(), 'idme',
     469            "Org", null, "fetchOrgByName", $orgName);
     470        return json_decode($jt);
     471       
     472    }
     473   
     474    /**
     475     * Retrieve the list of all the organizations that the user has been in.
     476     *
     477     * @param string $userID
     478     * @return JSON JSON array all related organizations
     479     */
     480    public function getOrgsByUserId($userID){
     481        $jt = $this->callHelper($this->getToken(), 'idme',
     482            'OrgUser', null, 'fetchOrgListByUserID', $userID);
     483        return json_decode($jt);
     484    }
     485   
     486   
     487    /**
     488     * Retrieve the list of all the users in the curent user's default organization.
     489     *
     490     * @return JSON JSON array of all "OrgUser" objects in the current org (i.e. current user's default org)
     491     */
     492    public function getAllUsers()
     493    {
     494        $jt = $this->callHelper($this->getToken(), 'idme',
     495            "OrgUser", "current", "fetchAllUsers", null);
     496        return json_decode($jt);
     497    }
     498   
     499    /**
     500     * @ignore
     501     */
     502    public function getAllOrgUsers()
     503    {
     504        $jt = $this->callHelper($this->getToken(), 'idme',
     505            "OrgUser", "current", "fetchAllOrgUsers", null);
     506        return json_decode($jt);
     507    }
     508   
     509
     510    /**
     511     * @ignore
     512     * Seems like bad function below, anyone still using it?
     513     */
     514    public function getAllOrgUsersById()
    350515    {
    351         $token = $this->getToken();
    352         if ( empty($token) )
    353             throw new Exception("RPC call cannot be made without a valid SessionToken");
    354 
    355         $jt = $this->callRpc("idme", "dispatchOrgUser",
    356             array($token, "getRoles", $uid, null));
     516        throw new Exception("Obsolete method??"); // this seems like a weird method.
     517       
     518        $jt = $this->callHelper($this->getToken(), 'idme',
     519            "OrgUser", "current", "fetchObject", null);
     520
    357521        return json_decode($jt);
    358522    }
    359523
    360     /**
    361      * Add a role for a given user in the user's default organization.
    362      *
    363      * @return void
    364      */
    365     public function addUserRole($uid, $role)
    366     {
    367         /*
    368           $jt = $this->callHelper($this->getToken(), 'bzfe',
    369               "Org", $oid, "getOrgUser", $uid);
    370           $ouid = json_decode($jt);
    371 
    372           $this->callHelper($this->getToken(), 'bzfe',
    373               "OrgUser", $ouid, "addRole", $role);
    374           */
    375 
    376         $token = $this->getToken();
    377         if ( empty($token) )
    378             throw new Exception("RPC call cannot be made without a valid SessionToken");
    379 
    380         return $this->callRpc("idme", "dispatchOrgUser",
    381             array($token, 'addRole', $uid, $role));
    382     }
    383 
    384     /**
    385      * Remove a role for a user in the user's default organization.
    386      * @param String $uid UserID
    387      * @param String $role Role Name
    388      * @return void
    389      */
    390     public function removeUserRole($uid, $role)
    391     {
    392         $token = $this->getToken();
    393         if ( empty($token) )
    394             throw new Exception("RPC call cannot be made without a valid SessionToken");
    395 
    396         return $this->callRpc("idme", "dispatchOrgUser",
    397             array($token, 'removeRole', $uid, $role));
    398     }
    399 
    400 
    401     //---------- Other Functions ----------
    402 
    403     /**
    404      * Retrieve a user's profile. Condition: ???
    405      *
    406      * @param $uid
    407      */
    408     public function getUserProfile($uid)
    409     {
    410         $jt = $this->callHelper($this->getToken(), 'idme',
    411             "UserProfile", $uid, "fetchObject", null);
    412         return json_decode($jt);
    413     }
    414 
    415 
    416     /**
    417      * Creating an empty organization for the current user, setting him/her as the Administrator.
    418      *
    419      * @return void
    420      */
    421     public function createEmptyOrg()
    422     {
    423         $this->callHelper($this->getToken(), 'idme',
    424             "User", "current", "createEmptyOrg", null);
    425     }
    426 
    427     /**
    428      * Retrieve a list of all the organizations in the system.
    429      *
    430      * @return JSON JSON array all organizations
    431      */
    432     public function getAllOrgs()
    433     {
    434         $jt = $this->callHelper($this->getToken(), 'idme',
    435             "Org", null, "fetchAll", null);
    436         return json_decode($jt);
    437     }
    438 
    439     /**
    440      * Retrieve the list of all the users in the curent user's default organization.
    441      *
    442      * @return JSON JSON array of all "OrgUser" objects in the current org (i.e. current user's default org)
    443      */
    444     public function getAllUsers()
    445     {
    446         $jt = $this->callHelper($this->getToken(), 'idme',
    447             "OrgUser", "current", "fetchAllUsers", null);
    448         return json_decode($jt);
    449     }
    450 
    451     /**
    452      * @ignore
    453      */
    454     public function getAllOrgUsers()
    455     {
    456         $jt = $this->callHelper($this->getToken(), 'idme',
    457             "OrgUser", "current", "fetchAllOrgUsers", null);
    458         return json_decode($jt);
    459     }
    460 
    461 
    462     /**
    463      * @ignore
    464      * Seems like bad function below, anyone still using it?
    465      */
    466     public function getAllOrgUsersById()
    467     {
    468         throw new Exception("Obsolete method??"); // this seems like a weird method.
    469 
    470         $jt = $this->callHelper($this->getToken(), 'idme',
    471             "OrgUser", "current", "fetchObject", null);
    472 
    473         return json_decode($jt);
    474     }
    475 
    476     /**
    477      * Retrieve the current user's profile.
    478      *
    479      * @return Object The current user's profile
    480      */
    481     /*
    482      public static function getUserProfile()
    483      {
    484          $jt = RpcManager::callHelperXt(self::$svcName, "UserProfile", "current", "fetchObject", null);
    485          return json_decode($jt);
    486      }
    487      */
    488 
    489     /**
    490      * Retrieve the "OrgUser" object for the current user, in the context of his/her default organization
    491      *
    492      * @return Object The "OrgUser" object for the current user in his/her default org.
    493 
    494     public function getOrgUser()
    495     {
    496     $jt = $this->callHelper($this->getToken(), 'bzfe',
    497     "OrgUser", "current", "fetchObject", null);
    498     return json_decode($jt);
    499     }
    500      */
     524    /**
     525     * Retrieve the current user's profile.
     526     *
     527     * @return Object The current user's profile
     528     */
     529    /*
     530    public static function getUserProfile()
     531    {
     532        $jt = RpcManager::callHelperXt(self::$svcName, "UserProfile", "current", "fetchObject", null);
     533        return json_decode($jt);
     534    }
     535    */
     536   
     537    /**
     538     * Retrieve the "OrgUser" object for the current user, in the context of his/her default organization
     539     *
     540     * @return Object The "OrgUser" object for the current user in his/her default org.
     541
     542     public function getOrgUser()
     543     {
     544        $jt = $this->callHelper($this->getToken(), 'bzfe',
     545        "OrgUser", "current", "fetchObject", null);
     546        return json_decode($jt);
     547        }
     548        */
    501549
    502550    /**
    503551     * Retrieve the JQForm representation of the current user's profile, suitable to support
    504552     * the JQForm UI component.
    505      *
    506     * @return JSON JSON text representing the form definition.
    507     */
    508     public function getUserProfileFormDefinition()
    509     {
    510         return $this->callHelper($this->getToken(), 'idme',
    511             "UserProfile", "current", "fetchJQForm", null);
    512     }
    513 
    514 
    515 
    516     /**
    517     * Retrieve the "Org" object for an ORG with a certain ID.
    518      *
    519     * @param $oid the ID of the Org.
    520     * @return Object The "Org" object for the organization with ID
    521     */
    522     public function getOrgFormDefinition($oid)
    523     {
    524         return $this->callHelper($this->getToken(), 'idme',
    525             "Org", $oid, "fetchJQForm", null);
    526     }
     553     *
     554    * @return JSON JSON text representing the form definition.
     555    */
     556    public function getUserProfileFormDefinition()
     557    {
     558        return $this->callHelper($this->getToken(), 'idme',
     559            "UserProfile", "current", "fetchJQForm", null);
     560    }
     561   
     562
     563   
     564    /**
     565    * Retrieve the "Org" object for an ORG with a certain ID.
     566     *
     567    * @param $oid the ID of the Org.
     568    * @return Object The "Org" object for the organization with ID
     569    */
     570    public function getOrgFormDefinition($oid)
     571    {
     572        return $this->callHelper($this->getToken(), 'idme',
     573            "Org", $oid, "fetchJQForm", null);
     574    }
    527575
    528576
     
    534582     */
    535583
    536     public function getOrg($oid)
    537     {
     584  public function getOrg($oid){
    538585        $jt = $this->callHelper($this->getToken(), 'idme',
    539586            "Org", $oid, "fetchObject", null);
    540587        return json_decode($jt);
    541588    }
    542 
    543 
    544 
    545     /*
    546      public static function getAllUserCredentials()
    547      {
    548          $userID = "current";
    549          $ret = RpcManager::callHelperXt(self::$svcName, "UserCredential", $userID, "fetchAllUserCredentials", null);
    550          return json_decode($ret);
    551      }
     589   
     590
     591    /**
     592     * Get user's avatar information
     593     * @param string $uid   the user ID, 'current' for current signed user
     594     * @param boolean $returnBinary     if true, return binary data rather than base64 encoded data
     595     * @return mixed        if no image data, return null; else return base64-encoded string or binary data
    552596     */
    553 
    554     /**
    555      * Set the default organization for the current user
    556      * @param String $orgID Organization ID
    557      * @return void
    558      */
    559     public function setDefaultOrg($orgID)
    560     {
    561         $userID = "current"; // special value, kind of a hack, for now.
    562         $this->callHelper($this->getToken(), 'idme',
    563             "User", $userID, "setDefaultOrg", $orgID);
     597  public function getUserAvatar($uid, $returnBinary=false){
     598   
     599        $userProfile = $this->getUserProfile($uid);
     600       
     601        $data = $userProfile->userImage->image;
     602        if (empty($data)) {
     603            return null;
     604        }
     605       
     606        if ($returnBinary) {
     607            $decoded = "";
     608            for ($i=0, $j = ceil(strlen($data)/256); $i<$j; $i++) {
     609            $decoded = $decoded . base64_decode(substr($data, $i*256, 256));
     610            }
     611            return $decoded;
     612        } else {
     613            return $data;
     614        }
     615       
    564616    }
    565 
    566 
    567     /**
    568      * This method allows idme service to be called outside.
    569      *
    570      * @ignore Only used by ssi-website
    571      * @param string $method
    572      * @param array $param_array
    573      * @param boolean $withToken        if set to true, the param array will be unshifted with token
    574      * @throws Exception
    575      */
    576     public function callIdme($method, $param_array, $withToken=true) {
    577         if (!is_string($method)) {
    578             throw new Exception(__METHOD__.' expects Parameter 1 to be string, '.gettype($method).' given.');
    579         }
    580         if (!is_array($param_array)) {
    581             throw new Exception(__METHOD__.' expects Parameter 2 to be array, '.gettype($param_array).' given.');
    582         }
    583         try{
    584             if ($withToken) {
    585                 $token = $this->getToken();
    586                 if (empty($token)) {
    587                     throw new Exception("RPC call cannot be made without a valid SessionToken", 97);
    588                 }
    589                 array_unshift($param_array, $token);
    590             }
    591             return $this->callRpc('idme', $method, $param_array);
    592         }catch(Exception $e){
    593             throw $e;
    594         }
    595     }
    596 
    597     /**
    598      * This method generates the HTML code snippets for the sign-in widgets,
    599      * to be placed on web pages.
    600      *
    601      * @param string $widgetName Name of the widget
    602      * @param string $codeType The type of the HTML code snippet to be generated,
    603      * valid choices include 'popup-header', 'popup-body', 'embedded-header',
    604      * 'embedded-body', 'link-body', 'link'.
    605      * @param string $siteURL the URL of the web site for the user to be redirected
    606      * back to, default is null.
    607      * @throws Exception when $codeType parameter is invalid
    608      */
    609     public function getCode($widgetName, $codeType, $siteURL=null) {
    610 
    611         $appKey = $this->callIdme('getAppKey', array($widgetName));
    612         $appSecret = $this->callIdme('getAppSecret', array($widgetName));
    613 
    614         return $this->generateCode($widgetName, $appKey, $appSecret, $codeType, $siteURL);
    615 
    616     }
    617 
    618 
    619     /**
    620      * This method generates the HTML code snippets for the sign-in widgets in static context.
    621      *
    622      * @param string $widgetName Name of the widget
    623      * @param string $appKey appKey of the widget
    624      * @param string $appSecret appSecret of the widget
    625      * @param string $codeType The type of the HTML code snippet to be generated,
    626      * valid choices include 'popup-header', 'popup-body', 'embedded-header',
    627      * 'embedded-body', 'link-body', 'link'.
    628      * @throws Exception when $codeType parameter is invalid
    629      */
    630     public static function generateCode($widgetName, $appKey, $appSecret, $codeType, $siteURL=null){
    631 
    632         if ($siteURL==null && ($codeType=='embedded-body' || $codeType == 'popup-body')) {
    633             throw new BadMethodCallException('With second parameter to be "'.$codeType.'", '.__METHOD__.' expect fifth parameter to be a string, none given.');
    634         }
    635 
    636         $owaSrc = self::$endpoint . '/owa'; // what if smxcore exists?
    637         $authSrc = "{$owaSrc}/js/app/{$appKey}.js";
    638         $owaSrc = str_ireplace('://', '://'.$widgetName.'.', $owaSrc);
    639         // echo "<pre>owaSrc=$owaSrc</pre>\n";
    640 
    641         $sig = md5($siteURL . $appSecret);
    642         $srcTale = 'exitURL=' . urlencode($siteURL) . "&sig={$sig}";
    643         $sourcePath = 'http://ssi.sumilux.com/ssi/download';
    644         $cssSrc = $sourcePath.'/ssi.css';
    645 
    646         if ( $codeType == 'popup-header') {
    647             $funcJs = $sourcePath.'/popup.js';
    648             $ret = <<<POP_UP_HEADER
     617   
     618    /*
     619    public static function getAllUserCredentials()
     620    {
     621        $userID = "current";
     622        $ret = RpcManager::callHelperXt(self::$svcName, "UserCredential", $userID, "fetchAllUserCredentials", null);
     623        return json_decode($ret);
     624    }
     625    */
     626   
     627    /**
     628     * Set the default organization for the current user
     629     * @param String $orgID Organization ID
     630     * @return void
     631     */
     632    public function setDefaultOrg($orgID)
     633    {
     634        $userID = "current"; // special value, kind of a hack, for now.
     635        $this->callHelper($this->getToken(), 'idme',
     636            "User", $userID, "setDefaultOrg", $orgID);     
     637    }
     638   
     639   
     640    /**
     641     * This method allows idme service to be called outside.
     642     *
     643     * @ignore Only used by ssi-website
     644     * @param string $method
     645     * @param array $param_array       
     646     * @param boolean $withToken        if set to true, the param array will be unshifted with token
     647     * @throws Exception
     648     */
     649    public function callIdme($method, $param_array, $withToken=true) {
     650        if (!is_string($method)) {
     651            throw new Exception(__METHOD__.' expects Parameter 1 to be string, '.gettype($method).' given.');
     652        }
     653        if (!is_array($param_array)) {
     654            throw new Exception(__METHOD__.' expects Parameter 2 to be array, '.gettype($param_array).' given.');
     655        }
     656        try{
     657            if ($withToken) {
     658                $token = $this->getToken();
     659                if (empty($token)) {
     660                    throw new Exception("RPC call cannot be made without a valid SessionToken", 97);
     661                }
     662                array_unshift($param_array, $token);
     663            }
     664            return $this->callRpc('idme', $method, $param_array);
     665        }catch(Exception $e){
     666            Yii::getLogger()->log('Method = '.$method.PHP_EOL.'Parameters = '.print_r($param_array, true), 'error', 'idme.call');
     667            throw $e;
     668        }
     669    }
     670   
     671    /**
     672     * This method generates the HTML code snippets for the sign-in widgets,
     673     * to be placed on web pages.
     674     *
     675     * @param string $widgetName Name of the widget
     676     * @param string $widgetStyle The style of the widget code snippet to be generated,
     677     * valid choices include 'big-icon', 'small-icon', 'text',
     678     * @param string $linkText specifies the text of the link if the style is "text"
     679     * @param string $siteURL the URL of the web site for the user to be redirected
     680     * back to, default is null.
     681     * @throws Exception when $widgetStyle parameter is invalid
     682     */
     683    public function getCode($widgetName, $widgetStyle, $linkText=null, $siteURL=null) {
     684       
     685        $app = json_decode($this->callIdme('getAppDetail', array($widgetName)));
     686        $appKey = $app->appKey;
     687        $appSecret = $app->appSecret;
     688       
     689        return $this->generateCode($widgetName, $appKey, $appSecret, $widgetStyle, $linkText, $siteURL);
     690       
     691    }
     692   
     693   
     694    /**
     695     * This method generates the HTML code snippets for the sign-in widgets in static context.
     696     *
     697     * @param string $widgetName Name of the widget
     698     * @param string $appKey appKey of the widget
     699     * @param string $appSecret appSecret of the widget
     700     * @param string $widgetStyle The style of the widget code snippet to be generated,
     701     * valid choices include 'big-icon', 'small-icon', 'text',
     702     * @param string $linkText specifies the text of the link if the style is "text"
     703     * @return array array('html-head-code' => '', 'html-body-code' => '')
     704     * @throws Exception when $widgetStyle parameter is invalid
     705     */
     706    public static function generateCode($widgetName, $appKey, $appSecret, $widgetStyle, $linkText=null, $siteURL=null){
     707       
     708        /*
     709        if ($siteURL==null && ($widgetStyle == 'embedded-body' || $widgetStyle == 'popup-body')) {
     710            throw new BadMethodCallException('With second parameter to be "'.$widgetStyle.'", '.__METHOD__.' expect fifth parameter to be a string, none given.');
     711        }
     712        */
     713       
     714        if (empty($linkText)) {
     715            $linkText = 'Sign In';
     716        }
     717       
     718        if (empty($siteURL)) {
     719            $siteURL = '__TOKEN_URL__';
     720            $comment = ' // replace __TOKEN_URL__ with your own callback URL';
     721        } else {
     722            $comment = '';
     723        }
     724       
     725        $owaSrc = self::$endpoint . '/owa';
     726        $authSrc = "{$owaSrc}/js/app/{$appKey}.js";
     727       
     728        // the source files path
     729        $sourcePath = 'http://demo.sumilux.com/ssi/download';
     730       
     731        $sig = md5($appSecret);
     732        $cssSrc = $sourcePath.'/ssi.css';
     733               
     734        if ( $widgetStyle == 'big-icon') {
     735            $funcJs = $sourcePath.'/popup.js';
     736            $head_code = <<<POP_UP_HEADER
    649737<link type="text/css" rel="stylesheet" href="{$cssSrc}">
    650738<script type="text/javascript">
    651 // Please do not modify this segment of code.
    652 // In case changes are needed, please regenerate through the SSI system.
    653 window.SSI={params:"{$srcTale}",
    654 owaUrl:"{$owaSrc}"};
     739window.SSI={
     740    tokenUrl: "{$siteURL}",{$comment}
     741    appName:"{$widgetName}",
     742    sig:"{$sig}",
     743    owaUrl:"{$owaSrc}"
     744};
    655745(function(){
    656746    var e=document.createElement("script");
     
    663753</script>
    664754POP_UP_HEADER;
    665         }
    666         else if ( $codeType == 'popup-body' ) {
    667             // no need for the siteURL parameter
    668             $ret = <<<POP_UP_BODY
     755
     756            $body_code = <<<POP_UP_BODY
    669757<div style="padding:20px">
    670758    <div style="text-align:center";>
    671         <a href="#none" onclick="SSI.popLoginPage();">Sign-in</a>
     759        <a href="#none" onclick="SSI.popLoginPage();">{$linkText}</a>
    672760    </div>
    673761</div>
    674762POP_UP_BODY;
    675         }
    676         else if ( $codeType == 'embedded-header') {
    677             $funcJs = $sourcePath.'/emb.js';
    678             $ret = <<<EMBEDDED_HEADER
     763        } else if ( $widgetStyle == 'small-icon') {
     764            $funcJs = $sourcePath.'/emb.js';
     765            $head_code = <<<EMBEDDED_HEADER
    679766<link type="text/css" rel="stylesheet" href="{$cssSrc}">
    680767<script type="text/javascript">
    681 // Please do not modify this segment of code.
    682 // In case changes are needed, please regenerate through the SSI system.
    683 window.SSI={params:"{$srcTale}",
    684 owaUrl:"{$owaSrc}"};
     768window.SSI={
     769    tokenUrl: "{$siteURL}",{$comment}
     770    appName:"{$widgetName}",
     771    sig:"{$sig}",
     772    owaUrl:"{$owaSrc}"
     773};
    685774(function(){
    686775    var e=document.createElement("script");
     
    693782</script>
    694783EMBEDDED_HEADER;
    695         }
    696         else if ( $codeType == 'embedded-body') {
    697             // no need for the siteURL param
    698             $ret = <<<EMBEDDED_BODY
     784            $body_code = <<<EMBEDDED_BODY
    699785<div id="smx_ssi">
    700786    <div id="smx_lastsign"></div>
     
    702788</div>
    703789EMBEDDED_BODY;
    704         }
    705         else if ( $codeType == 'link-body') {
    706             // how the link would be rendered on a page
    707             $authURL = $owaSrc . '?exitURL=' . urlencode($siteURL) . "&sig={$sig}";
    708             $ret = <<<LINK_BODY
     790        } else if ( $widgetStyle == 'text') {
     791            $funcJs = $sourcePath.'/link.js';
     792            $head_code = <<<LINK_HEAD
     793<script type="text/javascript">
     794window.SSI={
     795    tokenUrl: "{$siteURL}",{$comment}
     796    appName:"{$widgetName}",
     797    sig:"{$sig}",
     798    owaUrl:"{$owaSrc}"
     799};
     800(function(){
     801    var e=document.createElement("script");
     802    e.type="text/javascript"; e.src="{$authSrc}";
     803    var f=document.createElement("script");
     804    f.type="text/javascript"; f.src="{$funcJs}";
     805    var h=document.getElementsByTagName("script")[0];
     806    h.parentNode.insertBefore(e, h); h.parentNode.insertBefore(f, h);
     807})();
     808</script>
     809LINK_HEAD;
     810            $body_code = <<<LINK_BODY
    709811<div id="smx_ssi">
    710     <a href="{$authURL}">Sign In</a>
     812    <a href="#" onclick="SSI.doLogin();">{$linkText}</a>
    711813</div>
    712814LINK_BODY;
    713         }
    714         else if ( $codeType == 'link' ) {
    715             // just the link itself
    716             $ret = $owaSrc . '?exitURL=' . urlencode($siteURL) . "&sig={$sig}";
    717         }
    718         else {
    719             throw new Exception("Unknown code type: " + $codeType);
    720         }
    721 
    722         return $ret;
    723     }
    724 
    725 
     815        } else {
     816            throw new Exception("Unknown widget style: " + $widgetStyle);
     817        }
     818       
     819        return array('html-head-code' => $head_code, 'html-body-code' => $body_code);
     820    }
     821   
     822   
    726823}
    727824
  • ssi-sumilux/trunk/templates/html_login_form.tpl

    r490793 r492339  
    2525    width:325px;
    2626    color: #777777;
    27     font-size: 18px;
     27    font-size: 12px;
    2828    text-weight: bold;
     29    text-align: center;
     30    }
     31
     32    #smx_ssi{
     33    width :150px;
     34    margin : auto;
    2935    }
    3036
    3137</style>
    3238
    33 <div id="ssilogin" style="">%html_block%</div>
     39<div id="ssilogin" style="">
     40    No Account Yet?<br/>
     41    Sign In With One Of Your Social Identities Below:<br/>
     42    %html_block%
     43</div>
    3444
    3545<!--
Note: See TracChangeset for help on using the changeset viewer.