/** * Aggiorna la selezione delle tematiche da sincronizzare * @param eZHTTPTool $http */ public function modifySelection($http) { if ($http->hasPostVariable('BrowseActionName') && $http->postVariable('BrowseActionName') == 'SelectDestinationNodeID') { // Scelta del nodo di destinazione $nodeIDArray = $http->postVariable('SelectedNodeIDArray'); $this->object->setAttribute('destination_node_id', $nodeIDArray[0]); $this->object->store(); } else { // Abilitazione e disabilitazione delle tematiche $tematicheChanged = false; foreach ($http->attribute('post') as $key => $value) { $action = explode('_', $key); if ($action[0] == 'DisableTag') { if (($_key = array_search($value, $this->getTematiche())) !== false) { $_tematiche = $this->getTematiche(); unset($_tematiche[$_key]); $this->object->setAttribute('tags', implode(';', $_tematiche)); } $tematicheChanged = true; } else { if ($action[0] == 'EnableTag') { $_tematiche = $this->getTematiche(); $_tematiche[] = $value; $this->object->setAttribute('tags', implode(';', $_tematiche)); $tematicheChanged = true; } } } if ($tematicheChanged) { $this->object->store(); } } }
public function requestToken($Account) { $NGPushIni = eZINI::instance('ngpush.ini'); $SiteIni = eZINI::instance('site.ini'); $AccessToken = $NGPushIni->variable($Account, 'AccessToken'); // If access tokens are given if ($AccessToken) { //Save request signing tokens to cache ngPushBase::save_token($Account, $AccessToken, 'main_token'); } else { $AdministrationUrl = '/'; eZURI::transformURI($AdministrationUrl, false, 'full'); $AdministrationUrl = base64_encode($AdministrationUrl); $SettingsBlock = base64_encode($Account); $redirectUrl = 'http://' . $NGPushIni->variable('PushNodeSettings', 'ConnectURL') . '/redirect.php/' . $AdministrationUrl . '/' . $SettingsBlock . '?case=facebook'; $Facebook = new Facebook(array('appId' => $NGPushIni->variable($Account, 'AppAPIKey'), 'secret' => $NGPushIni->variable($Account, 'AppSecret'))); $Permissions = array('publish_actions', 'user_posts'); if ($NGPushIni->variable($Account, 'EntityType') == 'page') { $Permissions[] = 'manage_pages'; } $state = md5(uniqid(rand(), true)); $http = eZHTTPTool::instance(); $http->setSessionVariable('ngpush_state', $state); $LoginUrl = $Facebook->getLoginUrl(array('redirect_uri' => $redirectUrl, 'scope' => implode($Permissions, ','), 'state' => $state)); self::$response['RequestPermissionsUrl'] = $LoginUrl; } }
static function fetchIDListByUserID($userID) { if ($userID == eZUser::anonymousId()) { $userCache = eZUSer::getUserCacheByAnonymousId(); $ruleArray = $userCache['discount_rules']; } else { $http = eZHTTPTool::instance(); $handler = eZExpiryHandler::instance(); $expiredTimeStamp = 0; if ($handler->hasTimestamp('user-discountrules-cache')) { $expiredTimeStamp = $handler->timestamp('user-discountrules-cache'); } $ruleTimestamp =& $http->sessionVariable('eZUserDiscountRulesTimestamp'); $ruleArray = false; // check for cached version in session if ($ruleTimestamp > $expiredTimeStamp) { if ($http->hasSessionVariable('eZUserDiscountRules' . $userID)) { $ruleArray =& $http->sessionVariable('eZUserDiscountRules' . $userID); } } if (!is_array($ruleArray)) { $ruleArray = self::generateIDListByUserID((int) $userID); $http->setSessionVariable('eZUserDiscountRules' . $userID, $ruleArray); $http->setSessionVariable('eZUserDiscountRulesTimestamp', time()); } } $rules = array(); foreach ($ruleArray as $ruleRow) { $rules[] = $ruleRow['id']; } return $rules; }
/** * Set parameters from post data, expects post data to be validated by * {@link eZGmapLocationType::validateObjectAttributeHTTPInput()} * * @param eZHTTPTool $http * @param string $base * @param eZContentObjectAttribute $contentObjectAttribute */ function fetchObjectAttributeHTTPInput($http, $base, $contentObjectAttribute) { $validPostData = false; if ($http->hasPostVariable($base . '_data_gmaplocation_latitude_' . $contentObjectAttribute->attribute('id')) && $http->hasPostVariable($base . '_data_gmaplocation_longitude_' . $contentObjectAttribute->attribute('id'))) { $latitude = $http->postVariable($base . '_data_gmaplocation_latitude_' . $contentObjectAttribute->attribute('id')); $longitude = $http->postVariable($base . '_data_gmaplocation_longitude_' . $contentObjectAttribute->attribute('id')); $validPostData = $latitude !== '' && $longitude !== '' && is_numeric($latitude) && is_numeric($longitude); } if ($validPostData) { $address = ''; if ($http->hasPostVariable($base . '_data_gmaplocation_address_' . $contentObjectAttribute->attribute('id'))) { $address = $http->postVariable($base . '_data_gmaplocation_address_' . $contentObjectAttribute->attribute('id')); $address = htmlentities($address, ENT_QUOTES, 'UTF-8'); } if ($contentObjectAttribute->attribute('data_int') != 0) { $location = eZGmapLocation::fetch($contentObjectAttribute->attribute('id'), $contentObjectAttribute->attribute('version')); $location->setAttribute('latitude', $latitude); $location->setAttribute('longitude', $longitude); $location->setAttribute('address', $address); } else { $location = new eZGmapLocation(array('contentobject_attribute_id' => $contentObjectAttribute->attribute('id'), 'contentobject_version' => $contentObjectAttribute->attribute('version'), 'latitude' => $latitude, 'longitude' => $longitude, 'address' => $address)); $contentObjectAttribute->setAttribute('data_int', 1); } $contentObjectAttribute->setContent($location); } else { if ($contentObjectAttribute->attribute('data_int') != 0) { $contentObjectAttribute->setAttribute('data_int', 0); eZGmapLocation::removeById($contentObjectAttribute->attribute('id'), $contentObjectAttribute->attribute('version')); } } return true; }
function get($oid) { $oidroot = $this->oidRoot(); $oidroot = $oidroot[0]; switch (preg_replace('/\\.0$/', '', $oid)) { case $oidroot . '1.1': if (in_array('ezfind', eZExtension::activeExtensions())) { $ini = eZINI::instance('solr.ini'); $data = eZHTTPTool::getDataByURL($ini->variable('SolrBase', 'SearchServerURI') . "/admin/ping", false); if (stripos($data, '<str name="status">OK</str>') !== false) { $status = 1; } else { $status = 0; } } else { $status = -1; } return array('oid' => $oid, 'type' => eZSNMPd::TYPE_INTEGER, 'value' => $status); case $oidroot . '1.2': if (in_array('ezfind', eZExtension::activeExtensions())) { $ini = eZINI::instance('solr.ini'); $data = eZHTTPTool::getDataByURL($ini->variable('SolrBase', 'SearchServerURI') . "/admin/stats.jsp", false); if (preg_match('#<stat +name="numDocs" +>[ \\t\\r\\n]*(\\d+)[ \\t\\r\\n]*</stat>#', $data, $status)) { $status = $status[1]; } else { $status = -2; } } else { $status = -1; } return array('oid' => $oid, 'type' => eZSNMPd::TYPE_INTEGER, 'value' => $status); } return self::NO_SUCH_OID; }
function answer() { if ($this->Answer !== false) { return $this->Answer; } $http = eZHTTPTool::instance(); $prefix = eZSurveyType::PREFIX_ATTRIBUTE; $postSurveyAnswer = $prefix . '_ezsurvey_answer_' . $this->ID . '_' . $this->contentObjectAttributeID(); if ($http->hasPostVariable($postSurveyAnswer)) { $surveyAnswer = $http->postVariable($postSurveyAnswer); return $surveyAnswer; } $user = eZUser::instance(); $value = $this->Default; if ($user->isLoggedIn() === true) { switch ($this->Text3) { case "user_email": $value = $this->userEmail(); break; case "user_name": $value = $this->userName(); break; default: $value = $this->defaultUserValue(); } } return $value; }
/** * Handles redirection to the mobile optimized interface * */ public function redirect() { $http = eZHTTPTool::instance(); $currentSiteAccess = eZSiteAccess::current(); if ($http->hasGetVariable('notmobile')) { setcookie('eZMobileDeviceDetect', 1, time() + (int) eZINI::instance()->variable('SiteAccessSettings', 'MobileDeviceDetectCookieTimeout'), '/'); $http->redirect(eZSys::indexDir()); eZExecution::cleanExit(); } if (!isset($_COOKIE['eZMobileDeviceDetect']) && !in_array($currentSiteAccess['name'], eZINI::instance()->variable('SiteAccessSettings', 'MobileSiteAccessList'))) { $currentUrl = eZSys::serverURL() . eZSys::requestURI(); $redirectUrl = eZINI::instance()->variable('SiteAccessSettings', 'MobileSiteAccessURL'); // Do not redirect if already on the redirect url if (strpos($currentUrl, $redirectUrl) !== 0) { // Default siteaccess name needs to be removed from the uri when redirecting $uri = explode('/', ltrim(eZSys::requestURI(), '/')); if (array_shift($uri) == $currentSiteAccess['name']) { $http->redirect($redirectUrl . '/' . implode('/', $uri)); } else { $http->redirect($redirectUrl . eZSys::requestURI()); } } eZExecution::cleanExit(); } }
static function createClass( $tpl, $module, $stepArray, $basePath, $storageName = false, $metaData = false ) { if ( !$storageName ) { $storageName = 'eZWizard'; } if ( !$metaData ) { $http = eZHTTPTool::instance(); $metaData = $http->sessionVariable( $storageName . '_meta' ); } if ( !isset( $metaData['current_step'] ) || $metaData['current_step'] < 0 ) { $metaData['current_step'] = 0; eZDebug::writeNotice( 'Setting wizard step to : ' . $metaData['current_step'], __METHOD__ ); } $currentStep = $metaData['current_step']; if ( count( $stepArray ) <= $currentStep ) { eZDebug::writeError( 'Invalid wizard step count: ' . $currentStep, __METHOD__ ); return false; } $filePath = $basePath . $stepArray[$currentStep]['file']; if ( !file_exists( $filePath ) ) { eZDebug::writeError( 'Wizard file not found : ' . $filePath, __METHOD__ ); return false; } include_once( $filePath ); $className = $stepArray[$currentStep]['class']; eZDebug::writeNotice( 'Creating class : ' . $className, __METHOD__ ); $returnClass = new $className( $tpl, $module, $storageName ); if ( isset( $stepArray[$currentStep]['operation'] ) ) { $operation = $stepArray[$currentStep]['operation']; return $returnClass->$operation(); eZDebug::writeNotice( 'Running : "' . $className . '->' . $operation . '()". Specified in StepArray', __METHOD__ ); } if ( isset( $metaData['current_stage'] ) ) { $returnClass->setMetaData( 'current_stage', $metaData['current_stage'] ); eZDebug::writeNotice( 'Setting wizard stage to : ' . $metaData['current_stage'], __METHOD__ ); } return $returnClass; }
/** * Returns block item XHTML * * @param mixed $args * @return array */ public static function getNextItems($args) { $http = eZHTTPTool::instance(); $tpl = eZTemplate::factory(); $result = array(); $galleryID = $http->postVariable('gallery_id'); $offset = $http->postVariable('offset'); $limit = $http->postVariable('limit'); $galleryNode = eZContentObjectTreeNode::fetch($galleryID); if ($galleryNode instanceof eZContentObjectTreeNode) { $params = array('Depth' => 1, 'Offset' => $offset, 'Limit' => $limit); $pictureNodes = $galleryNode->subtree($params); foreach ($pictureNodes as $validNode) { $tpl->setVariable('node', $validNode); $tpl->setVariable('view', 'block_item'); $tpl->setVariable('image_class', 'blockgallery1'); $content = $tpl->fetch('design:node/view/view.tpl'); $result[] = $content; if ($counter === $limit) { break; } } } return $result; }
function execute($process, $event) { $parameters = $process->attribute('parameter_list'); $http = eZHTTPTool::instance(); eZDebug::writeNotice($parameters, "parameters"); $orderID = $parameters['order_id']; $order = eZOrder::fetch($orderID); if (empty($orderID) || get_class($order) != 'ezorder') { eZDebug::writeWarning("Can't proceed without a Order ID.", "SimpleStockCheck"); return eZWorkflowEventType::STATUS_FETCH_TEMPLATE_REPEAT; } // Decrement the quantitity field $order = eZOrder::fetch($orderID); $productCollection = $order->productCollection(); $ordereditems = $productCollection->itemList(); foreach ($ordereditems as $item) { $contentObject = $item->contentObject(); $contentObjectVersion = $contentObject->version($contentObject->attribute('current_version')); $contentObjectAttributes = $contentObjectVersion->contentObjectAttributes(); foreach (array_keys($contentObjectAttributes) as $key) { $contentObjectAttribute = $contentObjectAttributes[$key]; $contentClassAttribute = $contentObjectAttribute->contentClassAttribute(); // Each attribute has an attribute identifier called 'quantity' that identifies it. if ($contentClassAttribute->attribute("identifier") == "quantity") { $contentObjectAttribute->setAttribute("data_int", $contentObjectAttribute->attribute("value") - $item->ItemCount); $contentObjectAttribute->store(); } } } return eZWorkflowEventType::STATUS_ACCEPTED; }
static function gather() { $contentTypes = array('Objects (including users)' => array('table' => 'ezcontentobject'), 'Users' => array('table' => 'ezuser'), 'Nodes' => array('table' => 'ezcontentobject_tree'), 'Content Classes' => array('table' => 'ezcontentclass'), 'Information Collections' => array('table' => 'ezinfocollection'), 'Pending notification events' => array('table' => 'eznotificationevent', 'wherecondition' => 'status = 0'), 'Objects pending indexation' => array('table' => 'ezpending_actions', 'wherecondition' => "action = 'index_object'"), 'Binary files (content)' => array('table' => 'ezbinaryfile'), 'Image files (content)' => array('table' => 'ezimagefile'), 'Media files (content)' => array('table' => 'ezmedia'), 'Maximum children per node' => array('sql' => 'SELECT MAX(tot) AS NUM FROM ( SELECT count(*) AS tot FROM ezcontentobject_tree GROUP BY parent_node_id ) nodes'), 'Maximum nodes per object' => array('sql' => 'SELECT MAX(tot) AS NUM FROM ( SELECT count(*) AS tot FROM ezcontentobject_tree GROUP BY contentobject_id ) nodes'), 'Maximum incoming relations to an object' => array('sql' => 'SELECT MAX(tot) AS NUM FROM ( SELECT count(*) AS tot FROM ezcontentobject_link GROUP BY to_contentobject_id ) links', 'nvl' => 0), 'Maximum outgoing relations from an object' => array('sql' => 'SELECT MAX(tot) AS NUM FROM ( SELECT count(*) AS tot FROM ezcontentobject_link GROUP BY from_contentobject_id ) links', 'nvl' => 0)); $db = eZDB::instance(); $contentList = array(); foreach ($contentTypes as $key => $desc) { if (isset($desc['table'])) { $sql = 'SELECT COUNT(*) AS NUM FROM ' . $desc['table']; if (@$desc['wherecondition']) { $sql .= ' WHERE ' . $desc['wherecondition']; } } else { $sql = $desc['sql']; } $count = $db->arrayQuery($sql); $contentList[$key] = $count[0]['NUM'] === null ? $desc['nvl'] : $count[0]['NUM']; } if (in_array('ezfind', eZExtension::activeExtensions())) { $ini = eZINI::instance('solr.ini'); $ezfindpingurl = $ini->variable('SolrBase', 'SearchServerURI') . "/admin/stats.jsp"; $data = eZHTTPTool::getDataByURL($ezfindpingurl, false); //var_dump( $data ); if (preg_match('#<stat +name="numDocs" ?>([^<]+)</stat>#', $data, $matches)) { $contentList['Documents in SOLR'] = trim($matches[1]); } else { $contentList['Documents in SOLR'] = 'Unknown'; } } return $contentList; }
public static function push($args) { if (!self::userHasAccessToModule()) { return self::$noAccessResponse; } $http = eZHTTPTool::instance(); if ($http->hasPostVariable('nodeID') && $http->hasPostVariable('accountID')) { $NGPushIni = eZINI::instance('ngpush.ini'); $NGPushAccount = $http->postVariable('accountID'); $NGPushNodeID = $http->postVariable('nodeID'); switch ($NGPushIni->variable($NGPushAccount, 'Type')) { case 'twitter': $TwitterStatus = $http->postVariable('tw_status'); return ngPushTwitterStatus::push($NGPushAccount, $TwitterStatus); break; case 'facebook_feed': $Arguments = array('name' => $http->postVariable('fb_name'), 'description' => $http->postVariable('fb_description'), 'message' => $http->postVariable('fb_message'), 'link' => $http->postVariable('fb_link'), 'picture' => $http->postVariable('fb_picture')); return ngPushFacebookFeed::push($NGPushAccount, $Arguments); break; default: break; } } return array('status' => 'error', 'message' => 'Account not found!'); }
public function setState() { $http = eZHTTPTool::instance(); if ($http->hasGetVariable('state')) { $this->connection->setState(base64_encode($http->getVariable('state'))); } }
function fetchAccountInformation(&$module) { $http = eZHTTPTool::instance(); $http->setSessionVariable('RedirectAfterLogin', '/shop/basket/'); $http->setSessionVariable('DoCheckoutAutomatically', true); $module->redirectTo('/user/login/'); }
/** * @return string */ protected function acquireToken() { $response = eZHTTPTool::getDataByURL($this->tokenAcquireApiUrl); $xml = simplexml_load_string($response); return (string)$xml->data->string; }
/** * Some parts of eZ do not benefit from the enhanced checks implemented * in eZSys::isSSLNow(), especially when using an SSL reverse proxy * configured to send the HTTP_X_FORWARDED_PROTO header. * * @link http://issues.ez.no/21731 */ public function test_createRedirectUrl() { $path = '/a/root/rel/ative'; self::assertEquals('http://example.com' . $path, eZHTTPTool::createRedirectUrl($path, array())); $_SERVER['HTTP_X_FORWARDED_PROTO'] = 'https'; self::assertEquals('https://example.com' . $path, eZHTTPTool::createRedirectUrl($path, array())); unset($_SERVER['HTTP_X_FORWARDED_PROTO']); }
/** * Fetches the HTTP POST input and stores it in the data instance * * @param eZHTTPTool $http * @param string $base * @param eZContentObjectAttribute $contentObjectAttribute * * @return bool */ function fetchObjectAttributeHTTPInput($http, $base, $contentObjectAttribute) { $classList = $http->postVariable($base . self::CLASS_LIST_VARIABLE . $contentObjectAttribute->attribute("id"), array()); $classList = !is_array($classList) ? array() : $classList; $validClassIdentifiers = array(); foreach ($classList as $classIdentifier) { if (eZContentClass::exists($classIdentifier, eZContentClass::VERSION_STATUS_DEFINED, false, true)) { $validClassIdentifiers[] = $classIdentifier; } } if (!empty($validClassIdentifiers)) { $contentObjectAttribute->setAttribute(self::CLASS_LIST_FIELD, implode(",", $validClassIdentifiers)); } else { $contentObjectAttribute->setAttribute(self::CLASS_LIST_FIELD, ""); } return true; }
public function getMediaRecent($pageID = false, $limit = 20) { $result = array('result' => array()); $accumulator = $this->debugAccumulatorGroup . '_instagram_media_recent'; eZDebug::accumulatorStart($accumulator, $this->debugAccumulatorGroup, 'media_recent'); $cacheFileHandler = $this->getCacheFileHandler('_media_recent', array($pageID, $limit)); try { if ($this->isCacheExpired($cacheFileHandler)) { eZDebug::writeDebug(array('page_id' => $pageID, 'limit' => $limit), self::$debugMessagesGroup); $items = array(); $userData = eZHTTPTool::getDataByURL('https://api.instagram.com/v1/users/search?' . 'q=' . $pageID . '&' . 'client_id=' . $this->API['key']); $userID = false; if ($userData !== false) { $userDataArray = json_decode($userData, true); if (count($userDataArray['data'])) { foreach ($userDataArray['data'] as $user) { if ($user['username'] == $pageID) { $userID = $user['id']; break; } } } } if ($userID !== false) { $leftLimit = $limit; $feedData = eZHTTPTool::getDataByURL('https://api.instagram.com/v1/users/' . $userID . '/media/recent/?' . 'access_token=' . $this->API['token']); if ($feedData !== false) { $feedDataArray = json_decode($feedData, true); if (isset($feedDataArray['data'])) { $items = array_merge($items, array_slice($feedDataArray['data'], 0, $leftLimit)); $leftLimit = $leftLimit - count($feedDataArray['data']); } $endlessLoopBreaker = 0; while ($endlessLoopBreaker < 50 && $leftLimit > 0 && isset($feedDataArray['pagination']['next_url'])) { $endlessLoopBreaker++; $feedData = eZHTTPTool::getDataByURL($feedDataArray['pagination']['next_url']); if ($feedData !== false) { $feedDataArray = json_decode($feedData, true); $items = array_merge($items, array_slice($feedDataArray['data'], 0, $leftLimit)); } $leftLimit = $leftLimit - count($feedDataArray['data']); } } } $cacheFileHandler->fileStoreContents($cacheFileHandler->filePath, serialize($items)); } else { $items = unserialize($cacheFileHandler->fetchContents()); } eZDebug::accumulatorStop($accumulator); $result['result'] = $items; return $result; } catch (Exception $e) { eZDebug::accumulatorStop($accumulator); eZDebug::writeError($e->getMessage(), self::$debugMessagesGroup); return $result; } }
function sectionEditActionCheck( $module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $fromLanguage ) { if ( $module->isCurrentAction( 'SectionEdit' ) ) { $http = eZHTTPTool::instance(); if ( $http->hasPostVariable( 'SelectedSectionId' ) ) { $selectedSectionID = (int) $http->postVariable( 'SelectedSectionId' ); $selectedSection = eZSection::fetch( $selectedSectionID ); if ( is_object( $selectedSection ) ) { $currentUser = eZUser::currentUser(); if ( $currentUser->canAssignSectionToObject( $selectedSectionID, $object ) ) { $db = eZDB::instance(); $db->begin(); $assignedNodes = $object->attribute( 'assigned_nodes' ); if ( count( $assignedNodes ) > 0 ) { foreach ( $assignedNodes as $node ) { if ( eZOperationHandler::operationIsAvailable( 'content_updatesection' ) ) { $operationResult = eZOperationHandler::execute( 'content', 'updatesection', array( 'node_id' => $node->attribute( 'node_id' ), 'selected_section_id' => $selectedSectionID ), null, true ); } else { eZContentOperationCollection::updateSection( $node->attribute( 'node_id' ), $selectedSectionID ); } } } else { // If there are no assigned nodes we should update db for the current object. $objectID = $object->attribute( 'id' ); $db->query( "UPDATE ezcontentobject SET section_id='$selectedSectionID' WHERE id = '$objectID'" ); $db->query( "UPDATE ezsearch_object_word_link SET section_id='$selectedSectionID' WHERE contentobject_id = '$objectID'" ); } $object->expireAllViewCache(); $db->commit(); } else { eZDebug::writeError( "You do not have permissions to assign the section <" . $selectedSection->attribute( 'name' ) . "> to the object <" . $object->attribute( 'name' ) . ">." ); } $module->redirectToView( 'edit', array( $object->attribute( 'id' ), $editVersion, $editLanguage, $fromLanguage ) ); } } } }
/** * This method is used to process the second part of authentication workflow, after redirect * * @return array Array with status and user details */ public function processAuth() { $ngConnectINI = eZINI::instance('ngconnect.ini'); $http = eZHTTPTool::instance(); $consumerKey = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerKey')); $consumerSecret = trim($ngConnectINI->variable('LoginMethod_twitter', 'AppConsumerSecret')); if (empty($consumerKey) || empty($consumerSecret)) { return array('status' => 'error', 'message' => 'Consumer key or consumer secret undefined.'); } $oAuthToken = trim($http->getVariable('oauth_token', '')); $oAuthVerifier = trim($http->getVariable('oauth_verifier', '')); $state = trim($http->getVariable('state', '')); if (empty($oAuthToken) || empty($oAuthVerifier) || empty($state)) { return array('status' => 'error', 'message' => 'oauth_token, oauth_verifier or state GET parameters undefined.'); } if (!$http->hasSessionVariable('NGConnectOAuthState') || $state != $http->sessionVariable('NGConnectOAuthState')) { $http->removeSessionVariable('NGConnectOAuthState'); return array('status' => 'error', 'message' => 'State parameter does not match stored value.'); } else { $http->removeSessionVariable('NGConnectOAuthState'); } if (!$http->hasSessionVariable('NGConnectOAuthToken') || !$http->hasSessionVariable('NGConnectOAuthTokenSecret') || $oAuthToken != $http->sessionVariable('NGConnectOAuthToken')) { $http->removeSessionVariable('NGConnectOAuthToken'); $http->removeSessionVariable('NGConnectOAuthTokenSecret'); return array('status' => 'error', 'message' => 'Token does not match stored value.'); } else { $oAuthTokenSecret = $http->sessionVariable('NGConnectOAuthTokenSecret'); $http->removeSessionVariable('NGConnectOAuthToken'); $http->removeSessionVariable('NGConnectOAuthTokenSecret'); } $connection = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthTokenSecret); $connection->host = self::TWITTER_API_URI; $accessToken = $connection->getAccessToken($oAuthVerifier); if (!(isset($accessToken['oauth_token']) && isset($accessToken['oauth_token_secret']))) { return array('status' => 'error', 'message' => 'Error while retrieving access token.'); } $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken['oauth_token'], $accessToken['oauth_token_secret']); $connection->host = self::TWITTER_API_URI; $user = $connection->get(self::TWITTER_USER_API_URI); if (!isset($user->id) || empty($user->id)) { return array('status' => 'error', 'message' => 'Invalid Twitter user.'); } if (isset($user->profile_image_url) && !empty($user->profile_image_url)) { $pictureUri = $user->profile_image_url; $imageSize = trim($ngConnectINI->variable('LoginMethod_twitter', 'ImageSize')); if ($imageSize == 'original') { //Hm... it seems there's no way to get the full size image through API //Even https://api.twitter.com/1/users/profile_image/username never returns full version //Replacing is not safe, but at least we're replacing last occurrence $pictureUri = substr_replace($user->profile_image_url, '', strrpos($user->profile_image_url, '_normal'), 7); } } else { $pictureUri = ''; } $result = array('status' => 'success', 'login_method' => 'twitter', 'id' => $user->id, 'first_name' => isset($user->name) ? $user->name : '', 'last_name' => '', 'email' => '', 'picture' => $pictureUri); return $result; }
/** * Provides suggestion results when adding tags to object * * @static * @param mixed $args * @return array */ public static function suggest($args) { $tags = array(); $siteINI = eZINI::instance('site.ini'); if ($siteINI->variable('SearchSettings', 'SearchEngine') == 'ezsolr' && class_exists('eZSolr')) { $tagsCount = 1; $filteredTagsArray = array(); $http = eZHTTPTool::instance(); $tagsString = $http->postVariable('tags_string'); $tagsArray = explode('|#', $tagsString); $subTreeLimit = $http->postVariable('subtree_limit'); $hideRootTag = $http->postVariable('hide_root_tag') == '1' ? true : false; if (!empty($tagsArray) && strlen(trim($tagsArray[0])) > 0) { $solrFilter = '"' . trim($tagsArray[0]) . '"'; $filteredTagsArray[] = strtolower(trim($tagsArray[0])); for ($i = 1; $i < count($tagsArray); $i++) { if (strlen(trim($tagsArray[$i])) > 0) { $solrFilter = $solrFilter . ' OR "' . trim($tagsArray[$i]) . '"'; $filteredTagsArray[] = strtolower(trim($tagsArray[$i])); $tagsCount++; } } $solrFilter = 'ezf_df_tags:(' . $solrFilter . ')'; $solrSearch = new eZSolr(); $params = array('SearchOffset' => 0, 'SearchLimit' => 0, 'Facet' => array(array('field' => 'ezf_df_tags', 'limit' => 5 + $tagsCount, 'mincount', 1)), 'SortBy' => null, 'Filter' => $solrFilter, 'QueryHandler' => 'ezpublish', 'FieldsToReturn' => null); $searchResult = $solrSearch->search('', $params); $facetResult = $searchResult['SearchExtras']->attribute('facet_fields'); $facetResult = $facetResult[0]['nameList']; $tags = array(); foreach ($facetResult as $facetValue) { if (!in_array(strtolower($facetValue), $filteredTagsArray)) { $tags[] = trim($facetValue); } } if (!empty($tags)) { $tags = eZTagsObject::fetchByKeyword(array($tags)); } } } $returnArray = array(); $returnArray['status'] = 'success'; $returnArray['message'] = ''; $returnArray['tags'] = array(); foreach ($tags as $tag) { if (!$subTreeLimit > 0 || $subTreeLimit > 0 && strpos($tag->attribute('path_string'), '/' . $subTreeLimit . '/') !== false) { if (!$hideRootTag || $hideRootTag && $tag->attribute('id') != $subTreeLimit) { $returnArrayChild = array(); $returnArrayChild['tag_parent_id'] = (int) $tag->attribute('parent_id'); $returnArrayChild['tag_parent_name'] = $tag->hasParent() ? $tag->getParent()->attribute('keyword') : ''; $returnArrayChild['tag_name'] = $tag->attribute('keyword'); $returnArrayChild['tag_id'] = (int) $tag->attribute('id'); $returnArray['tags'][] = $returnArrayChild; } } } return $returnArray; }
public static function getDataByURL($url, array $aCurlParams = array(), $justCheckURL = false, $userAgent = false) { if (in_array(CURLOPT_RETURNTRANSFER, $aCurlParams) && isset($aCurlParams[CURLOPT_RETURNTRANSFER]) && !$aCurlParams[CURLOPT_RETURNTRANSFER]) { $justCheckURL = true; } else { $aCurlParams[CURLOPT_RETURNTRANSFER] = true; } if (!extension_loaded('curl') || !count($aCurlParams)) { return eZHTTPTool::getDataByURL($url, $justCheckURL, $userAgent); } $ch = curl_init($url); if ($justCheckURL) { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); } if ($userAgent) { curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); } $ini = eZINI::instance(); $proxy = $ini->hasVariable('ProxySettings', 'ProxyServer') ? $ini->variable('ProxySettings', 'ProxyServer') : false; // If we should use proxy if ($proxy) { curl_setopt($ch, CURLOPT_PROXY, $proxy); $userName = $ini->hasVariable('ProxySettings', 'User') ? $ini->variable('ProxySettings', 'User') : false; $password = $ini->hasVariable('ProxySettings', 'Password') ? $ini->variable('ProxySettings', 'Password') : false; if ($userName) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$userName}:{$password}"); } } foreach ($aCurlParams as $iCurlOption => $mCurlParam) { curl_setopt($ch, $iCurlOption, $mCurlParam); } // If we should check url without downloading data from it. if ($justCheckURL) { if (!curl_exec($ch)) { curl_close($ch); return false; } curl_close($ch); return true; } // Getting data // ob_start(); $data = curl_exec($ch); $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($responseCode != 200 || !$data) { curl_close($ch); // ob_end_clean(); return false; } curl_close($ch); // $data = ob_get_contents(); // ob_end_clean(); return $data; }
/** * @dataProvider providerTestGetDataByURL */ public function testGetDataByURL($expectedDataResult, $url, $justCheckURL = false, $userAgent = false) { $this->assertEquals(eZHTTPTool::getDataByURL($url, $justCheckURL, $userAgent), $expectedDataResult); // There's no way to test the whole method without refactoring it. if (extension_loaded('curl')) { $this->markTestIncomplete('cURL behaviour tested, not fopen()'); } else { $this->markTestIncomplete('fopen() behaviour tested, not cURL'); } }
/** * @return array */ public function run() { $result = array(); $http = eZHTTPTool::instance(); $action = $http->getVariable('action', false); $parameters = $http->getVariable('parameters', false); $result['request'] = array('action' => $action, 'parameters' => $parameters); $result['response'] = call_user_func(array($this, $action), $parameters); return $result; }
/** * If you send an HTTP request using eZHTTPTool::sendHTTPRequest( ) to an * URL with a domain name containing a dash ( -), it's misunderpreted and * doesn't get executed. * * @link http://issues.ez.no/10651 */ public function testSendRequestContainingDashes() { self::markTestSkipped( "Test disabled pending update." ); $url = 'http://php-og.mgdm.net/'; $this->assertInternalType( PHPUnit_Framework_Constraint_IsType::TYPE_STRING, eZHTTPTool::sendHTTPRequest( $url, 80, false, 'eZ Publish', false ) ); }
/** * This method is used to process the second part of authentication workflow, after redirect * * @return array Array with status and user details */ public function processAuth() { $ngConnectINI = eZINI::instance('ngconnect.ini'); $http = eZHTTPTool::instance(); $appID = trim($ngConnectINI->variable('LoginMethod_facebook', 'FacebookAppID')); $appSecret = trim($ngConnectINI->variable('LoginMethod_facebook', 'FacebookAppSecret')); if (empty($appID) || empty($appSecret)) { return array('status' => 'error', 'message' => 'Facebook app ID or Facebook app secret undefined.'); } $code = trim($http->getVariable('code', '')); $state = trim($http->getVariable('state', '')); if (empty($code) || empty($state)) { return array('status' => 'error', 'message' => 'code or state GET parameters undefined.'); } if (!$http->hasSessionVariable('NGConnectOAuthState') || $state != $http->sessionVariable('NGConnectOAuthState')) { $http->removeSessionVariable('NGConnectOAuthState'); return array('status' => 'error', 'message' => 'State parameter does not match stored value.'); } else { $http->removeSessionVariable('NGConnectOAuthState'); } $callbackUri = self::CALLBACK_URI_PART; $loginWindowType = trim($ngConnectINI->variable('ngconnect', 'LoginWindowType')); if ($loginWindowType == 'popup') { $callbackUri = '/layout/set/ngconnect' . self::CALLBACK_URI_PART; } eZURI::transformURI($callbackUri, false, 'full'); $tokenUri = str_replace(array('%app_id%', '%site_url%', '%app_secret%', '%code%'), array(urlencode($appID), urlencode($callbackUri), urlencode($appSecret), urlencode($code)), self::TOKEN_URI); $accessToken = ngConnectFunctions::fetchDataFromUrl($tokenUri); if (!$accessToken) { return array('status' => 'error', 'message' => 'Error while retrieving access token.'); } $accessTokenJson = json_decode($accessToken, true); if ($accessTokenJson !== null) { return array('status' => 'error', 'message' => $accessTokenJson['error']['message']); } $graphUri = str_replace(array('%access_token%'), array(trim($accessToken)), self::GRAPH_URI); $graphResponse = ngConnectFunctions::fetchDataFromUrl($graphUri); if (!$graphResponse) { return array('status' => 'error', 'message' => 'Error while retrieving graph response.'); } $user = json_decode($graphResponse, true); if ($user === null) { return array('status' => 'error', 'message' => 'Invalid JSON data returned.'); } if (!isset($user['id'])) { return array('status' => 'error', 'message' => 'Invalid Facebook user.'); } $pictureUri = self::PICTURE_URI; $imageSize = trim($ngConnectINI->variable('LoginMethod_facebook', 'ImageSize')); if ($imageSize == 'original') { $pictureUri = $pictureUri . '?type=large'; } $result = array('status' => 'success', 'login_method' => 'facebook', 'id' => $user['id'], 'first_name' => isset($user['first_name']) ? $user['first_name'] : '', 'last_name' => isset($user['last_name']) ? $user['last_name'] : '', 'email' => isset($user['email']) ? $user['email'] : '', 'picture' => str_replace('%user_id%', $user['id'], $pictureUri)); return $result; }
function eZSetupSetPersistencePostVariable($var, $value) { $http = eZHTTPTool::instance(); if (is_array($value)) { foreach ($value as $valueKey => $valueItem) { $http->setPostVariable('P_' . $var . '-' . $valueKey, $valueItem); } } else { $http->setPostVariable('P_' . $var . '-0', $value); } }
function execute($process, $event) { $user = eZUser::currentUser(); if ($user->isLoggedIn()) { return eZWorkflowType::STATUS_ACCEPTED; } $http = eZHTTPTool::instance(); // Get current content object ID. $parameters = $process->attribute('parameter_list'); $nodeID = $parameters['node_id']; $node = eZContentObjectTreeNode::fetch($nodeID); if (!$node) { return eZWorkflowType::STATUS_REJECTED; } $objectID = $node->attribute('contentobject_id'); // Get newsletter hash $uri = $GLOBALS['eZRequestedURI']; $userParameters = $uri->userParameters(); $hash = isset($userParameters['hash']) ? $userParameters['hash'] : false; $sendItem = eZSendNewsletterItem::fetchByHash($hash); if ($http->hasSessionVariable('NewsletterNodeIDArray')) { $globalNodeIDList = $http->sessionVariable('NewsletterNodeIDArray'); if (in_array($nodeID, $http->sessionVariable('NewsletterNodeIDArray'))) { $sendID = $http->sessionVariable('NewletterNodeMap_' . $nodeID); $sendItem = eZSendNewsletterItem::fetch($sendID); $sendItem->addObjectRead($objectID); return eZWorkflowType::STATUS_ACCEPTED; } } // Get send item, and check that is contains the object id. if (!$sendItem) { return eZWorkflowType::STATUS_REJECTED; } $sendItemIDList = $sendItem->attribute('newsletter_related_object_list'); if (!$sendItemIDList || !in_array($objectID, $sendItemIDList)) { return eZWorkflowType::STATUS_REJECTED; } $sendNodeIDArray = array(); // Set session variables foreach ($sendItemIDList as $sendObjectID) { $sendObject = eZContentObject::fetch($sendObjectID); if ($sendObject) { foreach ($sendObject->assignedNodes(false) as $nodeArray) { $http->setSessionVariable('NewletterNodeMap_' . $nodeArray['node_id'], $sendItem->attribute('id')); $sendNodeIDArray[] = $nodeArray['node_id']; } } } $globalNodeIDList = array_unique(array_merge($globalNodeIDList, $sendNodeIDArray)); $http->setSessionVariable('NewsletterNodeIDArray', $globalNodeIDList); // Add object read $sendItem->addObjectRead($objectID); return eZWorkflowType::STATUS_ACCEPTED; }
function processEditActions(&$validation, $params) { $http = eZHTTPTool::instance(); if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Text') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Text') != $this->Text) { $inputXML = $http->postVariable('SurveyQuestion_' . $this->ID . '_Text'); $xmlData = "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/' xmlns:custom='http://ez.no/namespaces/ezpublish3/custom/' >"; $xmlData .= "<paragraph>"; $xmlData .= $inputXML; $xmlData .= "</paragraph>"; $xmlData .= "</section>"; $xmlObject = new eZXMLText($inputXML, null); $inputHandler = $xmlObject->attribute('input'); $data =& $inputHandler->convertInput($xmlData); $domString =& eZXMLTextType::domString($data[0]); $domString = preg_replace("#<paragraph> </paragraph>#", "<paragraph> </paragraph>", $domString); $domString = str_replace("<paragraph />", "", $domString); $domString = str_replace("<line />", "", $domString); $domString = str_replace("<paragraph></paragraph>", "", $domString); $domString = preg_replace("#<paragraph> </paragraph>#", "<paragraph />", $domString); $domString = preg_replace("#<paragraph></paragraph>#", "", $domString); $domString = preg_replace("#[\n]+#", "", $domString); $domString = preg_replace("#</line>#", "\n", $domString); $domString = preg_replace("#<paragraph>#", "\n\n", $domString); $xml = new eZXML(); $tmpDom = $xml->domTree($domString, array('CharsetConversion' => false)); $domString = eZXMLTextType::domString($tmpDom); $this->setAttribute('text', $domString); } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Text2') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Text2') != $this->Text2) { $this->setAttribute('text2', $http->postVariable('SurveyQuestion_' . $this->ID . '_Text2')); } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Text3') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Text3') != $this->Text3) { $this->setAttribute('text3', $http->postVariable('SurveyQuestion_' . $this->ID . '_Text3')); } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Num') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Num') != $this->Num) { $this->setAttribute('num', $http->postVariable('SurveyQuestion_' . $this->ID . '_Num')); } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Num2') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Num2') != $this->Num2) { $this->setAttribute('num2', $http->postVariable('SurveyQuestion_' . $this->ID . '_Num2')); } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Mandatory_Hidden')) { if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Mandatory')) { $newMandatory = 1; } else { $newMandatory = 0; } if ($newMandatory != $this->Mandatory) { $this->setAttribute('mandatory', $newMandatory); } } if ($http->hasPostVariable('SurveyQuestion_' . $this->ID . '_Default') && $http->postVariable('SurveyQuestion_' . $this->ID . '_Default') != $this->Default) { $this->setAttribute('default_value', $http->postVariable('SurveyQuestion_' . $this->ID . '_Default')); } }
static function redirectURI( $module, $default, $view = true, $disallowed = false, $preferredURI = false ) { $uri = false; $http = eZHTTPTool::instance(); if ( $preferredURI ) // check if $preferredURI is a valid URI return $preferredURI; if ( $view ) { if ( $http->hasSessionVariable( "LastAccessesURI", false ) ) { $uri = $http->sessionVariable( "LastAccessesURI" ); } } else { if ( $http->hasSessionVariable( "LastAccessedModifyingURI", false ) ) { $uri = $http->sessionVariable( "LastAccessedModifyingURI" ); } } if ( $uri !== false ) { $moduleURI = $module->functionURI( $module->currentView() ); // Check for correct module/view if ( substr( $uri, 0, strlen( $moduleURI ) ) == $moduleURI ) { // Check parameters $moduleURI = $module->currentRedirectionURI(); if ( $moduleURI == $uri ) $uri = false; } } // Check for disallowed urls if ( $uri !== false and is_array( $disallowed ) ) { if ( in_array( $uri, $disallowed ) ) $uri = false; } if ( $uri === false ) { // If no default is set we should return false. if ( $default === false ) return false; $uri = $default; } return $uri; }