コード例 #1
0
 public function testCredentials()
 {
     $credentials = new Credentials(self::MERCHANT, self::PRIVATE_KEY, new Md5Algorithm(), self::ENCRYPTION_PROTOCOL);
     $this->assertEquals(self::MERCHANT, $credentials->getMerchantPosId());
     $this->assertEquals(self::PRIVATE_KEY, $credentials->getPrivateKey());
     $this->assertEquals(self::ENCRYPTION_PROTOCOL, $credentials->getEncryptionProtocols());
     $this->assertInstanceOf('\\Team3\\PayU\\SignatureCalculator\\Encoder\\Algorithms\\AlgorithmInterface', $credentials->getSignatureAlgorithm());
 }
コード例 #2
0
 public function tryLogin(Credentials $userCredentials, UserArray $users)
 {
     //First check to make sure the user is not already logged in (this is also checked in controller, but I prefer to check in all places to minimize errors)
     if (!$this->isUserLoggedIn()) {
         //If input matches any saved user, return true (successful login attempt) and save in session variable as 'logged in'
         if ($users->getUserByName($userCredentials->getUserName()) != null && password_verify($userCredentials->getUserPassword(), $users->getUserByName($userCredentials->getUserName())->getPassword())) {
             $_SESSION['LoggedIn'] = $userCredentials->getUserName();
             return true;
         }
     }
     //In all other cases, return false
     return false;
 }
