/** * Updates user with provided auth data * * @param eZUser $user * @param array $authResult * * @return bool */ public static function updateUser($user, $authResult) { $currentTimeStamp = eZDateTime::currentTimeStamp(); $contentObject = $user->contentObject(); if (!$contentObject instanceof eZContentObject) { return false; } /** @var eZContentObjectVersion $version */ $version = $contentObject->currentVersion(); $db = eZDB::instance(); $db->begin(); $version->setAttribute('modified', $currentTimeStamp); $version->store(); self::fillUserObject($version->dataMap(), $authResult); if ($authResult['email'] != $user->Email) { $userExists = false; if (eZUser::requireUniqueEmail()) { $userExists = eZUser::fetchByEmail($authResult['email']) instanceof eZUser; } if (empty($authResult['email']) || $userExists) { $email = md5('ngconnect_' . $authResult['login_method'] . '_' . $authResult['id']) . '@localhost.local'; } else { $email = $authResult['email']; } $user->setAttribute('email', $email); $user->store(); } $contentObject->setName($contentObject->contentClass()->contentObjectName($contentObject)); $contentObject->store(); $db->commit(); return $user; }
/** * Returns the authorization object for a user & application * @param ezpRestClient $client * @param eZUser $user */ public static function fetchForClientUser(ezpRestClient $client, eZUser $user) { $session = ezcPersistentSessionInstance::get(); $q = $session->createFindQuery(__CLASS__); $q->where($q->expr->eq('rest_client_id', $q->bindValue($client->id)))->where($q->expr->eq('user_id', $q->bindValue($user->attribute('contentobject_id')))); $results = $session->find($q, __CLASS__); if (count($results) != 1) { return false; } else { return array_shift($results); } }
/** * Writes audit information and redirects the user to the password change form. * * @param eZUser $user */ protected static function passwordHasExpired($user) { $userID = $user->attribute('contentobject_id'); // Password expired eZDebugSetting::writeDebug('kernel-user', $user, 'user password expired'); // Failed login attempts should be logged $userIDAudit = isset($userID) ? $userID : 'null'; $loginEscaped = eZDB::instance()->escapeString($user->attribute('login')); eZAudit::writeAudit('user-failed-login', array('User id' => $userIDAudit, 'User login' => $loginEscaped, 'Comment' => 'Failed login attempt: Password Expired. eZPaExUser::loginUser()')); // Redirect user to password change form self::redirectToChangePasswordForm($userID); }
static function create( $name, $command, $userID = false ) { if ( trim( $name ) == '' ) { eZDebug::writeError( 'Empty name. You must supply a valid script name string.', 'ezscriptmonitor' ); return false; } if ( trim( $command ) == '' ) { eZDebug::writeError( 'Empty command. You must supply a valid command string.', 'ezscriptmonitor' ); return false; } if ( !$userID ) { $userID = eZUser::currentUserID(); } $scriptMonitorIni = eZINI::instance( 'ezscriptmonitor.ini' ); $scriptSiteAccess = $scriptMonitorIni->variable( 'GeneralSettings', 'ScriptSiteAccess' ); $command = str_replace( self::SCRIPT_NAME_STRING, $name, $command ); $command = str_replace( self::SITE_ACCESS_STRING, $scriptSiteAccess, $command ); // Negative progress means not started yet return new self( array( 'name' => $name, 'command' => $command, 'last_report_timestamp' => time(), 'progress' => -1, 'user_id' => $userID ) ); }
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; }
public function authenticate( ezcAuthentication $auth, ezcMvcRequest $request ) { if ( !$auth->run() ) { $aStatuses = $auth->getStatus(); $statusCode = null; foreach ( $aStatuses as $status ) { if ( key( $status ) === 'ezpOauthFilter' ) { $statusCode = current( $status ); break; } } $request->variables['ezpAuth_redirUrl'] = $request->uri; $request->variables['ezpAuth_reason'] = $statusCode; $request->uri = "{$this->prefix}/auth/oauth/login"; return new ezcMvcInternalRedirect( $request ); } else { $user = eZUser::fetch( ezpOauthFilter::$tokenInfo->user_id ); if ( !$user instanceof eZUser ) { throw new ezpUserNotFoundException( ezpOauthFilter::$tokenInfo->user_id ); } return $user; } }
function akismet_ContentActionHandler($module, $http, $objectID) { $object = eZContentObject::fetch($objectID); $version = $object->attribute('current'); if ($http->hasPostVariable('AkismetSubmitSpam')) { $user = eZUser::currentUser(); $accessResult = $user->hasAccessTo('akismet', 'submit'); if ($accessResult['accessWord'] === 'yes') { $mainNode = $object->attribute('main_node'); $module->redirectTo($mainNode->attribute('url_alias')); $akismetObject = new eZContentObjectAkismet(); $comment = $akismetObject->akismetInformationExtractor($version); if ($comment) { $akismet = new eZAkismet($comment); if ($akismet) { $feedback = $akismet->submitSpam(); $response[] = $feedback[1]; } else { $response[] = ezi18n('extension/contactivity/akismet/submit', "An error has occured, unable to submit spam to Akismet."); } } else { $response[] = ezi18n('extension/contactivity/akismet/submit', "An error has occured, unable to submit spam to Akismet."); } } $mainNode = $object->attribute('main_node'); $module->redirectTo($mainNode->attribute('url_alias')); return true; } }
static function reCAPTCHAValidate($http) { // check if the current user is able to bypass filling in the captcha and // return true without checking if so $currentUser = eZUser::currentUser(); $accessAllowed = $currentUser->hasAccessTo('recaptcha', 'bypass_captcha'); if ($accessAllowed["accessWord"] == 'yes') { return true; } $ini = eZINI::instance('recaptcha.ini'); // If PrivateKey is an array try and find a match for the current host $privatekey = $ini->variable('Keys', 'PrivateKey'); if (is_array($privatekey)) { $hostname = eZSys::hostname(); if (isset($privatekey[$hostname])) { $privatekey = $privatekey[$hostname]; } else { // try our luck with the first entry $privatekey = array_shift($privatekey); } } $recaptcha_challenge_field = $http->postVariable('recaptcha_challenge_field'); $recaptcha_response_field = $http->postVariable('recaptcha_response_field'); $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $recaptcha_challenge_field, $recaptcha_response_field); return $resp->is_valid; }
/** * Unit test for eZSubtreeNotificationRule::fetchUserList() */ public function testFetchUserList() { // Add a notification rule for admin on root $adminUserID = eZUser::fetchByName( 'admin' )->attribute( 'contentobject_id' ); $rule = new eZSubtreeNotificationRule( array( 'user_id' => $adminUserID, 'use_digest' => 0, 'node_id' => 2 ) ); $rule->store(); // Create a content object below node #2 $article = new ezpObject( 'article', 2 ); $article->title = __FUNCTION__; $article->publish(); $articleContentObject = $article->object; $list = eZSubtreeNotificationRule::fetchUserList( array( 2, 43 ), $articleContentObject ); $this->assertInternalType( 'array', $list, "Return value should have been an array" ); $this->assertEquals( 1, count( $list ), "Return value should have one item" ); $this->assertInternalType( 'array', $list[0] ); $this->assertArrayHasKey( 'user_id', $list[0] ); $this->assertArrayHasKey( 'use_digest', $list[0] ); $this->assertArrayHasKey( 'address', $list[0] ); $this->assertEquals( 14, $list[0]['user_id'] ); $this->assertEquals( 0, $list[0]['use_digest'] ); $this->assertEquals( '*****@*****.**', $list[0]['address'] ); }
/** * Called by PHPUnit after each test. */ public function tearDown() { // Log in as whoever was logged in eZUser::setCurrentlyLoggedInUser( $this->currentUser, $this->currentUser->attribute( 'id' ) ); parent::tearDown(); }
public function getUserData() { $connection = $this->getFacebookConnection(); $uid = $connection->getUser(); if ($uid === 0) { throw new Exception('Could not get user ID. Refresh the page or try again later.'); } $picture = 'var/cache/fb_profile_' . $uid . '.jpg'; $fp = fopen($picture, 'w'); $ch = curl_init(BaseFacebook::$DOMAIN_MAP['graph'] . '/' . $uid . '/picture?type=large'); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_exec($ch); curl_close($ch); fclose($fp); $data = $connection->api('/' . $uid); $login = $data['username']; $email = $data['email']; if (empty($login) || eZUser::fetchByName($login) instanceof eZUser) { $login = '******' . $uid; } if (empty($email)) { $email = $uid . '@nospam.facebook.com'; } return array('image' => $picture, 'user_account' => self::getUserAccountString($login, $email), 'first_name' => $data['first_name'], 'last_name' => $data['last_name']); }
static function removeByIdentifier($collaborationIdentifier, $userID = false) { if (!$userID) { $userID = eZUser::currentUserID(); } eZPersistentObject::removeObject(eZCollaborationNotificationRule::definition(), array('collab_identifier' => $collaborationIdentifier, 'user_id' => $userID)); }
/** * @param int $objectID ContentObjectID */ public function __construct($objectID) { $userID = eZUser::currentUserID(); $message = ezpI18n::tr('design/standard/error/kernel', 'Access denied') . '. ' . ezpI18n::tr('design/standard/error/kernel', 'You do not have permission to access this area.'); eZLog::write("Access denied to content object #{$objectID} for user #{$userID}", 'error.log'); parent::__construct($message); }
/** * Writes $auditName with $auditAttributes as content * to file name that will be fetched from ini settings by auditNameSettings() for logging. * * @param string $auditName * @param array $auditAttributes * @return bool */ static function writeAudit( $auditName, $auditAttributes = array() ) { $enabled = eZAudit::isAuditEnabled(); if ( !$enabled ) return false; $auditNameSettings = eZAudit::auditNameSettings(); if ( !isset( $auditNameSettings[$auditName] ) ) return false; $ip = eZSys::clientIP(); if ( !$ip ) $ip = eZSys::serverVariable( 'HOSTNAME', true ); $user = eZUser::currentUser(); $userID = $user->attribute( 'contentobject_id' ); $userLogin = $user->attribute( 'login' ); $message = "[$ip] [$userLogin:$userID]\n"; foreach ( array_keys( $auditAttributes ) as $attributeKey ) { $attributeValue = $auditAttributes[$attributeKey]; $message .= "$attributeKey: $attributeValue\n"; } $logName = $auditNameSettings[$auditName]['file_name']; $dir = $auditNameSettings[$auditName]['dir']; eZLog::write( $message, $logName, $dir ); return true; }
/** * Main method to process current row returned by getNextRow() method. * You may throw an exception if something goes wrong. It will be logged but won't break the import process * @param mixed $row Depending on your data format, can be DOMNode, SimpleXMLIterator, SimpleXMLElement, CSV row... */ public function process($row) { $contentOptions = new SQLIContentOptions(array('class_identifier' => 'user', 'remote_id' => (string) $row->login)); $content = SQLIContent::create($contentOptions); $content->fields->first_name = (string) $row->firstName; $content->fields->last_name = (string) $row->lastName; $userParts = array((string) $row->login, (string) $row->email); //password management : if empty, generate it, use custom default or fixed default $password = $row->password; if (!$password) { if (isset($this->options->generate_password) && $this->options->generate_password) { $password = eZUser::createPassword(6); } elseif (isset($this->options->default_password) && $this->options->default_password) { $password = $this->options->default_password; } else { $password = '******'; } } $userParts[] = $password; $userParts[] = eZUser::createHash((string) $row->login, $password, eZUser::site(), eZUser::hashType()); $userParts[] = eZUser::hashType(); $content->fields->user_account = implode('|', $userParts); // Now publish content $content->addLocation(SQLILocation::fromNodeID($this->handlerConfArray['DefaultParentNodeID'])); $publisher = SQLIContentPublisher::getInstance(); $publisher->publish($content); // Free some memory. Internal methods eZContentObject::clearCache() and eZContentObject::resetDataMap() will be called // @see SQLIContent::__destruct() unset($content); $this->csv->rows->next(); }
static function enabled() { if ( isset( $GLOBALS['eZHTTPHeaderCustom'] ) ) { return $GLOBALS['eZHTTPHeaderCustom']; } $ini = eZINI::instance(); if ( !$ini->hasVariable( 'HTTPHeaderSettings', 'CustomHeader' ) ) { $GLOBALS['eZHTTPHeaderCustom'] = false; } else { if ( $ini->variable( 'HTTPHeaderSettings', 'CustomHeader' ) === 'enabled' && $ini->hasVariable( 'HTTPHeaderSettings', 'OnlyForAnonymous' ) && $ini->variable( 'HTTPHeaderSettings', 'OnlyForAnonymous' ) === 'enabled' ) { $user = eZUser::currentUser(); $GLOBALS['eZHTTPHeaderCustom'] = !$user->isLoggedIn(); } else { $GLOBALS['eZHTTPHeaderCustom'] = $ini->variable( 'HTTPHeaderSettings', 'CustomHeader' ) == 'enabled'; } } return $GLOBALS['eZHTTPHeaderCustom']; }
function checkAccess( $functionName, $contentObject ) { if( $contentObject instanceof feZMetaData and $functionName) { $result = $contentObject->checkAccess( $functionName ); return array( 'result' => $result ); } else { $user = eZUser::currentUser(); $userID = $user->attribute( 'contentobject_id' ); $accessResult = $user->hasAccessTo( 'fezmetadata', $functionName ); $accessWord = $accessResult['accessWord']; if( $accessWord == 'yes' ) { return 1; } else { return 0; } } }
/** * Test regression for issue #13952: Workflow cronjob gives fatal error if * node is moved to different location before approval. * * Test Outline * ------------ * 1. Create a folder * 2. Approve folder * 3. Create child of folder * 4. Approve child * 5. Create a new version and re-publish the child * 6. Move child to root * 7. Approve child * 8. Run approval cronjob * * @result: Fatal error: Call to a member function attribute() on a non-object in * /www/trunk/kernel/content/ezcontentoperationcollection.php on line 313 * @expected: No fatal error * @link http://issues.ez.no/13952 */ public function testApprovalFatalErrorWhenMoving() { $anonymousObjectID = eZUser::fetchByName('anonymous')->attribute('contentobject_id'); // STEP 1: Create a folder $folder = new ezpObject("folder", 2, $anonymousObjectID); $folder->name = "Parent folder (needs approval)"; $folder->publish(); // STEP 2: Approve folder $collaborationItem = eZCollaborationItem::fetch(1); $this->approveCollaborationItem($collaborationItem); $this->runWorkflow(); // STEP 3: Create child of folder $child = new ezpObject("folder", $folder->mainNode->node_id, $anonymousObjectID); $child->name = "Child folder (needs approval)"; $child->publish(); // STEP 4: Approve child $collaborationItem = eZCollaborationItem::fetch(2); $this->approveCollaborationItem($collaborationItem); $this->runWorkflow(); // STEP 5: Re-publish child $newVersion = $child->createNewVersion(); ezpObject::publishContentObject($child->object, $newVersion); // STEP 6: Move child to root $child->mainNode->move(2); // STEP 7: Approve child again $collaborationItem = eZCollaborationItem::fetch(3); $this->approveCollaborationItem($collaborationItem); // STEP 8: Run approval cronjob $this->runWorkflow(); }
function creator() { if (isset($this->CreatorID) and $this->CreatorID) { return eZUser::fetch($this->CreatorID); } return null; }
function modify(&$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters) { switch ($operatorName) { case 'recaptcha_get_html': include_once 'extension/recaptcha/classes/recaptchalib.php'; // Retrieve the reCAPTCHA public key from the ini file $ini = eZINI::instance('recaptcha.ini'); $key = $ini->variable('Keys', 'PublicKey'); if (is_array($key)) { $hostname = eZSys::hostname(); if (isset($key[$hostname])) { $key = $key[$hostname]; } else { // try our luck with the first entry $key = array_shift($key); } } // check if the current user is able to bypass filling in the captcha and // return nothing so that no captcha is displayed $currentUser = eZUser::currentUser(); $accessAllowed = $currentUser->hasAccessTo('recaptcha', 'bypass_captcha'); if ($accessAllowed["accessWord"] == 'yes') { $operatorValue = 'User bypasses CAPTCHA'; } else { // Run the HTML generation code from the reCAPTCHA PHP library $operatorValue = recaptcha_get_html($key); } break; } }
/** * Gets current users bookmarks by offset and limit * * @param array $args 0 => offset:0, 1 => limit:10 * @return hash */ public static function bookmarks($args) { $offset = isset($args[0]) ? (int) $args[0] : 0; $limit = isset($args[1]) ? (int) $args[1] : 10; $http = eZHTTPTool::instance(); $user = eZUser::currentUser(); $sort = 'desc'; if (!$user instanceof eZUser) { throw new ezcBaseFunctionalityNotSupportedException('Bookmarks retrival', 'current user object is not of type eZUser'); } $userID = $user->attribute('contentobject_id'); if ($http->hasPostVariable('SortBy') && $http->postVariable('SortBy') !== 'asc') { $sort = 'asc'; } // fetch bookmarks $count = eZPersistentObject::count(eZContentBrowseBookmark::definition(), array('user_id' => $userID)); if ($count) { $objectList = eZPersistentObject::fetchObjectList(eZContentBrowseBookmark::definition(), null, array('user_id' => $userID), array('id' => $sort), array('offset' => $offset, 'length' => $limit), true); } else { $objectList = false; } // Simplify node list so it can be encoded if ($objectList) { $list = ezjscAjaxContent::nodeEncode($objectList, array('loadImages' => true, 'fetchNodeFunction' => 'fetchNode', 'fetchChildrenCount' => true), 'raw'); } else { $list = array(); } return array('list' => $list, 'count' => $count ? count($objectList) : 0, 'total_count' => (int) $count, 'offset' => $offset, 'limit' => $limit); }
protected static function checkIfLoggedIn() { $ini = eZINI::instance('cookielaw.ini'); if (eZUser::currentUser()->isLoggedIn() && ($ini->hasVariable('UriExcludeList', 'ExcludeUserLoggedIn') && $ini->variable('UriExcludeList', 'ExcludeUserLoggedIn') == 'enabled')) { self::$isActive = false; } }
function modifier() { if (isset($this->ModifierID) and $this->ModifierID) { return eZUser::fetch($this->ModifierID); } return null; }
function onPublish($attribute, $contentObject, $publishedNodes) { $user = eZUser::currentUser(); $address = $user->attribute('email'); $userID = $user->attribute('contentobject_id'); $nodeIDList = eZSubtreeNotificationRule::fetchNodesForUserID($user->attribute('contentobject_id'), false); if ($attribute->attribute('data_int') == '1') { $newSubscriptions = array(); foreach ($publishedNodes as $node) { if (!in_array($node->attribute('node_id'), $nodeIDList)) { $newSubscriptions[] = $node->attribute('node_id'); } } foreach ($newSubscriptions as $nodeID) { $rule = eZSubtreeNotificationRule::create($nodeID, $userID); $rule->store(); } } else { foreach ($publishedNodes as $node) { if (in_array($node->attribute('node_id'), $nodeIDList)) { eZSubtreeNotificationRule::removeByNodeAndUserID($user->attribute('contentobject_id'), $node->attribute('node_id')); } } } return true; }
/** * @see ezpRestAuthenticationStyleInterface::authenticate() */ public function authenticate(ezcAuthentication $auth, ezcMvcRequest $request) { if (!$auth->run() && $request->uri !== "{$this->prefix}/fatal") { throw new ezpUserNotFoundException($auth->credentials->id); } else { return eZUser::fetch($auth->credentials->id); } }
/** * Checks if a file can be uploaded. * * @return boolean */ public function canUpload() { $access = eZUser::instance()->hasAccessTo('content', 'create'); if ($access['accessWord'] === 'no') { return false; } return true; }
/** * @deprecated Since 5.0, please use removeByUserID() * @param string $address */ static function removeByAddress($address) { eZDebug::writeStrict('Method ' . __METHOD__ . ' has been deprecated in 5.0', 'Deprecation'); $user = eZUser::fetchByEmail($address); if ($user instanceof eZUser) { self::removeByUserID($user->attribute('contentobject_id')); } }
static function move($nodeID, $newParentNodeID) { $result = false; if (!is_numeric($nodeID) || !is_numeric($newParentNodeID)) { return false; } $node = eZContentObjectTreeNode::fetch($nodeID); if (!$node) { return false; } $object = $node->object(); if (!$object) { return false; } $objectID = $object->attribute('id'); $oldParentNode = $node->fetchParent(); $oldParentObject = $oldParentNode->object(); // clear user policy cache if this is a user object if (in_array($object->attribute('contentclass_id'), eZUser::contentClassIDs())) { eZUser::purgeUserCacheByUserId($object->attribute('id')); } // clear cache for old placement. eZContentCacheManager::clearContentCacheIfNeeded($objectID); $db = eZDB::instance(); $db->begin(); $node->move($newParentNodeID); $newNode = eZContentObjectTreeNode::fetchNode($objectID, $newParentNodeID); if ($newNode) { $newNode->updateSubTreePath(true, true); if ($newNode->attribute('main_node_id') == $newNode->attribute('node_id')) { // If the main node is moved we need to check if the section ID must change $newParentNode = $newNode->fetchParent(); $newParentObject = $newParentNode->object(); if ($object->attribute('section_id') != $newParentObject->attribute('section_id')) { eZContentObjectTreeNode::assignSectionToSubTree($newNode->attribute('main_node_id'), $newParentObject->attribute('section_id'), $oldParentObject->attribute('section_id')); } } // modify assignment $curVersion = $object->attribute('current_version'); $nodeAssignment = eZNodeAssignment::fetch($objectID, $curVersion, $oldParentNode->attribute('node_id')); if ($nodeAssignment) { $nodeAssignment->setAttribute('parent_node', $newParentNodeID); $nodeAssignment->setAttribute('op_code', eZNodeAssignment::OP_CODE_MOVE); $nodeAssignment->store(); // update search index $nodeIDList = array($nodeID); eZSearch::removeNodeAssignment($node->attribute('main_node_id'), $newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList); eZSearch::addNodeAssignment($newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList); } $result = true; } else { eZDebug::writeError("Node {$nodeID} was moved to {$newParentNodeID} but fetching the new node failed"); } $db->commit(); // clear cache for new placement. eZContentCacheManager::clearContentCacheIfNeeded($objectID); return $result; }
static function create($type, $text = false, $creatorID = false) { $date_time = time(); if ($creatorID === false) { $user = eZUser::currentUser(); $creatorID = $user->attribute('contentobject_id'); } return new eZCollaborationSimpleMessage(array('message_type' => $type, 'data_text1' => $text, 'creator_id' => $creatorID, 'created' => $date_time, 'modified' => $date_time)); }
function eZOOImport() { $this->ERROR['number'] = 0; $this->ERROR['value'] = ''; $this->ERROR['description'] = ''; $currentUser = eZUser::currentUser(); $this->currentUserID = $currentUser->id(); $this->ImportDir .= md5(time()) . "/"; }