コード例 #3
0
 /**
  * Install hstore
  * /usr/share/postgresql/contrib # cat hstore.sql | psql -U pgsql -d onphp
  **/
 public function testHstore()
 {
     foreach (DBTestPool::me()->getPool() as $connector => $db) {
         DBPool::me()->setDefault($db);
         $properties = array('age' => '23', 'weight' => 80, 'comment' => null);
         $user = TestUser::create()->setCity($moscow = TestCity::create()->setName('Moscow'))->setCredentials(Credentials::create()->setNickname('fake')->setPassword(sha1('passwd')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'))->setProperties(Hstore::make($properties));
         $moscow = TestCity::dao()->add($moscow);
         $user = TestUser::dao()->add($user);
         Cache::me()->clean();
         TestUser::dao()->dropIdentityMap();
         $user = TestUser::dao()->getById('1');
         $this->assertInstanceOf('Hstore', $user->getProperties());
         $this->assertEquals($properties, $user->getProperties()->getList());
         $form = TestUser::proto()->makeForm();
         $form->get('properties')->setFormMapping(array(Primitive::string('age'), Primitive::integer('weight'), Primitive::string('comment')));
         $form->import(array('id' => $user->getId()));
         $this->assertNotNull($form->getValue('id'));
         $object = $user;
         FormUtils::object2form($object, $form);
         $this->assertInstanceOf('Hstore', $form->getValue('properties'));
         $this->assertEquals(array_filter($properties), $form->getValue('properties')->getList());
         $subform = $form->get('properties')->getInnerForm();
         $this->assertEquals($subform->getValue('age'), '23');
         $this->assertEquals($subform->getValue('weight'), 80);
         $this->assertNull($subform->getValue('comment'));
         $user = new TestUser();
         FormUtils::form2object($form, $user, false);
         $this->assertEquals($user->getProperties()->getList(), array_filter($properties));
     }
 }
コード例 #4
0
 /**
  * Constructs a Credentials object for Users (making requests on behalf of a user).
  *
  * @param string $consumerKey    Twitter Application Consumer Key
  * @param string $consumerSecret Twitter Application Consumer Secret
  * @param string|null $callbackUrl Twitter Application Callback URL
  * @param string|null $accessToken Twitter Access Token
  * @param string|null $accessTokenSecret Twitter Access Token Secret
  */
 public function __construct($consumerKey, $consumerSecret, $callbackUrl = null, $accessToken = null, $accessTokenSecret = null)
 {
     parent::__construct($consumerKey, $consumerSecret);
     $this->accessToken = $accessToken;
     $this->accessTokenSecret = $accessTokenSecret;
     $this->callbackUrl = $callbackUrl;
 }
コード例 #5
0
 /**
  * @test
  * @covers ::fromUsernameAndPassword
  * @covers ::basicAuthentication
  */
 public function it_should_provide_a_basic_authentication_token()
 {
     $username = '******';
     $password = '******';
     $credentials = Credentials::fromUsernameAndPassword($username, $password);
     $this->assertSame('bWlrZTppdHdvcmtz', $credentials->basicAuthentication());
 }
コード例 #6
0
 /**
  * @return string
  */
 protected function getSigningKey()
 {
     $signingKey = rawurlencode($this->credentials->getConsumerSecret()) . '&';
     if ($this->tokenSecret !== null) {
         $signingKey .= rawurlencode($this->tokenSecret);
     }
     return $signingKey;
 }
コード例 #7
0
ファイル: User.php プロジェクト: evodelavega/pushover-net
 /**
  * @param bool $includeNull = false
  * @return array
  */
 public function toArray($includeNull = false)
 {
     $array = parent::toArray($includeNull);
     if ($this->credentials) {
         $array['token'] = $this->credentials->getToken();
     }
     return $array;
 }
コード例 #8
0
ファイル: CredentialsTest.php プロジェクト: keyeMyria/CRM
 public function testMakeDefault()
 {
     $cred = $this->credentials('testUser');
     $cred->makeDefault($this->users('testUser')->id, 'email');
     $defaults = $cred->getDefaultCredentials(true);
     $default = Credentials::model()->findDefault($this->users('testUser')->id, 'email');
     $this->assertEquals($cred->id, $default->id, 'Failed asserting proper function of set-as-default method.');
 }
コード例 #9
0
ファイル: Repository.php プロジェクト: samueljwilliams/pcr
 /**
  * 
  * Authenticates the user using the supplied credentials.
  * If workspace is recognized as the name of an existing workspace in the repository and authorization to access that workspace is granted, then a new Session object is returned.
  * If authentication or authorization for the specified workspace fails, a LoginException is thrown.
  * If workspace is not recognized, a NoSuchWorkspaceException is thrown.
  * @param Credentials $credentials the credentials of the user.
  * @param string $workspace the name of the workspace.
  * @return Session a valid session for the user to access the repository.
  *  
  */
 public static function login(Credentials $credentials, $workspace)
 {
     if (!file_exists($_SERVER['PCR'] . "/config/{$workspace}.xml")) {
         throw new NoSuchWorkspaceException($workspace);
     }
     $config = simplexml_load_file($_SERVER['PCR'] . "/config/{$workspace}.xml");
     $persistenceManager = (string) $config->persistenceManager;
     if (!file_exists($_SERVER['PCR'] . "/PMs/{$persistenceManager}.php")) {
         throw new RepositoryException("persistence manager does not exist for workspace: {$workspace}=>{$persistenceManager}");
     }
     require_once $_SERVER['PCR'] . "/PMs/{$persistenceManager}.php";
     $pm = new $persistenceManager($credentials, $workspace, $config);
     if (!$pm->isLive()) {
         throw new LoginException("workspace=>{$workspace}, persistenceManager=>{$persistenceManager}, userID=>" . $credentials->getUserID());
     }
     Log4PCR::access("workspace=>{$workspace}, persistenceManager=>{$persistenceManager}, userID=>" . $credentials->getUserID());
     return new Session($pm);
 }
コード例 #10
0
 /**
  *  Lists the video outputs under a particular article.
  *
  * @param int articleId
  * @param int $offset offset to skip
  * @param int $limit The limit to apply to the list (maximum 100)
  * @param array $properties array of properties to add to querystring
  * @param array $array of fields to add to querystring
  * @return AdferoVideoOutputList 
  */
 private function ListVideoOutputsForArticle($articleId, $offset, $limit, $properties, $fields)
 {
     $uri = $this->GetUri($articleId, "articleId", "xml", $properties, $fields, $offset, $limit);
     $uri = "http://" . $this->credentials->getPublicKey() . ":" . $this->credentials->getSecretKey() . "@" . str_replace("http://", "", $uri);
     $xmlString = AdferoHelpers::GetXMLFromUri($uri);
     $videoOutputs = $this->ListVideoOutputsFromXmlString($xmlString);
     $videoOutputs->limit = $limit;
     $videoOutputs->offset = $offset;
     return $videoOutputs;
 }
コード例 #11
0
 public function testSubaccountDoesntExist()
 {
     $creds = Credentials::get();
     $client = new GSC_Client($creds["merchantId"]);
     $client->login($creds["email"], $creds["password"]);
     $errors = $client->getAccount("1");
     $errors = $errors->getErrors();
     $error = $errors[0];
     $this->assertEquals('ResourceNotFoundException', $error->getCode());
 }
コード例 #12
0
 public function __construct(Credentials $credentials, $workspace, $config)
 {
     $link = @mysql_connect($config->server, $credentials->getUserID(), $credentials->getPassword(), 1);
     if (mysql_stat($link) !== null) {
         if (!mysql_select_db($workspace, $link)) {
             $sql = "CREATE DATABASE {$workspace}";
             if (mysql_query($sql, $link)) {
                 mysql_select_db($workspace, $link);
                 $sql = "CREATE TABLE c (p text NOT NULL,\n\t\t\t\t\t\t\t\tn text NOT NULL,\n\t\t\t\t\t\t\t\tv text NOT NULL,\n\t\t\t\t\t\t\t\tKEY INDEX1 (p (1000)),\n\t\t\t\t\t\t\t\tKEY INDEX2 (p (850), n (150)),\n\t\t\t\t\t\t\t\tKEY INDEX3 (p (550), n (150), v (300)),\n\t\t\t\t\t\t\t\tKEY INDEX4 (v (1000)))\n\t\t\t\t\t\t\t\tENGINE = MyISAM DEFAULT CHARSET = latin1";
                 mysql_query($sql, $link);
             } else {
                 throw new RepositoryException("in MySQL, cannot create workspace: {$workspace}");
             }
         }
         $this->credentials = $credentials;
         $this->workspace = $workspace;
         $this->config = $config;
         $this->link = $link;
         $this->isLive = true;
     }
 }
コード例 #13
0
ファイル: class-request.php プロジェクト: mattheu/apple-news
 /**
  * Signs the API request.
  *
  * @param string $url
  * @param string $verb
  * @param string $content
  * @return array
  * @since 0.2.0
  */
 private function sign($url, $verb, $content = null)
 {
     $current_date = date('c');
     $request_info = $verb . $url . $current_date;
     if ('POST' == $verb) {
         $content_type = 'multipart/form-data; boundary=' . $this->mime_builder->boundary();
         $request_info .= $content_type . $content;
     }
     $secret_key = base64_decode($this->credentials->secret());
     $hash = hash_hmac('sha256', $request_info, $secret_key, true);
     $signature = base64_encode($hash);
     return 'HHMAC; key=' . $this->credentials->key() . '; signature=' . $signature . '; date=' . $current_date;
 }
コード例 #14
0
 public function testCount()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $this->getDBCreator()->fillDB();
         $count = TestUser::dao()->getTotalCount();
         $this->assertGreaterThan(1, $count);
         $city = TestCity::create()->setId(1);
         $newUser = TestUser::create()->setCity($city)->setCredentials(Credentials::create()->setNickname('newuser')->setPassword(sha1('newuser')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time()));
         TestUser::dao()->add($newUser);
         $newCount = TestUser::dao()->getTotalCount();
         $this->assertEquals($count + 1, $newCount);
     }
 }
コード例 #15
0
 /**
  * Gets the response from the api in string format
  * 
  * @param int $articleId Id of the article from which to get the video player
  * @param Players $playerName Name of the player to display embed code for
  * @param Version $playerVersion Version of the player to display embed code for
  * @param Players $fallbackPlayerName Name of the fallback player to display embed code for if the primary player isn't supported by the browser
  * @param Version $fallbackPlayerVersion Version of the fallback player to display embed code for if the primary player isn't supported by the browser
  * @param array $properties array of properties to add to querystring
  * @param array $fields array of fields to add to querystring
  * @param string $format can be either "xml" or "json"
  * @return string
  * @throws InvalidArgumentException 
  */
 private function GetVideoPlayerRaw($articleId, $playerName, $playerVersion, $fallbackPlayerName, $fallbackPlayerVersion, $properties, $fields, $format)
 {
     switch ($format) {
         case "xml":
             $uri = $this->GetUri($articleId, $playerName, $playerVersion, $fallbackPlayerName, $fallbackPlayerVersion, "xml", $properties, $fields);
             break;
         case "json":
             $uri = $this->GetUri($articleId, $playerName, $playerVersion, $fallbackPlayerName, $fallbackPlayerVersion, "json", $properties, $fields);
             break;
         default:
             throw new \InvalidArgumentException($format . 'format not supported');
             break;
     }
     $uri = "http://" . $this->credentials->getPublicKey() . ":" . $this->credentials->getSecretKey() . "@" . str_replace("http://", "", $uri);
     return AdferoHelpers::GetRawResponse($uri);
 }
コード例 #16
0
 public function testIpAddressProperty()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $city = TestCity::create()->setName('Khimki');
         TestCity::dao()->add($city);
         $userWithIp = TestUser::create()->setCredentials(Credentials::create()->setNickName('postgreser')->setPassword(sha1('postgreser')))->setLastLogin(Timestamp::makeNow())->setRegistered(Timestamp::makeNow())->setCity($city)->setIp(IpAddress::create('127.0.0.1'));
         TestUser::dao()->add($userWithIp);
         $this->assertTrue($userWithIp->getId() >= 1);
         $this->assertTrue($userWithIp->getIp() instanceof IpAddress);
         $plainIp = DBPool::me()->getByDao(TestUser::dao())->queryColumn(OSQL::select()->get('ip')->from(TestUser::dao()->getTable())->where(Expression::eq('id', $userWithIp->getId())));
         $this->assertEquals($plainIp[0], $userWithIp->getIp()->toString());
         $count = Criteria::create(TestUser::dao())->add(Expression::eq('ip', IpAddress::create('127.0.0.1')))->addProjection(Projection::count('*', 'count'))->getCustom('count');
         $this->assertEquals($count, 1);
     }
 }
コード例 #17
0
ファイル: BaseX2FlowEmail.php プロジェクト: dsyman2/X2CRM
 public function paramRules()
 {
     if (Yii::app()->isInSession) {
         $credOptsDict = Credentials::getCredentialOptions(null, true);
         $credOpts = $credOptsDict['credentials'];
         $selectedOpt = $credOptsDict['selectedOption'];
         foreach ($credOpts as $key => $val) {
             if ($key == $selectedOpt) {
                 $credOpts = array($key => $val) + $credOpts;
                 // move to beginning of array
                 break;
             }
         }
     } else {
         $credOpts = array();
     }
     return array_merge(parent::paramRules(), array('title' => Yii::t('studio', $this->title), 'info' => Yii::t('studio', $this->info), 'options' => array(array('name' => 'from', 'label' => Yii::t('studio', 'Send As:'), 'type' => 'dropdown', 'options' => $credOpts))));
 }
コード例 #18
0
 /**
  * Attempts to connect to database.
  *
  * @return void
  * @throws \RuntimeException
  */
 private function connect()
 {
     $dsn = "{$this->credentials->getDriver()}:host={$this->credentials->getHost()}";
     try {
         $pdo = new \PDO($dsn, $this->credentials->getUsername(), $this->credentials->getPassword());
     } catch (\PDOException $e) {
         throw new \RuntimeException('Failed to connect to database.', 0, $e);
     }
     $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
     $this->pdo = $pdo;
     if (!is_null($this->credentials->getCharset())) {
         $this->setCharset($this->credentials->getCharset());
     }
     if (!is_null($this->credentials->getDatabase())) {
         $this->selectDatabase($this->credentials->getDatabase());
     }
 }
コード例 #19
0
ファイル: API.php プロジェクト: Geotab/mygeotab-php
 /**
  * @param $method
  * @param array $post
  * @param null $successCallback
  * @param null $errorCallback
  */
 private function request($method, array $post, $successCallback, $errorCallback)
 {
     $url = "https://" . $this->credentials->getServer() . "/apiv1";
     $postData = "JSON-RPC=" . urlencode(json_encode(["method" => $method, "params" => $post]));
     $headers = ["Connection: keep-alive", "Content-Type: application/x-www-form-urlencoded", "Charset=UTF-8", "Cache-Control: no-cache", "Pragma: no-cache"];
     $defaults = array(CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => 30, CURLOPT_ENCODING => "gzip", CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSLVERSION => 6);
     $ch = curl_init();
     curl_setopt_array($ch, $defaults);
     $response = curl_exec($ch);
     $error = curl_error($ch);
     if ($error != "") {
         trigger_error(curl_error($ch));
     }
     $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
     //$headerReturn = substr($response, 0, $header_size);
     $body = substr($response, $header_size);
     curl_close($ch);
     $result = json_decode($body, true);
     // If callbacks are specified - then call them. Otherwise, just return the results or throw an error
     if ($this->array_check("result", $result)) {
         if (is_callable($successCallback)) {
             $successCallback($result["result"]);
         } else {
             return $result["result"];
         }
     } else {
         if (count($result) == 0) {
             if (is_callable($successCallback)) {
                 $successCallback($result);
             } else {
                 return $result;
             }
         } else {
             if (is_callable($errorCallback)) {
                 $errorCallback($result["error"]["errors"][0]);
             } else {
                 throw new MyGeotabException($result["error"]["errors"][0]);
             }
         }
     }
 }
コード例 #20
0
ファイル: AdminController.php プロジェクト: xl602/X2CRM
 public function actionTwitterIntegration()
 {
     $credId = Yii::app()->settings->twitterCredentialsId;
     if ($credId && ($cred = Credentials::model()->findByPk($credId))) {
         $params = array('id' => $credId);
     } else {
         $params = array('class' => 'TwitterApp');
     }
     $url = Yii::app()->createUrl('/profile/createUpdateCredentials', $params);
     $this->redirect($url);
 }
コード例 #21
0
ファイル: X2Model.php プロジェクト: tymiles003/X2CRM
    public static function renderModelInput(CModel $model, $field, $htmlOptions = array())
    {
        if (!$field->asa('CommonFieldsBehavior')) {
            throw new Exception('$field must have CommonFieldsBehavior');
        }
        if ($field->required) {
            if (isset($htmlOptions['class'])) {
                $htmlOptions['class'] .= ' x2-required';
            } else {
                $htmlOptions = array_merge(array('class' => 'x2-required'), $htmlOptions);
            }
        }
        $fieldName = $field->fieldName;
        if (!isset($field)) {
            return null;
        }
        switch ($field->type) {
            case 'text':
                return CHtml::activeTextArea($model, $field->fieldName, array_merge(array('title' => $field->attributeLabel), array_merge(array('encode' => false), $htmlOptions)));
            case 'date':
                $oldDateVal = $model->{$fieldName};
                $model->{$fieldName} = Formatter::formatDate($model->{$fieldName}, 'medium');
                Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
                $pickerOptions = array('dateFormat' => Formatter::formatDatePicker(), 'changeMonth' => false, 'changeYear' => true);
                if (Yii::app()->getLanguage() === 'fr') {
                    $pickerOptions['monthNamesShort'] = Formatter::getPlainAbbrMonthNames();
                }
                $input = Yii::app()->controller->widget('CJuiDateTimePicker', array('model' => $model, 'attribute' => $fieldName, 'mode' => 'date', 'options' => $pickerOptions, 'htmlOptions' => array_merge(array('title' => $field->attributeLabel), $htmlOptions), 'language' => Yii::app()->language == 'en' ? '' : Yii::app()->getLanguage()), true);
                $model->{$fieldName} = $oldDateVal;
                return $input;
            case 'dateTime':
                $oldDateTimeVal = $model->{$fieldName};
                $pickerOptions = array('dateFormat' => Formatter::formatDatePicker('medium'), 'timeFormat' => Formatter::formatTimePicker(), 'ampm' => Formatter::formatAMPM(), 'changeMonth' => true, 'changeYear' => true);
                if (Yii::app()->getLanguage() === 'fr') {
                    $pickerOptions['monthNamesShort'] = Formatter::getPlainAbbrMonthNames();
                }
                $model->{$fieldName} = Formatter::formatDateTime($model->{$fieldName});
                Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
                $input = Yii::app()->controller->widget('CJuiDateTimePicker', array('model' => $model, 'attribute' => $fieldName, 'mode' => 'datetime', 'options' => $pickerOptions, 'htmlOptions' => array_merge(array('title' => $field->attributeLabel), $htmlOptions), 'language' => Yii::app()->language == 'en' ? '' : Yii::app()->getLanguage()), true);
                $model->{$fieldName} = $oldDateTimeVal;
                return $input;
            case 'dropdown':
                // Note: if desired to translate dropdown options, change the seecond argument to
                // $model->module
                $om = $field->getDropdownOptions();
                $multi = (bool) $om['multi'];
                $dropdowns = $om['options'];
                $curVal = $multi ? CJSON::decode($model->{$field->fieldName}) : $model->{$field->fieldName};
                $ajaxArray = array();
                if ($field instanceof Fields) {
                    $dependencyCount = X2Model::model('Dropdowns')->countByAttributes(array('parent' => $field->linkType));
                    $fieldDependencyCount = X2Model::model('Fields')->countByAttributes(array('modelName' => $field->modelName, 'type' => 'dependentDropdown', 'linkType' => $field->linkType));
                    if ($dependencyCount > 0 && $fieldDependencyCount > 0) {
                        $ajaxArray = array('ajax' => array('type' => 'GET', 'url' => Yii::app()->controller->createUrl('/site/dynamicDropdown'), 'data' => 'js:{
                                "val":$(this).val(),
                                "dropdownId":"' . $field->linkType . '",
                                "field":true, "module":"' . $field->modelName . '"
                            }', 'success' => '
                                function(data){
                                    if(data){
                                        data=JSON.parse(data);
                                        if(data[0] && data[1]){
                                            $("#' . $field->modelName . '_"+data[0]).html(data[1]);
                                        }
                                    }
                                }'));
                    }
                }
                $htmlOptions = array_merge($htmlOptions, $ajaxArray, array('title' => $field->attributeLabel));
                if ($multi) {
                    $multiSelectOptions = array();
                    if (!is_array($curVal)) {
                        $curVal = array();
                    }
                    foreach ($curVal as $option) {
                        $multiSelectOptions[$option] = array('selected' => 'selected');
                    }
                    $htmlOptions = array_merge($htmlOptions, array('options' => $multiSelectOptions, 'multiple' => 'multiple'));
                } elseif ($field->includeEmpty) {
                    $htmlOptions = array_merge($htmlOptions, array('empty' => Yii::t('app', "Select an option")));
                }
                return CHtml::activeDropDownList($model, $field->fieldName, $dropdowns, $htmlOptions);
            case 'dependentDropdown':
                return CHtml::activeDropDownList($model, $field->fieldName, array('' => '-'), array_merge(array('title' => $field->attributeLabel), $htmlOptions));
            case 'link':
                $linkSource = null;
                $linkId = '';
                $name = '';
                if (class_exists($field->linkType)) {
                    // Create a model for autocompletion:
                    if (!empty($model->{$fieldName})) {
                        list($name, $linkId) = Fields::nameAndId($model->{$fieldName});
                        $linkModel = X2Model::getLinkedModelMock($field->linkType, $name, $linkId, true);
                    } else {
                        $linkModel = X2Model::model($field->linkType);
                    }
                    if ($linkModel instanceof X2Model && $linkModel->asa('X2LinkableBehavior') instanceof X2LinkableBehavior) {
                        $linkSource = Yii::app()->controller->createUrl($linkModel->autoCompleteSource);
                        $linkId = $linkModel->id;
                        $oldLinkFieldVal = $model->{$fieldName};
                        $model->{$fieldName} = $name;
                    }
                }
                static $linkInputCounter = 0;
                $hiddenInputId = $field->modelName . '_' . $fieldName . "_id" . $linkInputCounter++;
                $input = CHtml::hiddenField($field->modelName . '[' . $fieldName . '_id]', $linkId, array('id' => $hiddenInputId)) . Yii::app()->controller->widget('zii.widgets.jui.CJuiAutoComplete', array('model' => $model, 'attribute' => $fieldName, 'source' => $linkSource, 'value' => $name, 'options' => array('minLength' => '1', 'select' => 'js:function( event, ui ) {
                                    $("#' . $hiddenInputId . '").
                                        val(ui.item.id);
                                    $(this).val(ui.item.value);
                                    return false;
                            }', 'create' => $field->linkType == 'Contacts' ? 'js:function(event, ui) {
                                    $(this).data( "uiAutocomplete" )._renderItem = 
                                        function(ul,item) {
                                            return $("<li>").data("item.autocomplete",item).
                                                append(x2.forms.renderContactLookup(item)).
                                                appendTo(ul);
                                        };
                            }' : ($field->linkType == 'BugReports' ? 'js:function(event, ui) {
                                $(this).data( "uiAutocomplete" )._renderItem = 
                                    function( ul, item ) {

                                    var label = "<a style=\\"line-height: 1;\\">" + item.label;

                                    label += "<span style=\\"font-size: 0.6em;\\">";

                                    // add email if defined
                                    if(item.subject) {
                                        label += "<br>";
                                        label += item.subject;
                                    }

                                    label += "</span>";
                                    label += "</a>";

                                    return $( "<li>" )
                                        .data( "item.autocomplete", item )
                                        .append( label )
                                        .appendTo( ul );
                                };
                            }' : '')), 'htmlOptions' => array_merge(array('title' => $field->attributeLabel), $htmlOptions)), true);
                if (isset($oldLinkFieldVal)) {
                    $model->{$fieldName} = $oldLinkFieldVal;
                }
                return $input;
            case 'rating':
                return Yii::app()->controller->widget('X2StarRating', array('model' => $model, 'attribute' => $field->fieldName, 'readOnly' => isset($htmlOptions['disabled']) && $htmlOptions['disabled'], 'minRating' => Fields::RATING_MIN, 'maxRating' => Fields::RATING_MAX, 'starCount' => Fields::RATING_MAX - Fields::RATING_MIN + 1, 'cssFile' => Yii::app()->theme->getBaseUrl() . '/css/rating/jquery.rating.css', 'htmlOptions' => $htmlOptions, 'callback' => 'function(value, link){
                        if (typeof x2 !== "undefined" &&
                            typeof x2.InlineEditor !== "undefined" &&
                            typeof x2.InlineEditor.ratingFields !== "undefined") {

                            x2.InlineEditor.ratingFields["' . $field->modelName . '[' . $field->fieldName . ']"] = value;
                        }
                    }'), true);
            case 'boolean':
                $checkbox = CHtml::openTag('div', X2Html::mergeHtmlOptions($htmlOptions, array('class' => 'checkboxWrapper')));
                $checkbox .= CHtml::activeCheckBox($model, $field->fieldName, array_merge(array('unchecked' => 0, 'title' => $field->attributeLabel), $htmlOptions));
                $checkbox .= CHtml::closeTag('div');
                return $checkbox;
            case 'assignment':
                $oldAssignmentVal = $model->{$fieldName};
                $model->{$fieldName} = !empty($model->{$fieldName}) ? $field->linkType == 'multiple' && !is_array($model->{$fieldName}) ? explode(', ', $model->{$fieldName}) : $model->{$fieldName} : X2Model::getDefaultAssignment();
                $dropdownList = CHtml::activeDropDownList($model, $fieldName, X2Model::getAssignmentOptions(true, true), array_merge(array('title' => $field->attributeLabel, 'id' => $field->modelName . '_' . $fieldName . '_assignedToDropdown', 'multiple' => $field->linkType == 'multiple' ? 'multiple' : null), $htmlOptions));
                $model->{$fieldName} = $oldAssignmentVal;
                return $dropdownList;
            case 'optionalAssignment':
                // optional assignment for users (can be left blank)
                $users = User::getNames();
                unset($users['Anyone']);
                return CHtml::activeDropDownList($model, $fieldName, $users, array_merge(array('title' => $field->attributeLabel, 'empty' => ''), $htmlOptions));
            case 'visibility':
                $permissionsBehavior = Yii::app()->params->modelPermissions;
                return CHtml::activeDropDownList($model, $field->fieldName, $permissionsBehavior::getVisibilityOptions(), array_merge(array('title' => $field->attributeLabel, 'id' => $field->modelName . "_visibility"), $htmlOptions));
                // 'varchar', 'email', 'url', 'int', 'float', 'currency', 'phone'
                // case 'int':
                // return CHtml::activeNumberField($model, $field->fieldNamearray_merge(array(
                // 'title' => $field->attributeLabel,
                // ), $htmlOptions));
            // 'varchar', 'email', 'url', 'int', 'float', 'currency', 'phone'
            // case 'int':
            // return CHtml::activeNumberField($model, $field->fieldNamearray_merge(array(
            // 'title' => $field->attributeLabel,
            // ), $htmlOptions));
            case 'percentage':
                $htmlOptions['class'] = empty($htmlOptions['class']) ? 'input-percentage' : $htmlOptions['class'] . ' input-percentage';
                return CHtml::activeTextField($model, $field->fieldName, array_merge(array('title' => $field->attributeLabel), $htmlOptions));
            case 'currency':
                $fieldName = $field->fieldName;
                $elementId = isset($htmlOptions['id']) ? '#' . $htmlOptions['id'] : '#' . $field->modelName . '_' . $field->fieldName;
                Yii::app()->controller->widget('application.extensions.moneymask.MMask', array('element' => $elementId, 'currency' => Yii::app()->params['currency'], 'config' => array('affixStay' => true, 'decimal' => Yii::app()->locale->getNumberSymbol('decimal'), 'thousands' => Yii::app()->locale->getNumberSymbol('group'))));
                return CHtml::activeTextField($model, $field->fieldName, array_merge(array('title' => $field->attributeLabel, 'class' => 'currency-field'), $htmlOptions));
            case 'credentials':
                $typeAlias = explode(':', $field->linkType);
                $type = $typeAlias[0];
                if (count($typeAlias) > 1) {
                    $uid = Credentials::$sysUseId[$typeAlias[1]];
                } else {
                    $uid = Yii::app()->user->id;
                }
                return Credentials::selectorField($model, $field->fieldName, $type, $uid);
            case 'timerSum':
                // Sorry, no-can-do. This is field derives its value from a sum over timer records.
                return $model->renderAttribute($field->fieldName);
            case 'float':
            case 'int':
                if (isset($model->{$fieldName})) {
                    $oldNumVal = $model->{$fieldName};
                    $model->{$fieldName} = Yii::app()->locale->numberFormatter->formatDecimal($model->{$fieldName});
                }
                $input = CHtml::activeTextField($model, $field->fieldName, array_merge(array('title' => $field->attributeLabel), $htmlOptions));
                if (isset($oldNumVal)) {
                    $model->{$fieldName} = $oldNumVal;
                }
                return $input;
            default:
                return CHtml::activeTextField($model, $field->fieldName, array_merge(array('title' => $field->attributeLabel), $htmlOptions));
                // array(
                // 'tabindex'=>isset($item['tabindex'])? $item['tabindex'] : null,
                // 'disabled'=>$item['readOnly']? 'disabled' : null,
                // 'title'=>$field->attributeLabel,
                // 'style'=>$default?'color:#aaa;':null,
                // ));
        }
    }
コード例 #22
0
ファイル: FieldFormatter.php プロジェクト: tymiles003/X2CRM
 protected function renderCredentials($field, $makeLinks, $textOnly, $encode)
 {
     $fieldName = $field->fieldName;
     $sysleg = Yii::t('app', 'System default (legacy)');
     if ($this->owner->{$fieldName} == -1) {
         return $sysleg;
     } else {
         $creds = Credentials::model()->findByPk($this->owner->{$fieldName});
         if (!empty($creds)) {
             return $this->render($creds->name, $encode);
         } else {
             return $sysleg;
         }
     }
 }
コード例 #23
0
ファイル: x2base.php プロジェクト: shuvro35/X2CRM
 /**
  * Send an email from X2Engine, returns an array with status code/message
  *
  * @param array addresses
  * @param string $subject the subject for the email
  * @param string $message the body of the email
  * @param array $attachments array of attachments to send
  * @param array|integer $from from and reply to address for the email array(name, address)
  *     or, if integer, the ID of a email credentials record to use for delivery.
  * @return array
  */
 public function sendUserEmail($addresses, $subject, $message, $attachments = null, $from = null)
 {
     $eml = new InlineEmail();
     if (is_array($addresses) ? count($addresses) == 0 : true) {
         throw new Exception('Invalid argument 1 sent to x2base.sendUserEmail(); expected a non-empty array, got instead: ' . var_export($addresses, 1));
     }
     // Set recipients:
     if (array_key_exists('to', $addresses) || array_key_exists('cc', $addresses) || array_key_exists('bcc', $addresses)) {
         $eml->mailingList = $addresses;
     } else {
         return array('code' => 500, 'message' => 'No recipients specified for email; array given for argument 1 of x2base.sendUserEmail does not have a "to", "cc" or "bcc" key.');
     }
     // Resolve sender (use stored email credentials or system default):
     if ($from === null || in_array($from, Credentials::$sysUseId)) {
         $from = (int) Credentials::model()->getDefaultUserAccount($from);
         // Set to the user's name/email if no valid defaults found:
         if ($from == Credentials::LEGACY_ID) {
             $from = array('name' => Yii::app()->params->profile->fullName, 'address' => Yii::app()->params->profile->emailAddress);
         }
     }
     if (is_numeric($from)) {
         $eml->credId = $from;
     } else {
         $eml->from = $from;
     }
     // Set other attributes
     $eml->subject = $subject;
     $eml->message = $message;
     $eml->attachments = $attachments;
     return $eml->deliver();
 }
コード例 #24
0
ファイル: ua.php プロジェクト: nordquip/sousms
if (!isset($_POST["jsondata"])) {
    header('HTTP/1.1 404 Not Found');
    exit;
} else {
    try {
        $req = json_decode($_POST["jsondata"]);
        if (!isset($req->behavior)) {
            //these aren't the droids you're looking for...
            header('HTTP/1.1 404 Not Found');
            exit;
        } else {
            switch ($req->behavior) {
                case "getTokenFromCredentials":
                    $msg = new UATokenMessage();
                    // the constructor for Credentials can do some basic validation (or throw an exception)
                    $credentials = new Credentials($req->credentials->username, $req->credentials->password);
                    // the validate() method returns true if valid or false if invalid
                    if ($credentials->validate($token)) {
                        // the $token parameter was passed by reference and set inside validate()
                        $msg->token = $token;
                        //get the current time
                        $dt = new DateTime(null, new DateTimeZone("America/Los_Angeles"));
                        //expire the token in 10 seconds, this should probably reside inside validate
                        $dt->modify("+10 seconds");
                        $msg->expires = $dt->format(DateTime::RFC822);
                        //just some helpful status information for the caller
                        $msg->statuscode = 0;
                        $msg->statusdesc = "Login successful";
                    } else {
                        //bad credentials
                        $msg->statuscode = 1;
コード例 #25
0
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 *   License for the specific language governing permissions and limitations
 *   under the License.
 *
 * @version 1.3
 * @author dhermes@google.com
 * @copyright Google Inc, 2011
 * @package GShoppingContent
 */
// import our library
require_once 'GShoppingContent.php';
require_once 'BuildMockProduct.php';
// Get the user credentials
$creds = Credentials::get();
// Create a client for our merchant and log in
$client = new GSC_Client($creds["merchantId"]);
$client->login($creds["email"], $creds["password"]);
// Now enter some product data
$id = "SKU124";
$country = "US";
$language = "en";
$product = buildMockProduct($id, $country, $language);
// Finally send the data to the API
$warnings = false;
$dryRun = true;
$entry = $client->insertProduct($product, $warnings, $dryRun);
echo 'Dry Run Insert Response: ' . $entry->getTitle() . "\n\n";
// Verify the product still doesn't exist
$errors = $client->getProduct($id, $country, $language);
コード例 #26
0
<div class="page-title icon profile">
    <h2><?php 
echo Yii::t('profile', 'Manage Passwords for Third-Party Applications');
?>
</h2>
</div>
<div class="credentials-storage">
<?php 
$crit = new CDbCriteria(array('condition' => '(userId=:uid OR userId=-1) AND modelClass != "TwitterApp" AND 
        modelClass != "GoogleProject"', 'order' => 'name ASC', 'params' => array(':uid' => $profile->user->id)));
$staticModel = Credentials::model();
$staticModel->private = 0;
if (Yii::app()->user->checkAccess('CredentialsSelectNonPrivate', array('model' => $staticModel))) {
    $crit->addCondition('private=0', 'OR');
}
$dp = new CActiveDataProvider('Credentials', array('criteria' => $crit));
$this->widget('zii.widgets.CListView', array('dataProvider' => $dp, 'itemView' => '_credentialsView', 'itemsCssClass' => 'credentials-list', 'summaryText' => '', 'emptyText' => ''));
?>

    <?php 
echo CHtml::beginForm(array('/profile/createUpdateCredentials'), 'get', array('onSubmit' => 'return validate ();'));
echo CHtml::submitButton(Yii::t('app', 'Add New'), array('class' => 'x2-button', 'style' => 'float:left;margin-top:0'));
$modelLabels = Credentials::model()->authModelLabels;
unset($modelLabels['TwitterApp']);
$types = array_merge(array(null => '- ' . Yii::t('app', 'select a type') . ' -'), $modelLabels);
echo CHtml::dropDownList('class', 'EmailAccount', $types, array('options' => array_merge(array(null => array('selected' => 'selected')), array_fill_keys(array_keys($modelLabels), array('selected' => false))), 'class' => 'left x2-select'));
echo CHtml::endForm();
?>
</div>
コード例 #27
0
ファイル: inlineEmailForm.php プロジェクト: dsyman2/X2CRM
?>
    <div class='email-inputs form'>
        <div class="row">
            <div id="inline-email-errors" class="error" style="display:none"></div>
            <?php 
echo $form->errorSummary($this->model, Yii::t('app', "Please fix the following errors:"), null);
?>
        </div>
        <div class="row email-input-row credId-row" 
         <?php 
echo $this->hideFromField ? 'style="display: none;"' : '';
?>
>
            <?php 
echo $form->label($this->model, 'credId', array('class' => 'credId-label x2-email-label'));
echo Credentials::selectorField($this->model, 'credId');
?>
        </div>
    <div class='addressee-rows'>
        <div class="row email-input-row email-to-row show-input-name">
            <?php 
//echo $form->label($this->model, 'to', array('class' => 'x2-email-label'));
echo $form->textField($this->model, 'to', array('id' => 'email-to', 'class' => 'x2-default-field', 'data-default-text' => CHtml::encode(Yii::t('app', 'Addressees')), 'tabindex' => '1'));
?>
            <div class='toggle-container'>
                <a href="javascript:void(0)" 
                 id="cc-toggle"<?php 
if (!empty($this->model->cc)) {
    echo ' style="display:none;"';
}
?>
コード例 #28
0
ファイル: Credentials.php プロジェクト: keyeMyria/CRM
 /**
  * Getter for {@link defaultCredentials}
  * @param type $d
  * @return type
  */
 public function getDefaultCredentials($refresh = false)
 {
     if (!isset(self::$_defaultCredentials) || $refresh) {
         $allDefaults = Yii::app()->db->createCommand()->select('*')->from('x2_credentials_default')->queryAll();
         self::$_defaultCredentials = array_fill_keys(array_map(function ($d) {
             return $d['userId'];
         }, $allDefaults), array());
         foreach ($allDefaults as $d) {
             self::$_defaultCredentials[$d['userId']][$d['serviceType']] = $d['credId'];
         }
     }
     return self::$_defaultCredentials;
 }
コード例 #29
0
 public function execute(Request $request)
 {
     if (LOGGING) {
         Log::log(LoggingConstants::DEBUG, "commandmessage " . $this->operation . " operation");
     }
     /*Object*/
     $returnValue = null;
     if ($this->operation == "0") {
         /*IDestination*/
         $destObj = ORBConfig::getInstance()->getDataServices()->getDestinationManager()->getDestination($this->destination);
         /*Hashtable*/
         $headers = array();
         if ($destObj != null) {
             /*String*/
             $selectorName = $this->headers["DSSelector"];
             /*String*/
             $subtopic = $this->headers["DSSubtopic"];
             /*String*/
             $dsId = $this->headers["DSId"];
             /*Subscriber*/
             $subscriber = new Subscriber($selectorName, $destObj);
             $subscriber->setDSId($dsId);
             $subscriber->setSubtopic($subtopic);
             $guid = new GUID();
             $subscriber->setClientId($guid->toString());
             SubscriptionsManager::getInstance()->addSubscriber($dsId, $subscriber);
             $destObj->getServiceHandler()->handleSubscribe($subscriber);
         } else {
             /*String*/
             $error = "Unknown destination " . $this->destination . ". Cannot handle subscription request";
             if (LOGGING) {
                 Log::log(LoggingConstants::ERROR, $error);
             }
             return new ErrMessage($this->messageId, new Exception($error));
         }
         return new AckMessage($this->messageId, $clientId, null, $headers);
     } else {
         if ($this->operation == "1") {
             /*String*/
             $dsId = $this->headers["DSId"];
             /*Subscriber*/
             $subscriber = SubscriptionsManager::getInstance()->getSubscriber($dsId);
             if ($subscriber == null) {
                 return new ErrMessage($this->messageId, new Exception("Unable to unsubscribe - unknown client"));
             }
             /*IDestination*/
             $destination = $subscriber->getDestination();
             $destination->getServiceHandler()->handleUnsubscribe($subscriber);
             SubscriptionsManager::getInstance()->removeSubscriber($dsId);
         } else {
             if ($this->operation == "2") {
                 /*String*/
                 $dsId = $this->headers["DSId"];
                 /*Subscriber*/
                 $subscriber = SubscriptionsManager::getInstance()->getSubscriber($dsId);
                 if ($subscriber == null) {
                     /*String*/
                     $error = "Invalid client id " . $dsId;
                     if (LOGGING) {
                         Log::log(LoggingConstants::ERROR, $error);
                     }
                     return new ErrMessage($this->messageId, new Exception($error));
                 }
                 /*IDestination*/
                 $destination = $subscriber->getDestination();
                 //Log::log( LoggingConstants::INFO, "Getting messages from " . $destination->getServiceHandler() );
                 /*ArrayList*/
                 $messages = $destination->getServiceHandler()->getMessages($subscriber);
                 $subscriber->setLastRequestTime(microtime(true));
                 if (count($messages) == 0) {
                     return new AckMessage(null, null, null, array());
                 }
                 return $this->createCmdMessage("4", $messages);
             } else {
                 if ($this->operation == "5") {
                     /*Hashtable*/
                     $headers = array();
                     $guid = new GUID();
                     $headers["DSId"] = $guid->toString();
                     return new AckMessage($this->messageId, $this->clientId, null, $headers);
                 } else {
                     if ($this->operation == "9") {
                         ThreadContext::setCallerCredentials(null);
                     } else {
                         if ($this->operation == "8") {
                             $arr = $this->body->getBody();
                             $adaptingType = $arr[0];
                             $authData = split(":", base64_decode($adaptingType->defaultAdapt()));
                             $credentials = new Credentials($authData[0], $authData[1]);
                             $authHandler = ORBSecurity::getAuthenticationHandler(ThreadContext::getORBConfig());
                             if (LOGGING) {
                                 Log::log(LoggingConstants::DEBUG, "got auth handler " . get_class($authHandler));
                             }
                             if ($authHandler == null) {
                                 $errorMessage = new ErrMessage($this->messageId, new ServiceException("Missing authentication handler"));
                                 $errorMessage->faultCode = "Client.Authentication";
                                 return $errorMessage;
                             }
                             try {
                                 $authHandler->checkCredentials($credentials->getUserId(), $credentials->getPassword(), $request);
                                 if (LOGGING) {
                                     Log::log(LoggingConstants::DEBUG, "credentials are valid ");
                                 }
                                 ThreadContext::setCallerCredentials($credentials);
                             } catch (Exception $e) {
                                 if (LOGGING) {
                                     Log::log(LoggingConstants::EXCEPTION, "authentication exception" . $e);
                                 }
                                 $errorMessage = new ErrMessage($this->messageId, $e);
                                 $errorMessage->faultCode = "Client.Authentication";
                                 return $errorMessage;
                             }
                             return new AckMessage($this->messageId, $this->clientId, null);
                         }
                     }
                 }
             }
         }
     }
     //echo $this->operation; exit;
     return new AckMessage($this->messageId, $this->clientId, $returnValue, array());
 }
コード例 #30
0
 public function testToArray()
 {
     $expected = [ConfigEnum::ID => '', ConfigEnum::KEY => ''];
     $this->assertEquals($expected, $this->credentials->toArray());
 }