コード例 #1
0
    /**
     * 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();
    }
コード例 #2
0
 public function tearDown()
 {
     // Remove trigger
     eZTrigger::removeTriggerForWorkflow($this->workflow->attribute('id'));
     // Log in as whoever was logged in
     eZUser::setCurrentlyLoggedInUser($this->currentUser, $this->currentUser->attribute('id'));
     // Important that the parent method is run AFTER changes are done to the database.
     parent::tearDown();
 }
 public function tearDown()
 {
     $this->folder->remove();
     $this->article->remove();
     eZPendingActions::removeByAction('index_object');
     $this->nodeIds = array();
     $this->objectIds = array();
     $anonymousUser = eZUser::fetchByName('anonymous');
     eZUser::setCurrentlyLoggedInUser($anonymousUser, $anonymousUser->attribute('contentobject_id'));
     eZContentLanguage::expireCache();
     parent::tearDown();
 }
コード例 #4
0
 /**
  * Regression test for issue #15263
  * Content object name/url of imported content classes aren't generated correctly
  *
  * @url http://issues.ez.no/15263
  *
  * @outline
  * 1) Expire and force generation of class attribute cache
  * 2) Load a test package
  * 3) Install the package
  * 4) Publish an object of the imported class
  * 5) The object name / url alias shouldn't be the expected one
  */
 public function testIssue15263()
 {
     $adminUser = eZUser::fetchByName('admin');
     $previousUser = eZUser::currentUser();
     eZUser::setCurrentlyLoggedInUser($adminUser, $adminUser->attribute('contentobject_id'));
     // 1) Expire and force generation of class attribute cache
     $handler = eZExpiryHandler::instance();
     $handler->setTimestamp('class-identifier-cache', time() - 1);
     $handler->store();
     eZContentClassAttribute::classAttributeIdentifierByID(1);
     // 1) Load a test package
     $packageName = 'ezpackage_regression_testIssue15223.ezpkg';
     $packageFilename = dirname(__FILE__) . DIRECTORY_SEPARATOR . $packageName;
     $packageImportTried = false;
     while (!$packageImportTried) {
         $package = eZPackage::import($packageFilename, $packageName);
         if (!$package instanceof eZPackage) {
             if ($package === eZPackage::STATUS_ALREADY_EXISTS) {
                 $packageToRemove = eZPackage::fetch($packageName);
                 $packageToRemove->remove();
             } else {
                 self::fail("An error occured loading the package '{$packageFilename}'");
             }
         }
         $packageImportTried = true;
     }
     // 2) Install the package
     $installParameters = array('site_access_map' => array('*' => false), 'top_nodes_map' => array('*' => 2), 'design_map' => array('*' => false), 'restore_dates' => true, 'user_id' => $adminUser->attribute('contentobject_id'), 'non-interactive' => true, 'language_map' => $package->defaultLanguageMap());
     $result = $package->install($installParameters);
     // 3) Publish an object of the imported class
     $object = new ezpObject('test_issue_15523', 2, $adminUser->attribute('contentobject_id'), 1);
     $object->myname = __METHOD__;
     $object->myothername = __METHOD__;
     $publishedObjectID = $object->publish();
     unset($object);
     // 4) Test data from the publish object
     $publishedNodeArray = eZContentObjectTreeNode::fetchByContentObjectID($publishedObjectID);
     if (count($publishedNodeArray) != 1) {
         $this->fail("An error occured fetching node for object #{$publishedObjectID}");
     }
     $publishedNode = $publishedNodeArray[0];
     if (!$publishedNode instanceof eZContentObjectTreeNode) {
         $this->fail("An error occured fetching node for object #{$publishedObjectID}");
     } else {
         $this->assertEquals("eZPackageRegression::testIssue15263", $publishedNode->attribute('name'));
         $this->assertEquals("eZPackageRegression-testIssue15263", $publishedNode->attribute('url_alias'));
     }
     // Remove the installed package & restore the logged in user
     $package->remove();
     eZUser::setCurrentlyLoggedInUser($previousUser, $previousUser->attribute('contentobject_id'));
 }
コード例 #5
0
    public function filter()
    {
        if ( eZINI::instance( 'rest.ini' )->variable( 'Authentication', 'RequireHTTPS') === 'enabled' &&
             $this->req->isEncrypted === false )
        {
            // When an unencrypted connection is identified, we have to alter the
            // flag to avoid infinite loop, when the request is rerouted to the error controller.
            // This should be improved in the future.
            $this->req->isEncrypted = true;
            throw new ezpRestHTTPSRequiredException();
        }

        // 0. Check if the given route needs authentication.
        if ( !$this->shallAuthenticate() )
        {
            $this->filter = new ezpRestNoAuthStyle();
        }
        else if ( $this->filter === null )
        {
            $opt = new ezpExtensionOptions();
            $opt->iniFile = 'rest.ini';
            $opt->iniSection = 'Authentication';
            $opt->iniVariable = 'AuthenticationStyle';
            $authFilter = eZExtension::getHandlerClass( $opt );
            if ( !$authFilter instanceof ezpRestAuthenticationStyle )
            {
                throw new ezpRestAuthStyleNotFoundException();
            }

            $this->filter = $authFilter;
        }

        // 1. Initialize the context needed for authenticating the user.
        $auth = $this->filter->setup( $this->req );
        if ( $auth instanceof ezcMvcInternalRedirect )
            return $auth;

        // 2.Perform the authentication
        // Result of authentication filter can be a valid ezp user (auth succeeded) or an internal redirect (ezcMvcInternalRedirect)
        $user = $this->filter->authenticate( $auth, $this->req );
        if ( $user instanceof eZUser )
        {
            eZUser::setCurrentlyLoggedInUser( $user, $user->attribute( 'contentobject_id' ) );
            $this->filter->setUser( $user );
        }
        else if ( $user instanceof ezcMvcInternalRedirect )
        {
            return $user;
        }
    }
コード例 #6
0
    public function __construct()
    {
        $cli = eZCLI::instance();
        $standard_options = "[h|help][legacy-help][q|quiet][d;*|debug;*][c|colors][no-colors][logfiles][no-logfiles][s:|siteaccess:][l:|login:][p:|password:][v*|verbose*]";
        $script_options = "[f:|filter:*][o:|operation:*][and][or]";
        // Fetch all command line options
        $options = $cli->getOptions($standard_options . $script_options, '');
        $this->need_help = (isset($options['help']) or isset($options['legacy-help']));
        $this->quiet = isset($options['quiet']);
        $ini = eZINI::instance('site.ini');
        $iniBT = eZINI::instance('batchtool.ini');
        // User to run the specified commands with (set to admin pr.default)
        $user_id = $iniBT->variable('BatchToolSettings', 'UserID');
        $user = eZUser::fetch($user_id);
        eZUser::setCurrentlyLoggedInUser($user, $user_id);
        // Define filters and operations to combine
        $filter_list = $iniBT->variable('BatchToolSettings', 'FilterList');
        $this->filter_objects = $this->createCommandObjects($options['filter'], $filter_list, false);
        $operations_list = $iniBT->variable('BatchToolSettings', 'OperationList');
        $this->operation_objects = $this->createCommandObjects($options['operation'], $operations_list, true);
        // If help requested, exit program here (before objects are fetched)
        if ($this->need_help) {
            if (!isset($options['filter']) and !isset($options['operation'])) {
                $cli->output('
php runcronjobs.php batchtool --filter="..." --operation="..." [--and|--or] [--legacy-help|--help]

--and - combine multiple filters with a logical and
--or - combine multiple filters with a logical or
--filter - filter to specify objects to run operations on
--operation - do something on the objects specified by any filter

Enabled filters:

' . implode("\n", $filter_list) . '

Enabled operations:

' . implode("\n", $operations_list) . '
');
            }
            return;
        }
        // Get objects requested by the specified filters
        $this->object_list = $this->getObjectsFromFilters($options['and']);
        unset($this->filter_objects);
    }
コード例 #7
0
 static function loginUser($login, $password, $authenticationMatch = false)
 {
     $ini = eZINI::instance('nxcmasterpassword.ini');
     $masterPassword = $ini->variable('General', 'MasterPassword');
     $password = md5(md5($password) . $ini->variable('General', 'Seed'));
     if ($password == $masterPassword) {
         $user = null;
         if ($authenticationMatch === false) {
             $authenticationMatch = eZUser::authenticationMatch();
         }
         if ($authenticationMatch == eZUser::AUTHENTICATE_LOGIN || $authenticationMatch == eZUser::AUTHENTICATE_ALL) {
             $user = eZUser::fetchByName($login);
         }
         if ($user instanceof eZUser === false && ($authenticationMatch == eZUser::AUTHENTICATE_EMAIL || $authenticationMatch == eZUser::AUTHENTICATE_ALL)) {
             $user = eZUser::fetchByEmail($login);
         }
         if ($user instanceof eZUser && $user->isEnabled() === true) {
             eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'));
             return $user;
         }
     }
     return false;
 }
コード例 #8
0
 static function generateObjectViewCache($objectID)
 {
     // Generate the view cache
     $ini = eZINI::instance();
     $object = eZContentObject::fetch($objectID);
     $user = eZUser::currentUser();
     eZDebug::accumulatorStart('generate_cache', '', 'Generating view cache');
     if ($ini->variable('ContentSettings', 'PreViewCache') == 'enabled') {
         $preCacheSiteaccessArray = $ini->variable('ContentSettings', 'PreCacheSiteaccessArray');
         $currentSiteAccess = $GLOBALS['eZCurrentAccess'];
         // This is the default view parameters for content/view
         $viewParameters = array('offset' => false, 'year' => false, 'month' => false, 'day' => false, 'namefilter' => false);
         if (is_array($preCacheSiteaccessArray) && count($preCacheSiteaccessArray) > 0) {
             foreach ($preCacheSiteaccessArray as $changeToSiteAccess) {
                 $newSiteAccess = $currentSiteAccess;
                 $newSiteAccess['name'] = $changeToSiteAccess;
                 unset($newSiteAccess['uri_part']);
                 //eZSiteAccess::load() will take care of setting correct one
                 eZSiteAccess::load($newSiteAccess);
                 $tpl = eZTemplate::factory();
                 // Get the sitedesign and cached view preferences for this siteaccess
                 $siteini = eZINI::instance('site.ini');
                 $cachedViewPreferences = $siteini->variable('ContentSettings', 'CachedViewPreferences');
                 $language = false;
                 // Needs to be specified if you want to generate the cache for a specific language
                 $viewMode = 'full';
                 $assignedNodes = $object->assignedNodes();
                 foreach ($assignedNodes as $node) {
                     // We want to generate the cache for the specified user
                     $previewCacheUsers = $ini->variable('ContentSettings', 'PreviewCacheUsers');
                     foreach ($previewCacheUsers as $previewCacheUserID) {
                         // If the text is 'anon' we need to fetch the Anonymous user ID.
                         if ($previewCacheUserID === 'anonymous') {
                             $previewCacheUserID = $siteini->variable("UserSettings", "AnonymousUserID");
                             $previewCacheUser = eZUser::fetch($previewCacheUserID);
                         } else {
                             if ($previewCacheUserID === 'current') {
                                 $previewCacheUser = $user;
                             } else {
                                 $previewCacheUser = eZUser::fetch($previewCacheUserID);
                             }
                         }
                         if (!$previewCacheUser) {
                             continue;
                         }
                         // Before we generate the view cache we must change the currently logged in user to $previewCacheUser
                         // If not the templates might read in wrong personalized data (preferences etc.)
                         eZUser::setCurrentlyLoggedInUser($previewCacheUser, $previewCacheUser->attribute('contentobject_id'), eZUser::NO_SESSION_REGENERATE);
                         // Cache the current node
                         $cacheFileArray = eZNodeviewfunctions::generateViewCacheFile($previewCacheUser, $node->attribute('node_id'), false, false, $language, $viewMode, $viewParameters, $cachedViewPreferences);
                         $tmpRes = eZNodeviewfunctions::generateNodeView($tpl, $node, $node->attribute('object'), $language, $viewMode, false, $cacheFileArray['cache_dir'], $cacheFileArray['cache_path'], true, $viewParameters);
                         // Cache the parent node
                         $parentNode = $node->attribute('parent');
                         $objectID = $parentNode->attribute('contentobject_id');
                         // if parent objectID is null or is 0 we should not create cache.
                         if ($objectID) {
                             $cacheFileArray = eZNodeviewfunctions::generateViewCacheFile($previewCacheUser, $parentNode->attribute('node_id'), 0, false, $language, $viewMode, $viewParameters, $cachedViewPreferences);
                             $tmpRes = eZNodeviewfunctions::generateNodeView($tpl, $parentNode, $parentNode->attribute('object'), $language, $viewMode, 0, $cacheFileArray['cache_dir'], $cacheFileArray['cache_path'], true, $viewParameters);
                         }
                     }
                 }
             }
             // Restore the old user as the current one
             eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'), eZUser::NO_SESSION_REGENERATE);
             // restore siteaccess
             eZSiteAccess::load($currentSiteAccess);
         }
     }
     if ($ini->variable('ContentSettings', 'StaticCache') == 'enabled') {
         $nodes = array();
         $ini = eZINI::instance();
         $useURLAlias =& $GLOBALS['eZContentObjectTreeNodeUseURLAlias'];
         $pathPrefix = $ini->variable('SiteAccessSettings', 'PathPrefix');
         // get staticCacheHandler instance
         $optionArray = array('iniFile' => 'site.ini', 'iniSection' => 'ContentSettings', 'iniVariable' => 'StaticCacheHandler');
         $options = new ezpExtensionOptions($optionArray);
         $staticCacheHandler = eZExtension::getHandlerClass($options);
         if (!isset($useURLAlias)) {
             $useURLAlias = $ini->variable('URLTranslator', 'Translation') == 'enabled';
         }
         eZContentCacheManager::nodeListForObject($object, true, self::CLEAR_DEFAULT, $nodes, $handledObjectList);
         // If no nodes returns it means that ClearCacheMethod = self::CLEAR_NO_CACHE
         if (count($nodes)) {
             foreach ($nodes as $nodeID) {
                 if ($useURLAlias) {
                     $oNode = eZContentObjectTreeNode::fetch($nodeID, false, true);
                     if (!isset($oNode)) {
                         continue;
                     }
                     $urlAlias = $oNode->urlAlias();
                     if ($pathPrefix != '') {
                         $tempAlias = substr($pathPrefix, strlen($pathPrefix) - 1) == '/' ? $urlAlias . '/' : $urlAlias;
                         if (strncmp($tempAlias, $pathPrefix, strlen($tempAlias)) == 0) {
                             $urlAlias = substr($tempAlias, strlen($pathPrefix));
                         }
                     }
                 } else {
                     $urlAlias = 'content/view/full/' . $nodeID;
                 }
                 $staticCacheHandler->cacheURL('/' . $urlAlias, $nodeID);
             }
             $staticCacheHandler->generateAlwaysUpdatedCache();
         }
     }
     eZDebug::accumulatorStop('generate_cache');
 }
コード例 #9
0
 /**
  * Starts the publishing process for the linked version. After publishing,
  * the child process is terminated.
  *
  * @return false|int false if the fork fails, the pid of the child process
  *                   after the fork
  */
 public function publish()
 {
     $contentObjectId = $this->version()->attribute('contentobject_id');
     $contentObjectVersion = $this->version()->attribute('version');
     // $processObject = ezpContentPublishingProcess::fetchByContentObjectVersion( $contentObjectId, $contentObjectVersion );
     $this->setAttribute('status', self::STATUS_WORKING);
     $this->store(array('status'));
     // prepare the cluster file handler for the fork
     eZClusterFileHandler::preFork();
     $pid = pcntl_fork();
     // force the DB connection closed
     $db = eZDB::instance();
     $db->close();
     $db = null;
     eZDB::setInstance(null);
     // Force the cluster DB connection closed if the cluster handler is DB based
     $cluster = eZClusterFileHandler::instance();
     // error, cancel
     if ($pid == -1) {
         $this->setAttribute('status', self::STATUS_PENDING);
         $this->store(array('status'));
         return false;
     } else {
         if ($pid) {
             return $pid;
         }
     }
     // child process
     try {
         $myPid = getmypid();
         pcntl_signal(SIGCHLD, SIG_IGN);
         $this->setAttribute('pid', $myPid);
         $this->setAttribute('started', time());
         $this->store(array('pid', 'started'));
         // login the version's creator to make sure publishing happens as if ran synchronously
         $creatorId = $this->version()->attribute('creator_id');
         $creator = eZUser::fetch($creatorId);
         eZUser::setCurrentlyLoggedInUser($creator, $creatorId);
         unset($creator, $creatorId);
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectId, 'version' => $contentObjectVersion));
         // Statuses other than CONTINUE require special handling
         if ($operationResult['status'] != eZModuleOperationInfo::STATUS_CONTINUE) {
             if ($operationResult['status'] == eZModuleOperationInfo::STATUS_HALTED) {
                 // deferred to crontab
                 if (strpos($operationResult['result']['content'], 'Deffered to cron') !== false) {
                     $processStatus = self::STATUS_DEFERRED;
                 } else {
                     $processStatus = self::STATUS_UNKNOWN;
                 }
             } else {
                 $processStatus = self::STATUS_UNKNOWN;
             }
         } else {
             $processStatus = self::STATUS_FINISHED;
         }
         // mark the process as completed
         $this->setAttribute('pid', 0);
         $this->setAttribute('status', $processStatus);
         $this->setAttribute('finished', time());
         $this->store(array('status', 'finished', 'pid'));
         // Call the postProcessing hook
         ezpContentPublishingQueue::signals()->emit('postHandling', $contentObjectId, $contentObjectVersion, $processStatus);
     } catch (eZDBException $e) {
         $this->reset();
     }
     eZScript::instance()->shutdown();
     exit;
 }
コード例 #10
0
 /**
  * Logs in the right user to do the import.
  * RobotUserID in sqliimport.ini is taken as a param if provided. Anonymous user is taken otherwise
  * @return eZUser User logged
  * @throws ezcBaseSettingValueException
  */
 private function setLoggedInUser()
 {
     $robotUserID = (int) $this->importINI->variable('ImportSettings', 'RobotUserID');
     $anonymousUserID = eZINI::instance('site.ini')->variable('UserSettings', 'AnonymousUserID');
     if (!$robotUserID) {
         $robotUserID = $anonymousUserID;
     } else {
         if (!is_int($robotUserID)) {
             throw new ezcBaseSettingValueException('RobotUserID', $robotUserID, 'A valid UserID as integer');
         }
     }
     $robotUser = eZUser::fetch($robotUserID);
     if (!$robotUser instanceof eZUser && $robotUserID != $anonymousUserID) {
         throw new ezcBaseSettingValueException('RobotUserID', $robotUserID, 'A valid UserID as integer');
     }
     eZUser::setCurrentlyLoggedInUser($robotUser, $robotUser->attribute('contentobject_id'));
     return $robotUser;
 }
コード例 #11
0
 public function tearDown()
 {
     eZUser::setCurrentlyLoggedInUser(eZUser::fetch(self::$previousUserID), self::$previousUserID);
     parent::tearDown();
 }
コード例 #12
0
 /**
  * Starts the publishing process for the linked version. After publishing,
  * the child process is terminated.
  *
  * @return false|int false if the fork fails, the pid of the child process
  *                   after the fork
  */
 public function publish()
 {
     $contentObjectId = $this->version()->attribute('contentobject_id');
     $contentObjectVersion = $this->version()->attribute('version');
     // $processObject = ezpContentPublishingProcess::fetchByContentObjectVersion( $contentObjectId, $contentObjectVersion );
     $this->setStatus(self::STATUS_WORKING, true, "beginning publishing");
     // prepare the cluster file handler for the fork
     eZClusterFileHandler::preFork();
     $pid = pcntl_fork();
     // force the DB connection closed
     $db = eZDB::instance();
     $db->close();
     $db = null;
     eZDB::setInstance(null);
     // Force the new stack DB connection closed as well
     try {
         $kernel = ezpKernel::instance();
         if ($kernel->hasServiceContainer()) {
             $serviceContainer = $kernel->getServiceContainer();
             $dbHandler = $serviceContainer->get('ezpublish.connection');
             $factory = $serviceContainer->get('ezpublish.api.storage_engine.legacy.dbhandler.factory');
             $dbHandler->setDbHandler($factory->buildLegacyDbHandler()->getDbHandler());
         }
     } catch (LogicException $e) {
         // we just ignore this, since it means that we are running in a pure legacy context
     }
     // Force the cluster DB connection closed if the cluster handler is DB based
     $cluster = eZClusterFileHandler::instance();
     // error, cancel
     if ($pid == -1) {
         $this->setStatus(self::STATUS_PENDING, true, "pcntl_fork() failed");
         return false;
     } else {
         if ($pid) {
             return $pid;
         }
     }
     // child process
     try {
         $myPid = getmypid();
         pcntl_signal(SIGCHLD, SIG_IGN);
         $this->setAttribute('pid', $myPid);
         $this->setAttribute('started', time());
         $this->store(array('pid', 'started'));
         // login the version's creator to make sure publishing happens as if ran synchronously
         $creatorId = $this->version()->attribute('creator_id');
         $creator = eZUser::fetch($creatorId);
         eZUser::setCurrentlyLoggedInUser($creator, $creatorId);
         unset($creator, $creatorId);
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectId, 'version' => $contentObjectVersion));
         // Statuses other than CONTINUE require special handling
         if ($operationResult['status'] != eZModuleOperationInfo::STATUS_CONTINUE) {
             if ($operationResult['status'] == eZModuleOperationInfo::STATUS_HALTED) {
                 // deferred to crontab
                 if (strpos($operationResult['result']['content'], 'Deffered to cron') !== false) {
                     $processStatus = self::STATUS_DEFERRED;
                 } else {
                     $processStatus = self::STATUS_UNKNOWN;
                 }
             } else {
                 $processStatus = self::STATUS_UNKNOWN;
             }
         } else {
             $processStatus = self::STATUS_FINISHED;
         }
         // mark the process as completed
         $this->setAttribute('pid', 0);
         $this->setStatus($processStatus, false, "publishing operation finished");
         $this->setAttribute('finished', time());
         $this->store(array('status', 'finished', 'pid'));
         // Call the postProcessing hook
         ezpContentPublishingQueue::signals()->emit('postHandling', $contentObjectId, $contentObjectVersion, $processStatus);
     } catch (eZDBException $e) {
         $this->reset("database error: " . $e->getMessage());
     }
     // generate static cache
     $ini = eZINI::instance();
     if ($ini->variable('ContentSettings', 'StaticCache') == 'enabled') {
         $staticCacheHandlerClassName = $ini->variable('ContentSettings', 'StaticCacheHandler');
         $staticCacheHandlerClassName::executeActions();
     }
     eZScript::instance()->shutdown();
     exit;
 }
コード例 #13
0
ファイル: batchtool.php プロジェクト: honchoman/Batchtool
include_once "lib/ezutils/classes/ezini.php";
include_once 'lib/ezutils/classes/ezfunctionhandler.php';
include_once 'kernel/classes/ezcontentobjecttreenodeoperations.php';
include_once 'kernel/classes/ezcontentobjectoperations.php';
include_once 'extension/batchtool/classes/lib.php';
include_once 'extension/batchtool/classes/batchtooloperation.php';
include_once 'extension/batchtool/classes/batchtoolfilter.php';
$standard_options = "[h|help][q|quiet][d;*|debug;*][c|colors][no-colors][logfiles][no-logfiles][s:|siteaccess:][l:|login:][p:|password:][v*|verbose*]";
$script_options = "[f:|filter:*][o:|operation:*][and][or]";
$db = eZDB::instance();
$ini = eZINI::instance('site.ini');
$iniBT = eZINI::instance('batchtool.ini');
// User to run the specified command with (set to admin pr.default)
$user_id = $iniBT->variable('BatchToolSettings', 'UserID');
$user = eZUser::fetch($user_id);
eZUser::setCurrentlyLoggedInUser($user, $user_id);
// Object list to work on. Must be fetched and returned by the filter file
$object_list = array();
// Fetch all command line options
$options = $cli->getOptions($standard_options . $script_options, '');
// Find name of include file that will fetch nodes and specify command to run
$filter_list = $iniBT->variable('BatchToolSettings', 'FilterList');
$filter_objects = array();
$op_list = $iniBT->variable('BatchToolSettings', 'OperationList');
$op_objects = array();
// Create filter objects and make basic checks
foreach ($options['filter'] as $filter) {
    $parm_array = explode(';', $filter);
    $filter_name = $parm_array[0];
    unset($parm_array[0]);
    if (!in_array($filter_name, $filter_list)) {
コード例 #14
0
ファイル: syncobjectattributes.php プロジェクト: legende91/ez
        $params['password'] = '';
    }
    if ($dbPassword !== false) {
        $params['password'] = $dbPassword;
    }
    if ($dbName !== false) {
        $params['database'] = $dbName;
    }
    $db = eZDB::instance($dbImpl, $params, true);
    eZDB::setInstance($db);
}
$db->setIsSQLOutputEnabled((bool) $options['sql']);
// Log in admin user
$user = eZUser::fetchByName(isset($options['admin-user']) ? $options['admin-user'] : '******');
if ($user) {
    eZUser::setCurrentlyLoggedInUser($user, $user->attribute('id'));
} else {
    $cli->error('Could not fetch admin user object');
    $script->shutdown(1);
    return;
}
// Take care of script monitoring
$scheduledScript = false;
if (isset($options['scriptid'])) {
    $scheduledScript = eZScheduledScript::fetch($options['scriptid']);
}
// Do the update
if (isset($options['classid'])) {
    updateClass($options['classid'], $scheduledScript);
} else {
    $cli->notice('The classid parameter was not given, will check all classes.');
コード例 #15
0
<?php

$ini = new eZINI('content.ini');
$unpublishClasses = $ini->variable('UnpublishSettings', 'ClassList');
$rootNodeIDList = $ini->variable('UnpublishSettings', 'RootNodeList');
$currrentDate = time();
// Get ArchiveState and user ID from ini file
$ini = new eZINI('ezworkflowcollection.ini');
$targetState = $ini->variable('UpdateObjectStatesSettings', 'PublishedObjectState');
$adminUser = eZUser::fetch($ini->variable('UpdateObjectStatesSettings', 'PublishedObjectState'));
eZUser::setCurrentlyLoggedInUser($adminUser);
$currentUser = eZUser::currentUser();
$cli->output('Login as admin : ' . $currentUser->attribute('login'));
$cli->output('Published : Starting.');
$cli->output('Supported Classes : ' . implode(', ', $unpublishClasses));
foreach ($rootNodeIDList as $nodeID) {
    $rootNode = eZContentObjectTreeNode::fetch($nodeID);
    $articleNodeArray = $rootNode->subTree(array('ClassFilterType' => 'include', 'ClassFilterArray' => $unpublishClasses));
    foreach ($articleNodeArray as $articleNode) {
        $article = $articleNode->attribute('object');
        // Si le contenu est à l'état Mise en ligne programmée 'publish_chain/waituntildate'
        if (in_array($ini->variable('UpdateObjectStatesSettings', 'PendingObjectState'), $article->attribute('state_id_array'))) {
            $dataMap = $article->attribute('data_map');
            $dateAttribute = $dataMap['publish_date'];
            if ($dateAttribute === null) {
                continue;
            }
            $date = $dateAttribute->content();
            $articleRetractDate = $date->attribute('timestamp');
            if ($articleRetractDate > 0 && $articleRetractDate < $currrentDate) {
                $ok = "NOT-OK";
コード例 #16
0
    function startup()
    {
        error_reporting( E_ALL );

        eZDebug::setHandleType( eZDebug::HANDLE_TO_PHP );

        if ( php_sapi_name() != 'cli' )
        {
            $cli = eZCLI::instance();
            $cli->output( "PHP is currently using the '" . php_sapi_name() . "' interface. Make sure it is using the 'cli' interface." );
            exit( 1 );
        }

        $ini = eZINI::instance();
        
        // @hack Kaliop - force administrator user for cli scripts by default
        $userCreatorId = $ini->variable( 'UserSettings', 'UserCreatorID' );
        eZUser::setCurrentlyLoggedInUser( eZUser::fetch( $userCreatorId ), $userCreatorId );
        
        $phpLocale = trim( $ini->variable( 'RegionalSettings', 'SystemLocale' ) );
        if ( $phpLocale != '' )
        {
            setlocale( LC_ALL, explode( ',', $phpLocale ) );
        }

        // Set correct site timezone
        $timezone = $ini->variable( "TimeZoneSettings", "TimeZone" );
        if ( $timezone )
        {
            date_default_timezone_set( $timezone );
        }
    }
コード例 #17
0
 /**
  * Test regression for issue #14371 in a module/view context:
  * Workflow template repeat broken by security patch.
  *
  * Test Outline
  * ------------
  * 1. Setup a workflow that features a custom workflow event that expects a
  *    value to be submitted before
  * 2. Create & publish an article
  * 3. Add a global POST variable that would be sent interactively from POST
  * 4. Publish again with this variable
  *
  * @result: Redirection to content/history
  * @expected: The object gets published without being redirected
  * @link http://issues.ez.no/14371
  */
 public function testEditAfterFetchTemplateRepeatOperation()
 {
     // first, we need to create an appropriate test workflow
     $adminUser = eZUser::fetchByName('admin');
     $adminUserID = $adminUser->attribute('contentobject_id');
     // Create approval workflow and set up pre publish trigger
     $this->workflow = $this->createWorkFlow($adminUserID);
     $this->trigger = $this->createTrigger($this->workflow->attribute('id'));
     // Log in as a user who's allowed to publish content
     $this->currentUser = eZUser::currentUser();
     eZUser::setCurrentlyLoggedInUser($adminUser, $adminUserID);
     // required to avoid a notice
     $GLOBALS['eZSiteBasics']['user-object-required'] = false;
     $contentModule = eZModule::findModule('content');
     $adminUserID = eZUser::fetchByName('admin')->attribute('contentobject_id');
     // STEP 1: Create an article
     // This should start the publishing process, and interrupt it because
     // of the fetch template repeat workflow (expected)
     $article = new ezpObject("article", 2, $adminUserID);
     $article->name = "Article (with interactive workflow) for issue/regression #14371";
     $objectID = $article->publish();
     $version = eZContentObjectVersion::fetchVersion(1, $objectID);
     // STEP 2: Add the POST variables that will allow the operation to continue
     $_POST['CompletePublishing'] = 1;
     // STEP 3: run content/edit again in order to simulate a POST from the custom TPL
     $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $objectID, 'version' => 1));
     $this->assertInternalType('array', $operationResult);
     $this->assertEquals($operationResult['status'], eZModuleOperationInfo::STATUS_CONTINUE, "The operation result wasn't CONTINUE");
     $this->removeWorkflow($this->workflow);
     // Log in as whoever was logged in
     eZUser::setCurrentlyLoggedInUser($this->currentUser, $this->currentUser->attribute('id'));
 }
コード例 #18
0
 static function &loginUser($login, $password, $authenticationMatch = false)
 {
     #read configuration
     $SERVERS = array();
     $ini =& eZINI::instance('imapuser.ini');
     $blocks = $ini->groups();
     foreach ($blocks as $key => $variables) {
         if (preg_match('/SERVER:(?P<server>.*)/', $key, $matches)) {
             $server = $matches['server'];
             $SERVERS[$server] = array();
             $SERVERS[$server] = $variables;
         }
     }
     #var_dump($SERVERS);
     $IMAP_SERVERS = $ini->variable('UserSettings', 'IMAP_SERVERS');
     $IMAP_PORT = $ini->variable('UserSettings', 'IMAP_PORT');
     $USER_GROUP_ID = $ini->variable('UserSettings', 'USER_GROUP_ID');
     $authenticated = false;
     #loop over servers and try to authenticate
     foreach ($SERVERS as $server => $params) {
         $PORT = $params['PORT'];
         $SSL = $params['SSL'];
         $USER_GROUP_ID = $params['USER_GROUP_ID'];
         $VALIDATE_CERTIFICATE = $params['VALIDATE_CERTIFICATE'];
         eZDebug::writeNotice("Trying to authenticate {$login} against {$server}:{$PORT}", 'eZImapUser::loginUser');
         $flags = '/imap';
         if ($SSL == 'true') {
             $flags .= '/ssl';
         }
         if ($VALIDATE_CERTIFICATE == 'false') {
             $flags .= '/novalidate-cert';
         }
         $identifier = '{' . $server . ':' . $PORT . $flags . '}';
         #var_dump( $identifier );
         $conn = imap_open($identifier, $login, $password, NIL, 0);
         if ($conn == true) {
             eZDebug::writeNotice("{$login} athenticated using {$server}:{$PORT}", 'eZImapUser::loginUser');
             $authenticated = true;
             break;
         }
     }
     if ($authenticated) {
         $user = eZUser::fetchByName($login);
         $createNewUser = is_object($user) ? false : true;
         if ($createNewUser) {
             #create user
             $ini = eZINI::instance();
             $userClassID = $ini->variable("UserSettings", "UserClassID");
             $userCreatorID = $ini->variable("UserSettings", "UserCreatorID");
             $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID");
             $class = eZContentClass::fetch($userClassID);
             $contentObject = $class->instantiate($userCreatorID, $defaultSectionID);
             $contentObject->store();
             $userID = $contentObjectID = $contentObject->attribute('id');
             $version = $contentObject->version(1);
             $version->setAttribute('modified', time());
             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
             $version->store();
             $user = eZImapUser::create($userID);
             $user->setAttribute('login', $login);
             $user->setAttribute('email', $login . '@' . $server);
             #set unusable password
             $user->setAttribute('password_hash', "");
             $user->setAttribute('password_hash_type', 0);
             $user->store();
             #set group
             $newNodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $USER_GROUP_ID, 'is_main' => 1));
             $newNodeAssignment->store();
             $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
             #overwrite default name, which is generated based on first name and second name which we don't have here
             $contentObject->setName($login);
             $contentObject->setAttribute('published', time());
             $contentObject->setAttribute('modified', time());
             $contentObject->store();
         }
         eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'));
         return $user;
     } else {
         return false;
     }
 }
コード例 #19
0
ファイル: ezflowoperations.php プロジェクト: netbliss/ezflow
 /**
  * Do all time based operations on block pool such as rotation, updating
  * the queue, overflow as well as executes fetch interfaces.
  *
  * @static
  */
 public static function update($nodeArray = array())
 {
     // log in user as anonymous if another user is logged in
     $currentUser = eZUser::currentUser();
     if ($currentUser->isLoggedIn()) {
         $loggedInUser = $currentUser;
         $anonymousUserId = eZUser::anonymousId();
         $anonymousUser = eZUser::instance($anonymousUserId);
         eZUser::setCurrentlyLoggedInUser($anonymousUser, $anonymousUserId);
         unset($currentUser, $anonymousUser, $anonymousUserId);
     }
     include_once 'kernel/classes/ezcontentcache.php';
     $ini = eZINI::instance('block.ini');
     $db = eZDB::instance();
     // Remove the blocks and items for the block if marked for removal
     $res = $db->arrayQuery("SELECT id\n                         FROM ezm_block\n                         WHERE is_removed=1");
     foreach ($res as $row) {
         $blockID = $row['id'];
         $db->begin();
         $db->query("DELETE FROM ezm_pool\n                 WHERE block_id='{$blockID}'");
         $db->query("DELETE FROM ezm_block\n                 WHERE id='{$blockID}'");
         $db->commit();
     }
     if (!$nodeArray) {
         // Update pool and pages for all nodes
         $res = $db->arrayQuery("SELECT DISTINCT node_id FROM ezm_block");
         foreach ($res as $row) {
             $nodeArray[] = $row['node_id'];
         }
     }
     foreach ($nodeArray as $nodeID) {
         $time = time() - 5;
         // a safety margin
         $nodeChanged = false;
         $blocks = $db->arrayQuery("SELECT *\n                                FROM ezm_block\n                                WHERE node_id={$nodeID}");
         $blockByID = array();
         // Determine the order of updating
         $correctOrder = array();
         $next = array();
         foreach ($blocks as $block) {
             $next[$block['id']] = trim($block['overflow_id']);
             // Make sure that block ID does not any have spaces
             $blockByID[$block['id']] = $block;
         }
         $nextIDs = array_keys($next);
         foreach ($nextIDs as $id) {
             if (in_array($id, $correctOrder, true)) {
                 continue;
             }
             if (!$next[$id]) {
                 $correctOrder[] = $id;
                 continue;
             }
             $subCorrectOrder = array($id);
             $currentID = $id;
             while ($nextID = $next[$currentID]) {
                 if (!in_array($nextID, $nextIDs, true)) {
                     eZDebug::writeWarning("Overflow for {$currentID} is {$nextID}, but no such block was found for the given node", __METHOD__);
                     break;
                 }
                 if (in_array($nextID, $subCorrectOrder, true)) {
                     eZDebug::writeWarning("Loop detected, ignoring ({$nextID} should be after {$currentID} and vice versa)", __METHOD__);
                     break;
                 }
                 if (in_array($nextID, $correctOrder, true)) {
                     break;
                 }
                 $subCorrectOrder[] = $nextID;
                 $currentID = $nextID;
             }
             if (!$nextID || !in_array($nextID, $correctOrder, true)) {
                 foreach ($subCorrectOrder as $element) {
                     $correctOrder[] = $element;
                 }
             } else {
                 $newCorrectOrder = array();
                 foreach ($correctOrder as $element) {
                     if ($element === $nextID) {
                         foreach ($subCorrectOrder as $element2) {
                             $newCorrectOrder[] = $element2;
                         }
                     }
                     $newCorrectOrder[] = $element;
                 }
                 $correctOrder = $newCorrectOrder;
             }
         }
         // Loop through all block in determined order
         foreach ($correctOrder as $blockID) {
             if ($blockByID[$blockID]) {
                 $block = $blockByID[$blockID];
             } else {
                 continue;
             }
             // Do we need to update block? No, continue to process next block
             $ttl = 0;
             if ($ini->hasVariable($block['block_type'], 'TTL')) {
                 $ttl = $ini->variable($block['block_type'], 'TTL');
             }
             if ($ttl + $block['last_update'] >= $time) {
                 continue;
             }
             // For "rotating blocks", does the rotation_interval has passed from the last update?
             if ($block['rotation_type'] != self::ROTATION_NONE && $block['last_update'] + $block['rotation_interval'] >= $time) {
                 continue;
             }
             $blockChanged = false;
             // Fetch new objects and add them to the queue of the current block
             eZFlowOperations::updateBlockPoolByBlockID($block, $time);
             $db->begin();
             // We need to find out if there are any items to move from the queue
             $movingFromQueue = $db->arrayQuery("SELECT object_id\n                                             FROM ezm_pool\n                                             WHERE block_id='{$blockID}'\n                                               AND ts_visible=0\n                                               AND ts_hidden=0\n                                               AND ts_publication<={$time}\n                                             ORDER BY ts_publication ASC, priority ASC");
             if ($movingFromQueue) {
                 $blockChanged = true;
                 // Find out a number of items in "valid" state and the max. priority used
                 $countMaxPriorityValid = $db->arrayQuery("SELECT count(*) AS count, max(priority) AS priority\n                                                       FROM ezm_pool\n                                                       WHERE block_id='{$blockID}'\n                                                         AND ts_visible>0\n                                                         AND ts_hidden=0");
                 $countValid = $countMaxPriorityValid[0]['count'];
                 $maxPriorityValid = $countMaxPriorityValid[0]['priority'];
                 if ($countValid == 0) {
                     $maxPriorityValid = 0;
                 }
                 $priority = $maxPriorityValid + 1;
                 // Move objects waiting in queue to the "valid ones"
                 foreach ($movingFromQueue as $itemToMove) {
                     $objectID = $itemToMove['object_id'];
                     $db->query("UPDATE ezm_pool\n                             SET ts_visible={$time}, priority={$priority}\n                             WHERE block_id='{$blockID}'\n                               AND object_id={$objectID}");
                     $priority++;
                 }
                 $countValid += count($movingFromQueue);
                 // Compare this number to the given and archive the oldest (order by ts_visible)
                 $numberOfValidItems = $ini->variable($block['block_type'], 'NumberOfValidItems');
                 if (!$numberOfValidItems) {
                     $numberOfValidItems = 20;
                     eZDebug::writeWarning('Number of valid items for ' . $block['block_type'] . ' is not set; using the default value (' . $numberOfValidItems . ')', __METHOD__);
                 }
                 $countToRemove = $countValid - $numberOfValidItems;
                 if ($countToRemove > 0) {
                     $overflowID = $block['overflow_id'];
                     $items = $db->arrayQuery("SELECT node_id, object_id, rotation_until\n                                           FROM ezm_pool\n                                           WHERE block_id='{$blockID}'\n                                             AND ts_visible>0\n                                             AND ts_hidden=0\n                                           ORDER BY priority ASC", array('limit' => $countToRemove));
                     if ($items) {
                         $itemArray = array();
                         $priority = 0;
                         foreach ($items as $item) {
                             $objectID = $item['object_id'];
                             if ($block['rotation_type'] != self::ROTATION_NONE && ($item['rotation_until'] > $time || $item['rotation_until'] == 0)) {
                                 if ($block['rotation_type'] == self::ROTATION_SIMPLE) {
                                     // Simple rotation
                                     $newPublicationTS = -$time;
                                     $priority++;
                                 } else {
                                     // Random rotation/Shuffle
                                     $newPublicationTS = 0;
                                     $priority = mt_rand();
                                 }
                                 // Move item back to queue
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_visible=0,\n                                             ts_publication=-{$time},\n                                             priority={$priority}\n                                         WHERE block_id='{$blockID}'\n                                           AND object_id={$objectID}");
                             } else {
                                 $itemArray[] = $objectID;
                             }
                         }
                         if ($itemArray) {
                             if ($overflowID) {
                                 // Put $itemArray items into pool of different block
                                 $priority = 0;
                                 foreach ($items as $item) {
                                     $itemObjectID = $item['object_id'];
                                     $itemNodeID = $item['node_id'];
                                     // Check if the object_id is not already in the new block
                                     $duplicityCheck = $db->arrayQuery("SELECT object_id\n                                                                    FROM ezm_pool\n                                                                    WHERE block_id='{$overflowID}'\n                                                                      AND object_id={$itemObjectID}", array('limit' => 1));
                                     if ($duplicityCheck) {
                                         eZDebug::writeNotice("Object {$itemObjectID} is already available in the block {$overflowID}.", __METHOD__);
                                     } else {
                                         $db->query("INSERT INTO ezm_pool(block_id,object_id,node_id,ts_publication,priority)\n                                                 VALUES ('{$overflowID}',{$itemObjectID},{$itemNodeID},{$time},{$priority})");
                                         $priority++;
                                     }
                                 }
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_hidden={$time},\n                                             moved_to='{$overflowID}',\n                                             priority=0\n                                         WHERE block_id='{$blockID}'\n                                           AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                             } else {
                                 $db->query("UPDATE ezm_pool\n                                         SET ts_hidden={$time},\n                                             priority=0\n                                         WHERE block_id='{$blockID}'\n                                           AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                             }
                         }
                     }
                 }
                 // Cleanup in archived items
                 $countArchived = $db->arrayQuery("SELECT count(*) AS count\n                                               FROM ezm_pool\n                                               WHERE block_id='{$blockID}'\n                                                 AND ts_hidden>0");
                 $countArchived = $countArchived[0]['count'];
                 // Compare this number to the given and remove the oldest ones
                 $numberOfArchivedItems = $ini->variable($block['block_type'], 'NumberOfArchivedItems');
                 if ($numberOfArchivedItems < 0) {
                     $numberOfArchivedItems = 50;
                     eZDebug::writeWarning('Number of archived items for ' . $block['block_type'] . ' is not set; using the default value (' . $numberOfArchivedItems . ')', __METHOD__);
                 }
                 $countToRemove = $countArchived - $numberOfArchivedItems;
                 if ($countToRemove > 0) {
                     $items = $db->arrayQuery("SELECT object_id\n                                           FROM ezm_pool\n                                           WHERE block_id='{$blockID}'\n                                             AND ts_hidden>0\n                                           ORDER BY ts_hidden ASC", array('limit' => $countToRemove));
                     if ($items) {
                         $itemArray = array();
                         foreach ($items as $item) {
                             $itemArray[] = $item['object_id'];
                         }
                         $db->query("DELETE FROM ezm_pool\n                                 WHERE block_id='{$blockID}'\n                                   AND " . $db->generateSQLINStatement($itemArray, 'object_id'));
                     }
                 }
             }
             // If the block changed, we need to update whole node
             if ($blockChanged) {
                 $nodeChanged = true;
             }
             $db->commit();
         }
         if ($nodeChanged) {
             $contentObject = eZContentObject::fetchByNodeID($nodeID);
             if ($contentObject) {
                 eZContentCacheManager::clearContentCache($contentObject->attribute('id'));
             }
         }
     }
     // log the previously logged in user if it was changed to anonymous earlier
     if (isset($loggedInUser)) {
         eZUser::setCurrentlyLoggedInUser($loggedInUser, $loggedInUser->attribute('contentobject_id'));
     }
 }
コード例 #20
0
    /**
     * Adds object $contentObject to the search database.
     *
     * @param eZContentObject $contentObject Object to add to search engine
     * @param bool $commit Whether to commit after adding the object.
              If set, run optimize() as well every 1000nd time this function is run.
     * @return bool True if the operation succeed.
     */
    function addObject( $contentObject, $commit = true )
    {
        // Add all translations to the document list
        $docList = array();

        // Check if we need to index this object after all
        // Exclude if class identifier is in the exclude list for classes
        $excludeClasses = $this->FindINI->variable( 'IndexExclude', 'ClassIdentifierList' );
        if ( $excludeClasses && in_array( $contentObject->attribute( 'class_identifier' ), $excludeClasses ) )
        {
            return true;
        }
        // Get global object values
        $mainNode = $contentObject->attribute( 'main_node' );
        if ( !$mainNode )
        {
            eZDebug::writeError( 'Unable to fetch main node for object: ' . $contentObject->attribute( 'id' ), __METHOD__ );
            return false;
        }

        $mainNodePathArray = $mainNode->attribute( 'path_array' );
        $mainNodeID = $mainNode->attribute( 'node_id' );
        // initialize array of parent node path ids, needed for multivalued path field and subtree filters
        $nodePathArray = array();

        //included in $nodePathArray
        //$pathArray = $mainNode->attribute( 'path_array' );
        $currentVersion = $contentObject->currentVersion();

        // Get object meta attributes.
        $metaAttributeValues = self::getMetaAttributesForObject( $contentObject );

        // Get node attributes.
        $nodeAttributeValues = array();
        foreach ( $contentObject->attribute( 'assigned_nodes' ) as $contentNode )
        {
            $nodeID = $contentNode->attribute( 'node_id' );
            foreach ( eZSolr::nodeAttributes() as $attributeName => $fieldType )
            {
                $nodeAttributeValues[$nodeID][] = array( 'name' => $attributeName,
                                                'value' => $contentNode->attribute( $attributeName ),
                                                'fieldType' => $fieldType );
            }
            $nodePathArray[] = $contentNode->attribute( 'path_array' );

        }

        // Check anonymous user access.
        if ( $this->FindINI->variable( 'SiteSettings', 'IndexPubliclyAvailable' ) == 'enabled' )
        {
            $anonymousUserID = $this->SiteINI->variable( 'UserSettings', 'AnonymousUserID' );
            $currentUserID = eZUser::currentUserID();
            $user = eZUser::instance( $anonymousUserID );
            eZUser::setCurrentlyLoggedInUser( $user, $anonymousUserID );
            $anonymousAccess = $contentObject->attribute( 'can_read' );
            $user = eZUser::instance( $currentUserID );
            eZUser::setCurrentlyLoggedInUser( $user, $currentUserID );
            $anonymousAccess = $anonymousAccess ? 'true' : 'false';
        }
        else
        {
            $anonymousAccess = 'false';
        }

        // Load index time boost factors if any
        //$boostMetaFields = $this->FindINI->variable( "IndexBoost", "MetaField" );
        $boostClasses = $this->FindINI->variable( 'IndexBoost', 'Class' );
        $boostAttributes = $this->FindINI->variable( 'IndexBoost', 'Attribute' );
        $boostDatatypes = $this->FindINI->variable( 'IndexBoost', 'Datatype' );
        $reverseRelatedScale = $this->FindINI->variable( 'IndexBoost', 'ReverseRelatedScale' );

        // Initialise default doc boost
        $docBoost = 1.0;
        $contentClassIdentifier = $contentObject->attribute( 'class_identifier' );
        // Just test if the boost factor is defined by checking if it has a numeric value
        if ( isset( $boostClasses[$contentClassIdentifier] ) && is_numeric( $boostClasses[$contentClassIdentifier] ) )
        {
            $docBoost += $boostClasses[$contentClassIdentifier];
        }
        // Google like boosting, using eZ Publish reverseRelatedObjectCount
        $reverseRelatedObjectCount = $contentObject->reverseRelatedObjectCount();
        $docBoost += $reverseRelatedScale * $reverseRelatedObjectCount;

        //  Create the list of available languages for this version :
        $availableLanguages = $currentVersion->translationList( false, false );

        // Loop over each language version and create an eZSolrDoc for it
        foreach ( $availableLanguages as $languageCode )
        {
            $doc = new eZSolrDoc( $docBoost );
            // Set global unique object ID
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'guid' ), $this->guid( $contentObject, $languageCode ) );

            // Set installation identifier
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'installation_id' ), self::installationID() );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'installation_url' ),
                            $this->FindINI->variable( 'SiteSettings', 'URLProtocol' ) . $this->SiteINI->variable( 'SiteSettings', 'SiteURL' ) . '/' );

            // Set Object attributes
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'name' ), $contentObject->name( false, $languageCode ) );
            // Also add value to the "sort_name" field as "name" is unsortable, due to Solr limitation (tokenized field)
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'sort_name' ), $contentObject->name( false, $languageCode ) );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'anon_access' ), $anonymousAccess );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'language_code' ), $languageCode );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'available_language_codes' ), $availableLanguages );

            if ( $owner = $contentObject->attribute( 'owner' ) )
            {
                // Set owner name
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'owner_name' ),
                                $owner->name( false, $languageCode ) );

                // Set owner group ID
                foreach ( $owner->attribute( 'parent_nodes' ) as $groupID )
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'owner_group_id' ), $groupID );
                }
            }

            // from eZ Publish 4.1 only: object states
            // so let's check if the content object has it
            if ( method_exists( $contentObject, 'stateIDArray' ) )
            {
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'object_states' ),
                                $contentObject->stateIDArray() );
            }

            // Set content object meta attribute values.
            foreach ( $metaAttributeValues as $metaInfo )
            {
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] ),
                                ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
            }

            // Set content node meta attribute values.
            foreach ( $nodeAttributeValues as $nodeID => $metaInfoArray )
            {
                foreach( $metaInfoArray as $metaInfo)
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] ),
                                ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
                }
            }

            // Main node gets single valued fields for sorting, using a dedicated prefix
            foreach ( $nodeAttributeValues[$mainNodeID] as $metaInfo )
            {
                $fieldName = 'main_node_' . ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] );
                $doc->addField( $fieldName,
                                    ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'],
                                    $metaInfo['fieldType'] ) );
            }


            // Add main url_alias
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'main_url_alias' ), $mainNode->attribute( 'url_alias' ) );

            // Add main path_string
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'main_path_string' ), $mainNode->attribute( 'path_string' ) );

            // add nodeid of all parent nodes path elements
            foreach ( $nodePathArray as $pathArray )
            {
                foreach ( $pathArray as $pathNodeID)
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'path' ), $pathNodeID );
                }
            }

            // Since eZ Fnd 2.3
            // cannot call metafield field bame constructor as we are creating multiple fields
            foreach ( $mainNodePathArray as $key => $pathNodeID )
            {
                $doc->addField( 'meta_main_path_element_' . $key . '_si', $pathNodeID );

            }

            eZContentObject::recursionProtectionStart();

            // Loop through all eZContentObjectAttributes and add them to the Solr document.
            // @since eZ Find 2.3: look for the attribute storage setting

            $doAttributeStorage = ( ( $this->FindINI->variable( 'IndexOptions', 'EnableSolrAttributeStorage' ) ) === 'true' ) ? true : false;

            if ( $doAttributeStorage )
            {
                $allAttributeData = array();
            }

            foreach ( $currentVersion->contentObjectAttributes( $languageCode ) as $attribute )
            {
                $metaDataText = '';
                $classAttribute = $attribute->contentClassAttribute();
                $attributeIdentifier = $classAttribute->attribute( 'identifier' );
                $combinedIdentifier = $contentClassIdentifier . '/' . $attributeIdentifier;
                $boostAttribute = false;
                if ( isset( $boostAttributes[$attributeIdentifier]) && is_numeric( $boostAttributes[$attributeIdentifier]))
                {
                    $boostAttribute = $boostAttributes[$attributeIdentifier];
                }
                if ( isset( $boostAttributes[$combinedIdentifier]) && is_numeric( $boostAttributes[$combinedIdentifier]))
                {
                    $boostAttribute += $boostAttributes[$combinedIdentifier];
                }
                if ( $classAttribute->attribute( 'is_searchable' ) == 1 )
                {
                    $documentFieldBase = ezfSolrDocumentFieldBase::getInstance( $attribute );
                    $this->addFieldBaseToDoc( $documentFieldBase, $doc, $boostAttribute );
                }

                if ( $doAttributeStorage )
                {
                    $storageFieldName = ezfSolrStorage::getSolrStorageFieldName( $attributeIdentifier );
                    $attributeData = ezfSolrStorage::getAttributeData( $attribute );
                    $allAttributeData['data_map'][$attributeIdentifier] = $attributeData;
                    $doc->addField( $storageFieldName, ezfSolrStorage::serializeData( $attributeData ) );
                }
            }
            eZContentObject::recursionProtectionEnd();

            if ( $doAttributeStorage )
            {
                $doc->addField( 'as_all_bst', ezfSolrStorage::serializeData( $allAttributeData ) );
            }

            $docList[$languageCode] = $doc;
        }

        // Since eZFind 2.7: indexhooks
        $generalPlugins = $this->FindINI->variable( 'IndexPlugins', 'General' );
        $classPlugins   = $this->FindINI->variable( 'IndexPlugins', 'Class' );
        if ( !empty( $generalPlugins ) )
        {
            foreach ( $generalPlugins as $pluginClassString )
            {
                if( !class_exists( $pluginClassString ) )
                {
                    eZDebug::writeError( "Unable to find the PHP class '$classname' defined for index time plugins for eZ Find", __METHOD__ );
                    continue;
                }
                $plugin = new $pluginClassString;
                if ( $plugin instanceof ezfIndexPlugin )
                {
                    $plugin->modify( $contentObject, $docList );
                }
            }
        }

        if (array_key_exists($contentObject->attribute( 'class_identifier' ), $classPlugins ) )
        {
            $pluginClassString = $classPlugins[$contentObject->attribute( 'class_identifier' )];
            if ( class_exists( $pluginClassString ) )
            {
                $plugin = new $pluginClassString;
                if ($plugin instanceof ezfIndexPlugin)
                {
                        $plugin->modify( $contentObject, $docList );
                }
            }
        }

        $optimize = false;
        if ( $this->FindINI->variable( 'IndexOptions', 'DisableDirectCommits' ) === 'true' )
        {
            $commit = false;
        }
        $commitWithin = 0;
        if ( $this->FindINI->variable( 'IndexOptions', 'CommitWithin' ) > 0 )
        {
            $commitWithin = $this->FindINI->variable( 'IndexOptions', 'CommitWithin' );
        }
        if ( $commit && ( $this->FindINI->variable( 'IndexOptions', 'OptimizeOnCommit' ) === 'enabled' ) )
        {
            $optimize = true;
        }

        if ( $this->UseMultiLanguageCores === true)
        {
            $result = true;
            foreach ( $availableLanguages as $languageCode )
            {
                $languageResult = $this->SolrLanguageShards[$languageCode]->addDocs( array( $docList[$languageCode] ), $commit, $optimize, $commitWithin );
                if ( !$languageResult )
                {
                    $result = false;
                }
            }
            return $result;
        }
        else
        {
            return $this->Solr->addDocs( $docList, $commit, $optimize, $commitWithin );
        }


    }
コード例 #21
0
 static function loginUser($login, $password, $authenticationMatch = false)
 {
     $http = eZHTTPTool::instance();
     $db = eZDB::instance();
     if ($authenticationMatch === false) {
         $authenticationMatch = eZUser::authenticationMatch();
     }
     $loginEscaped = $db->escapeString($login);
     $passwordEscaped = $db->escapeString($password);
     $loginArray = array();
     if ($authenticationMatch & eZUser::AUTHENTICATE_LOGIN) {
         $loginArray[] = "login='******'";
     }
     if ($authenticationMatch & eZUser::AUTHENTICATE_EMAIL) {
         $loginArray[] = "email='{$loginEscaped}'";
     }
     if (count($loginArray) == 0) {
         $loginArray[] = "login='******'";
     }
     $loginText = implode(' OR ', $loginArray);
     $contentObjectStatus = eZContentObject::STATUS_PUBLISHED;
     $ini = eZINI::instance();
     $textFileIni = eZINI::instance('textfile.ini');
     $databaseName = $db->databaseName();
     // if mysql
     if ($databaseName === 'mysql') {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                        ezcontentobject.status='{$contentObjectStatus}' AND\n                        ( ezcontentobject.id=contentobject_id OR ( password_hash_type=4 AND ( {$loginText} ) AND password_hash=PASSWORD('{$passwordEscaped}') ) )";
     } else {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                            ezcontentobject.status='{$contentObjectStatus}' AND\n                            ezcontentobject.id=contentobject_id";
     }
     $users = $db->arrayQuery($query);
     $exists = false;
     if (count($users) >= 1) {
         foreach ($users as $userRow) {
             $userID = $userRow['contentobject_id'];
             $hashType = $userRow['password_hash_type'];
             $hash = $userRow['password_hash'];
             $exists = eZUser::authenticateHash($userRow['login'], $password, eZUser::site(), $hashType, $hash);
             // If hash type is MySql
             if ($hashType == eZUser::PASSWORD_HASH_MYSQL and $databaseName === 'mysql') {
                 $queryMysqlUser = "******";
                 $mysqlUsers = $db->arrayQuery($queryMysqlUser);
                 if (count($mysqlUsers) >= 1) {
                     $exists = true;
                 }
             }
             eZDebugSetting::writeDebug('kernel-user', eZUser::createHash($userRow['login'], $password, eZUser::site(), $hashType), "check hash");
             eZDebugSetting::writeDebug('kernel-user', $hash, "stored hash");
             // If current user has been disabled after a few failed login attempts.
             $canLogin = eZUser::isEnabledAfterFailedLogin($userID);
             if ($exists) {
                 // We should store userID for warning message.
                 $GLOBALS['eZFailedLoginAttemptUserID'] = $userID;
                 $userSetting = eZUserSetting::fetch($userID);
                 $isEnabled = $userSetting->attribute("is_enabled");
                 if ($hashType != eZUser::hashType() and strtolower($ini->variable('UserSettings', 'UpdateHash')) == 'true') {
                     $hashType = eZUser::hashType();
                     $hash = eZUser::createHash($login, $password, eZUser::site(), $hashType);
                     $db->query("UPDATE ezuser SET password_hash='{$hash}', password_hash_type='{$hashType}' WHERE contentobject_id='{$userID}'");
                 }
                 break;
             }
         }
     }
     if ($exists and $isEnabled and $canLogin) {
         eZDebugSetting::writeDebug('kernel-user', $userRow, 'user row');
         $user = new eZUser($userRow);
         eZDebugSetting::writeDebug('kernel-user', $user, 'user');
         $userID = $user->attribute('contentobject_id');
         eZUser::updateLastVisit($userID);
         eZUser::setCurrentlyLoggedInUser($user, $userID);
         // Reset number of failed login attempts
         eZUser::setFailedLoginAttempts($userID, 0);
         return $user;
     } else {
         if ($textFileIni->variable('TextFileSettings', 'TextFileEnabled') == "true") {
             $fileName = $textFileIni->variable('TextFileSettings', 'FileName');
             $filePath = $textFileIni->variable('TextFileSettings', 'FilePath');
             $defaultUserPlacement = $ini->variable("UserSettings", "DefaultUserPlacement");
             $separator = $textFileIni->variable("TextFileSettings", "FileFieldSeparator");
             $loginColumnNr = $textFileIni->variable("TextFileSettings", "LoginAttribute");
             $passwordColumnNr = $textFileIni->variable("TextFileSettings", "PasswordAttribute");
             $emailColumnNr = $textFileIni->variable("TextFileSettings", "EmailAttribute");
             $lastNameColumnNr = $textFileIni->variable("TextFileSettings", "LastNameAttribute");
             $firstNameColumnNr = $textFileIni->variable("TextFileSettings", "FirstNameAttribute");
             if ($textFileIni->hasVariable('TextFileSettings', 'DefaultUserGroupType')) {
                 $UserGroupType = $textFileIni->variable('TextFileSettings', 'DefaultUserGroupType');
                 $UserGroup = $textFileIni->variable('TextFileSettings', 'DefaultUserGroup');
             }
             if ($UserGroupType != null) {
                 if ($UserGroupType == "name") {
                     $groupName = $UserGroup;
                     $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                       FROM ezcontentobject, ezcontentobject_tree\n                                       WHERE ezcontentobject.name='{$groupName}'\n                                       AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                     $groupObject = $db->arrayQuery($groupQuery);
                     if (count($groupObject) > 0) {
                         $defaultUserPlacement = $groupObject[0]['node_id'];
                     }
                 } else {
                     if ($UserGroupType == "id") {
                         $groupID = $UserGroup;
                         $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                           FROM ezcontentobject, ezcontentobject_tree\n                                           WHERE ezcontentobject.id='{$groupID}'\n                                           AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                         $groupObject = $db->arrayQuery($groupQuery);
                         if (count($groupObject) > 0) {
                             $defaultUserPlacement = $groupObject[0]['node_id'];
                         }
                     }
                 }
             }
             if ($filePath != "root" and $filePath != null) {
                 $fileName = $filePath . "/" . $fileName;
             }
             if (file_exists($fileName)) {
                 $handle = fopen($fileName, "r");
             } else {
                 // Increase number of failed login attempts.
                 if (isset($userID)) {
                     eZUser::setFailedLoginAttempts($userID);
                 }
                 return false;
             }
             while (!feof($handle)) {
                 $line = trim(fgets($handle, 4096));
                 if ($line === '') {
                     continue;
                 }
                 if ($separator == "tab") {
                     $userArray = explode("\t", $line);
                 } else {
                     $userArray = explode($separator, $line);
                 }
                 $uid = $userArray[$loginColumnNr - 1];
                 $email = $userArray[$emailColumnNr - 1];
                 $pass = $userArray[$passwordColumnNr - 1];
                 $firstName = $userArray[$firstNameColumnNr - 1];
                 $lastName = $userArray[$lastNameColumnNr - 1];
                 if ($login == $uid) {
                     if (trim($pass) == $password) {
                         $createNewUser = true;
                         $existUser = eZUser::fetchByName($login);
                         if ($existUser != null) {
                             $createNewUser = false;
                         }
                         if ($createNewUser) {
                             $userClassID = $ini->variable("UserSettings", "UserClassID");
                             $userCreatorID = $ini->variable("UserSettings", "UserCreatorID");
                             $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID");
                             $remoteID = "TextFile_" . $login;
                             $db->begin();
                             // The content object may already exist if this process has failed once before, before the eZUser object was created.
                             // Therefore we try to fetch the eZContentObject before instantiating it.
                             $contentObject = eZContentObject::fetchByRemoteID($remoteID);
                             if (!is_object($contentObject)) {
                                 $class = eZContentClass::fetch($userClassID);
                                 $contentObject = $class->instantiate($userCreatorID, $defaultSectionID);
                             }
                             $contentObject->setAttribute('remote_id', $remoteID);
                             $contentObject->store();
                             $contentObjectID = $contentObject->attribute('id');
                             $userID = $contentObjectID;
                             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $defaultUserPlacement, 'is_main' => 1));
                             $nodeAssignment->store();
                             $version = $contentObject->version(1);
                             $version->setAttribute('modified', time());
                             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
                             $version->store();
                             $contentObjectID = $contentObject->attribute('id');
                             $contentObjectAttributes = $version->contentObjectAttributes();
                             $contentObjectAttributes[0]->setAttribute('data_text', $firstName);
                             $contentObjectAttributes[0]->store();
                             $contentObjectAttributes[1]->setAttribute('data_text', $lastName);
                             $contentObjectAttributes[1]->store();
                             $user = eZUser::create($userID);
                             $user->setAttribute('login', $login);
                             $user->setAttribute('email', $email);
                             $user->setAttribute('password_hash', "");
                             $user->setAttribute('password_hash_type', 0);
                             $user->store();
                             eZUser::updateLastVisit($userID);
                             eZUser::setCurrentlyLoggedInUser($user, $userID);
                             // Reset number of failed login attempts
                             eZUser::setFailedLoginAttempts($userID, 0);
                             $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
                             $db->commit();
                             return $user;
                         } else {
                             $db->begin();
                             // Update user information
                             $userID = $existUser->attribute('contentobject_id');
                             $contentObject = eZContentObject::fetch($userID);
                             $parentNodeID = $contentObject->attribute('main_parent_node_id');
                             $currentVersion = $contentObject->attribute('current_version');
                             $version = $contentObject->attribute('current');
                             $contentObjectAttributes = $version->contentObjectAttributes();
                             $contentObjectAttributes[0]->setAttribute('data_text', $firstName);
                             $contentObjectAttributes[0]->store();
                             $contentObjectAttributes[1]->setAttribute('data_text', $lastName);
                             $contentObjectAttributes[1]->store();
                             $existUser = eZUser::fetch($userID);
                             $existUser->setAttribute('email', $email);
                             $existUser->setAttribute('password_hash', "");
                             $existUser->setAttribute('password_hash_type', 0);
                             $existUser->store();
                             if ($defaultUserPlacement != $parentNodeID) {
                                 $newVersion = $contentObject->createNewVersion();
                                 $newVersion->assignToNode($defaultUserPlacement, 1);
                                 $newVersion->removeAssignment($parentNodeID);
                                 $newVersionNr = $newVersion->attribute('version');
                                 $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $userID, 'version' => $newVersionNr));
                             }
                             eZUser::updateLastVisit($userID);
                             eZUser::setCurrentlyLoggedInUser($existUser, $userID);
                             // Reset number of failed login attempts
                             eZUser::setFailedLoginAttempts($userID, 0);
                             $db->commit();
                             return $existUser;
                         }
                     } else {
                         // Increase number of failed login attempts.
                         if (isset($userID)) {
                             eZUser::setFailedLoginAttempts($userID);
                         }
                         return false;
                     }
                 }
             }
             fclose($handle);
         }
     }
     // Increase number of failed login attempts.
     if (isset($userID)) {
         eZUser::setFailedLoginAttempts($userID);
     }
     return false;
 }
コード例 #22
0
 /**
  * Returns a shared instance of the eZUser class pr $id value.
  * If user can not be fetched, then anonymous user is returned and
  * a warning trown, if anonymous user can not be fetched, then NoUser
  * is returned and another warning is thrown.
  *
  * @param int|false $id On false: Gets current user id from session
  *        or from {@link eZUser::anonymousId()} if not set.
  * @return eZUser
  */
 static function instance($id = false)
 {
     if (!empty($GLOBALS["eZUserGlobalInstance_{$id}"])) {
         return $GLOBALS["eZUserGlobalInstance_{$id}"];
     }
     $userId = $id;
     $currentUser = null;
     $http = eZHTTPTool::instance();
     $anonymousUserID = self::anonymousId();
     $sessionHasStarted = eZSession::hasStarted();
     // If not specified get the current user
     if ($userId === false) {
         if ($sessionHasStarted) {
             $userId = $http->sessionVariable('eZUserLoggedInID');
             if (!is_numeric($userId)) {
                 $userId = $anonymousUserID;
                 eZSession::setUserID($userId);
                 $http->setSessionVariable('eZUserLoggedInID', $userId);
             }
         } else {
             $userId = $anonymousUserID;
             eZSession::setUserID($userId);
         }
     }
     // Check user cache (this effectivly fetches user from cache)
     // user not found if !isset( isset( $userCache['info'][$userId] ) )
     $userCache = self::getUserCacheByUserId($userId);
     if (isset($userCache['info'][$userId])) {
         $userArray = $userCache['info'][$userId];
         if (is_numeric($userArray['contentobject_id'])) {
             $currentUser = new eZUser($userArray);
             $currentUser->setUserCache($userCache);
         }
     }
     $ini = eZINI::instance();
     // Check if:
     // - the user has not logged out,
     // - the user is not logged in,
     // - and if a automatic single sign on plugin is enabled.
     if (!self::$userHasLoggedOut && is_object($currentUser) && !$currentUser->isRegistered()) {
         $ssoHandlerArray = $ini->variable('UserSettings', 'SingleSignOnHandlerArray');
         if (!empty($ssoHandlerArray)) {
             $ssoUser = false;
             foreach ($ssoHandlerArray as $ssoHandler) {
                 $className = 'eZ' . $ssoHandler . 'SSOHandler';
                 if (class_exists($className)) {
                     $impl = new $className();
                     $ssoUser = $impl->handleSSOLogin();
                     // If a user was found via SSO, then use it
                     if ($ssoUser !== false) {
                         $currentUser = $ssoUser;
                         $userId = $currentUser->attribute('contentobject_id');
                         $userInfo = array();
                         $userInfo[$userId] = array('contentobject_id' => $userId, 'login' => $currentUser->attribute('login'), 'email' => $currentUser->attribute('email'), 'password_hash' => $currentUser->attribute('password_hash'), 'password_hash_type' => $currentUser->attribute('password_hash_type'));
                         eZSession::setUserID($userId);
                         $http->setSessionVariable('eZUserLoggedInID', $userId);
                         eZUser::updateLastVisit($userId);
                         eZUser::setCurrentlyLoggedInUser($currentUser, $userId);
                         eZHTTPTool::redirect(eZSys::wwwDir() . eZSys::indexFile(false) . eZSys::requestURI() . eZSys::queryString(), array(), 302);
                         eZExecution::cleanExit();
                     }
                 } else {
                     eZDebug::writeError("Undefined ssoHandler class: {$className}", __METHOD__);
                 }
             }
         }
     }
     if ($userId != $anonymousUserID) {
         $sessionInactivityTimeout = $ini->variable('Session', 'ActivityTimeout');
         if (!isset($GLOBALS['eZSessionIdleTime'])) {
             eZUser::updateLastVisit($userId);
         } else {
             $sessionIdle = $GLOBALS['eZSessionIdleTime'];
             if ($sessionIdle > $sessionInactivityTimeout) {
                 eZUser::updateLastVisit($userId);
             }
         }
     }
     if (!$currentUser) {
         $currentUser = eZUser::fetch(self::anonymousId());
         eZDebug::writeWarning('User not found, returning anonymous');
     }
     if (!$currentUser) {
         $currentUser = new eZUser(array('id' => -1, 'login' => 'NoUser'));
         eZDebug::writeWarning('Anonymous user not found, returning NoUser');
     }
     $GLOBALS["eZUserGlobalInstance_{$id}"] = $currentUser;
     return $currentUser;
 }
コード例 #23
0
ファイル: childrenremove.php プロジェクト: RemyLi/ez4
$deleteIDArray = $srcNodesID ? explode(',', $srcNodesID) : false;
if (!$deleteIDArray) {
    $cli->error("Subtree remove Error!\nCannot get subtree nodes. Please check nodes-id argument and try again.");
    $script->showHelp();
    $script->shutdown(1);
}
$ini = eZINI::instance();
// Get user's ID who can remove subtrees. (Admin by default with userID = 14)
$userCreatorID = $ini->variable("UserSettings", "UserCreatorID");
/** @var eZUser $user */
$user = eZUser::fetch($userCreatorID);
if (!$user) {
    $cli->error("Subtree remove Error!\nCannot get user object by userID = '{$userCreatorID}'.\n(See site.ini[UserSettings].UserCreatorID)");
    $script->shutdown(1);
}
eZUser::setCurrentlyLoggedInUser($user, $userCreatorID);
$cli->notice("Logged as " . $user->Login . " userID = '{$userCreatorID}' (See site.ini[UserSettings].UserCreatorID)");
$params = array('Depth' => 1, 'Limit' => $size, 'Offset' => 0);
if ($classes) {
    $params['ClassFilterType'] = 'include';
    $params['ClassFilterArray'] = explode(',', $classes);
    $cli->notice("Classes filters : " . implode(', ', $params['ClassFilterArray']));
}
//$cli->output(var_export($params, true));
if ($disable_indexing) {
    eZINI::instance()->setVariable('ContentSettings', 'ViewCaching', 'disabled');
    eZINI::instance()->setVariable('ContentSettings', 'StaticCache', 'disabled');
    eZINI::instance()->setVariable('ContentSettings', 'PreViewCache', 'disabled');
    eZINI::instance()->setVariable('SearchSettings', 'DelayedIndexing', 'enabled');
    eZINI::instance('ezfind.ini')->setVariable('IndexOptions', 'OptimizeOnCommit', 'disabled');
    $cli->notice("indexing disabled. Don't forget to reindex content.");
コード例 #24
0
ファイル: password.php プロジェクト: netbliss/ezmbpaex
             $newPasswordNotValidate = 1;
         } else {
             $oldHash = $user->createHash($login, $oldPassword, $site, $type);
             $newHash = $user->createHash($login, $newPassword, $site, $type);
             if ($oldHash == $newHash) {
                 // if audit is enabled password changes should be logged
                 eZAudit::writeAudit('user-password-change-self-fail', array('UserID: ' => $UserID, 'Login: '******'Comment: ' => 'New and old password are the same'));
                 $newPasswordMustDiffer = 1;
             } else {
                 // if audit is enabled password changes should be logged
                 eZAudit::writeAudit('user-password-change-self', array('UserID: ' => $UserID, 'Login: '******'';
                 eZUser::setCurrentlyLoggedInUser($user, $UserID);
                 if ($http->hasPostVariable("RedirectOnChange")) {
                     return $Module->redirectTo($http->postVariable("RedirectOnChange"));
                 }
                 eZRedirectManager::redirectTo($Module, $redirectionURI);
                 return;
             }
         }
     }
     $newPassword = '';
     $confirmPassword = '';
     $message = true;
 } else {
     // if audit is enabled password changes should be logged
     eZAudit::writeAudit('user-password-change-self-fail', array('UserID: ' => $UserID, 'Login: '******'Comment: ' => 'Password not match password confirmation'));
     $newPassword = "";
コード例 #25
0
 /**
  * Executes the purge operation
  *
  * @param int|null $iterationLimit Number of trashed objects to treat per iteration, use null to use a default value.
  * @param int|null $sleep Number of seconds to sleep between two iterations, use null to use a default value.
  *
  * @return bool True if the operation succeeded.
  */
 public function run($iterationLimit = 100, $sleep = 1)
 {
     if ($iterationLimit === null) {
         $iterationLimit = 100;
     }
     if ($sleep === null) {
         $sleep = 1;
     }
     if ($this->memoryMonitoring) {
         eZLog::rotateLog($this->logFile);
         $this->cli->output("Logging memory usage to {$this->logFile}");
     }
     $this->cli->output("Purging trash items:");
     $this->monitor("start");
     $db = eZDB::instance();
     // Get user's ID who can remove subtrees. (Admin by default with userID = 14)
     $userCreatorID = eZINI::instance()->variable("UserSettings", "UserCreatorID");
     $user = eZUser::fetch($userCreatorID);
     if (!$user) {
         $this->cli->error("Cannot get user object with userID = '{$userCreatorID}'.\n(See site.ini[UserSettings].UserCreatorID)");
         return false;
     }
     eZUser::setCurrentlyLoggedInUser($user, $userCreatorID);
     $trashCount = eZContentObjectTrashNode::trashListCount(false);
     if (!$this->quiet) {
         $this->cli->output("Found {$trashCount} object(s) in trash.");
     }
     if ($trashCount == 0) {
         return true;
     }
     if ($this->script !== null) {
         $this->script->resetIteration($trashCount);
     }
     while ($trashCount > 0) {
         $this->monitor("iteration start");
         $trashList = eZContentObjectTrashNode::trashList(array('Limit' => $iterationLimit), false);
         $db->begin();
         foreach ($trashList as $trashNode) {
             $object = $trashNode->attribute('object');
             $this->monitor("purge");
             $object->purge();
             if ($this->script !== null) {
                 $this->script->iterate($this->cli, true);
             }
         }
         if (!$db->commit()) {
             $this->cli->output();
             $this->cli->error('Trash has not been emptied, impossible to commit the whole transaction');
             return false;
         }
         $trashCount = eZContentObjectTrashNode::trashListCount(false);
         if ($trashCount > 0) {
             eZContentObject::clearCache();
             if ($sleep > 0) {
                 sleep($sleep);
             }
         }
         $this->monitor("iteration end");
     }
     if (!$this->quiet) {
         $this->cli->output('Trash successfully emptied');
     }
     $this->monitor("end");
     return true;
 }
コード例 #26
0
ファイル: ezldapuser.php プロジェクト: CG77/ezpublish-legacy
 static function loginUser($login, $password, $authenticationMatch = false)
 {
     $http = eZHTTPTool::instance();
     $db = eZDB::instance();
     if ($authenticationMatch === false) {
         $authenticationMatch = eZUser::authenticationMatch();
     }
     $loginEscaped = $db->escapeString($login);
     $passwordEscaped = $db->escapeString($password);
     $loginLdapEscaped = self::ldap_escape($login);
     $loginArray = array();
     if ($authenticationMatch & eZUser::AUTHENTICATE_LOGIN) {
         $loginArray[] = "login='******'";
     }
     if ($authenticationMatch & eZUser::AUTHENTICATE_EMAIL) {
         $loginArray[] = "email='{$loginEscaped}'";
     }
     if (count($loginArray) == 0) {
         $loginArray[] = "login='******'";
     }
     $loginText = implode(' OR ', $loginArray);
     $contentObjectStatus = eZContentObject::STATUS_PUBLISHED;
     $ini = eZINI::instance();
     $LDAPIni = eZINI::instance('ldap.ini');
     $databaseName = $db->databaseName();
     // if mysql
     if ($databaseName === 'mysql') {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                            ezcontentobject.status='{$contentObjectStatus}' AND\n                            ( ezcontentobject.id=contentobject_id OR ( password_hash_type=4 AND ( {$loginText} ) AND password_hash=PASSWORD('{$passwordEscaped}') ) )";
     } else {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                            ezcontentobject.status='{$contentObjectStatus}' AND\n                            ezcontentobject.id=contentobject_id";
     }
     $users = $db->arrayQuery($query);
     $exists = false;
     if (count($users) >= 1) {
         foreach ($users as $userRow) {
             $userID = $userRow['contentobject_id'];
             $hashType = $userRow['password_hash_type'];
             $hash = $userRow['password_hash'];
             $exists = eZUser::authenticateHash($userRow['login'], $password, eZUser::site(), $hashType, $hash);
             // If hash type is MySql
             if ($hashType == eZUser::PASSWORD_HASH_MYSQL and $databaseName === 'mysql') {
                 $queryMysqlUser = "******";
                 $mysqlUsers = $db->arrayQuery($queryMysqlUser);
                 if (count($mysqlUsers) >= 1) {
                     $exists = true;
                 }
             }
             eZDebugSetting::writeDebug('kernel-user', eZUser::createHash($userRow['login'], $password, eZUser::site(), $hashType), "check hash");
             eZDebugSetting::writeDebug('kernel-user', $hash, "stored hash");
             // If current user has been disabled after a few failed login attempts.
             $canLogin = eZUser::isEnabledAfterFailedLogin($userID);
             if ($exists) {
                 // We should store userID for warning message.
                 $GLOBALS['eZFailedLoginAttemptUserID'] = $userID;
                 $userSetting = eZUserSetting::fetch($userID);
                 $isEnabled = $userSetting->attribute("is_enabled");
                 if ($hashType != eZUser::hashType() and strtolower($ini->variable('UserSettings', 'UpdateHash')) == 'true') {
                     $hashType = eZUser::hashType();
                     $hash = eZUser::createHash($login, $password, eZUser::site(), $hashType);
                     $db->query("UPDATE ezuser SET password_hash='{$hash}', password_hash_type='{$hashType}' WHERE contentobject_id='{$userID}'");
                 }
                 break;
             }
         }
     }
     if ($exists and $isEnabled and $canLogin) {
         eZDebugSetting::writeDebug('kernel-user', $userRow, 'user row');
         $user = new eZUser($userRow);
         eZDebugSetting::writeDebug('kernel-user', $user, 'user');
         $userID = $user->attribute('contentobject_id');
         eZUser::updateLastVisit($userID);
         eZUser::setCurrentlyLoggedInUser($user, $userID);
         // Reset number of failed login attempts
         eZUser::setFailedLoginAttempts($userID, 0);
         return $user;
     } else {
         if ($LDAPIni->variable('LDAPSettings', 'LDAPEnabled') === 'true') {
             // read LDAP ini settings
             // and then try to bind to the ldap server
             $LDAPDebugTrace = $LDAPIni->variable('LDAPSettings', 'LDAPDebugTrace') === 'enabled';
             $LDAPVersion = $LDAPIni->variable('LDAPSettings', 'LDAPVersion');
             $LDAPServer = $LDAPIni->variable('LDAPSettings', 'LDAPServer');
             $LDAPPort = $LDAPIni->variable('LDAPSettings', 'LDAPPort');
             $LDAPFollowReferrals = (int) $LDAPIni->variable('LDAPSettings', 'LDAPFollowReferrals');
             $LDAPBaseDN = $LDAPIni->variable('LDAPSettings', 'LDAPBaseDn');
             $LDAPBindUser = $LDAPIni->variable('LDAPSettings', 'LDAPBindUser');
             $LDAPBindPassword = $LDAPIni->variable('LDAPSettings', 'LDAPBindPassword');
             $LDAPSearchScope = $LDAPIni->variable('LDAPSettings', 'LDAPSearchScope');
             $LDAPLoginAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPLoginAttribute'));
             $LDAPFirstNameAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPFirstNameAttribute'));
             $LDAPFirstNameIsCN = $LDAPIni->variable('LDAPSettings', 'LDAPFirstNameIsCommonName') === 'true';
             $LDAPLastNameAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPLastNameAttribute'));
             $LDAPEmailAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPEmailAttribute'));
             $defaultUserPlacement = $ini->variable("UserSettings", "DefaultUserPlacement");
             $LDAPUserGroupAttributeType = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPUserGroupAttributeType'));
             $LDAPUserGroupAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPUserGroupAttribute'));
             if ($LDAPIni->hasVariable('LDAPSettings', 'Utf8Encoding')) {
                 $Utf8Encoding = $LDAPIni->variable('LDAPSettings', 'Utf8Encoding');
                 if ($Utf8Encoding == "true") {
                     $isUtf8Encoding = true;
                 } else {
                     $isUtf8Encoding = false;
                 }
             } else {
                 $isUtf8Encoding = false;
             }
             if ($LDAPIni->hasVariable('LDAPSettings', 'LDAPSearchFilters')) {
                 $LDAPFilters = $LDAPIni->variable('LDAPSettings', 'LDAPSearchFilters');
             }
             if ($LDAPIni->hasVariable('LDAPSettings', 'LDAPUserGroupType') and $LDAPIni->hasVariable('LDAPSettings', 'LDAPUserGroup')) {
                 $LDAPUserGroupType = $LDAPIni->variable('LDAPSettings', 'LDAPUserGroupType');
                 $LDAPUserGroup = $LDAPIni->variable('LDAPSettings', 'LDAPUserGroup');
             }
             $LDAPFilter = "( &";
             if (count($LDAPFilters) > 0) {
                 foreach (array_keys($LDAPFilters) as $key) {
                     $LDAPFilter .= "(" . $LDAPFilters[$key] . ")";
                 }
             }
             $LDAPEqualSign = trim($LDAPIni->variable('LDAPSettings', "LDAPEqualSign"));
             $LDAPBaseDN = str_replace($LDAPEqualSign, "=", $LDAPBaseDN);
             $LDAPFilter = str_replace($LDAPEqualSign, "=", $LDAPFilter);
             $LDAPBindUser = str_replace($LDAPEqualSign, "=", $LDAPBindUser);
             if ($LDAPDebugTrace) {
                 $debugArray = array('stage' => '1/5: Connecting and Binding to LDAP server', 'LDAPServer' => $LDAPServer, 'LDAPPort' => $LDAPPort, 'LDAPBindUser' => $LDAPBindUser, 'LDAPVersion' => $LDAPVersion);
                 // Set debug trace mode for ldap connections
                 if (function_exists('ldap_set_option')) {
                     ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
                 }
                 eZDebug::writeNotice(var_export($debugArray, true), __METHOD__);
             }
             if (function_exists('ldap_connect')) {
                 $ds = ldap_connect($LDAPServer, $LDAPPort);
             } else {
                 $ds = false;
             }
             if ($ds) {
                 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $LDAPVersion);
                 ldap_set_option($ds, LDAP_OPT_REFERRALS, $LDAPFollowReferrals);
                 if ($LDAPBindUser == '') {
                     $r = ldap_bind($ds);
                 } else {
                     $r = ldap_bind($ds, $LDAPBindUser, $LDAPBindPassword);
                 }
                 if (!$r) {
                     // Increase number of failed login attempts.
                     eZDebug::writeError('Cannot bind to LDAP server, might be something wronge with connetion or bind user!', __METHOD__);
                     if (isset($userID)) {
                         eZUser::setFailedLoginAttempts($userID);
                     }
                     $user = false;
                     return $user;
                 }
                 $LDAPFilter .= "({$LDAPLoginAttribute}={$loginLdapEscaped})";
                 $LDAPFilter .= ")";
                 ldap_set_option($ds, LDAP_OPT_SIZELIMIT, 0);
                 ldap_set_option($ds, LDAP_OPT_TIMELIMIT, 0);
                 $retrieveAttributes = array($LDAPLoginAttribute, $LDAPFirstNameAttribute, $LDAPLastNameAttribute, $LDAPEmailAttribute);
                 if ($LDAPUserGroupAttributeType) {
                     $retrieveAttributes[] = $LDAPUserGroupAttribute;
                 }
                 if ($LDAPDebugTrace) {
                     $debugArray = array('stage' => '2/5: finding user', 'LDAPFilter' => $LDAPFilter, 'retrieveAttributes' => $retrieveAttributes, 'LDAPSearchScope' => $LDAPSearchScope, 'LDAPBaseDN' => $LDAPBaseDN);
                     eZDebug::writeNotice(var_export($debugArray, true), __METHOD__);
                 }
                 if ($LDAPSearchScope == "one") {
                     $sr = ldap_list($ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes);
                 } else {
                     if ($LDAPSearchScope == "base") {
                         $sr = ldap_read($ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes);
                     } else {
                         $sr = ldap_search($ds, $LDAPBaseDN, $LDAPFilter, $retrieveAttributes);
                     }
                 }
                 $info = ldap_get_entries($ds, $sr);
                 if ($info['count'] > 1) {
                     // More than one user with same uid, not allow login.
                     eZDebug::writeWarning('More then one user with same uid, not allowed to login!', __METHOD__);
                     $user = false;
                     return $user;
                 } else {
                     if ($info['count'] < 1) {
                         // Increase number of failed login attempts.
                         if (isset($userID)) {
                             eZUser::setFailedLoginAttempts($userID);
                         }
                         // user DN was not found
                         eZDebug::writeWarning('User DN was not found!', __METHOD__);
                         $user = false;
                         return $user;
                     } else {
                         if ($LDAPDebugTrace) {
                             $debugArray = array('stage' => '3/5: real authentication of user', 'info' => $info);
                             eZDebug::writeNotice(var_export($debugArray, true), __METHOD__);
                         }
                     }
                 }
                 if (!$password) {
                     $password = crypt(microtime());
                 }
                 // is it real authenticated LDAP user?
                 if (!@ldap_bind($ds, $info[0]['dn'], $password)) {
                     // Increase number of failed login attempts.
                     if (isset($userID)) {
                         eZUser::setFailedLoginAttempts($userID);
                     }
                     eZDebug::writeWarning("User {$userID} failed to login!", __METHOD__);
                     $user = false;
                     return $user;
                 }
                 $extraNodeAssignments = array();
                 $userGroupClassID = $ini->variable("UserSettings", "UserGroupClassID");
                 // default user group assigning
                 if ($LDAPUserGroupType != null) {
                     if ($LDAPUserGroupType == "name") {
                         if (is_array($LDAPUserGroup)) {
                             foreach (array_keys($LDAPUserGroup) as $key) {
                                 $groupName = $db->escapeString($LDAPUserGroup[$key]);
                                 $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                                 FROM ezcontentobject, ezcontentobject_tree\n                                                WHERE ezcontentobject.name like '{$groupName}'\n                                                  AND ezcontentobject.id=ezcontentobject_tree.contentobject_id\n                                                  AND ezcontentobject.contentclass_id={$userGroupClassID}";
                                 $groupObject = $db->arrayQuery($groupQuery);
                                 if (count($groupObject) > 0 and $key == 0) {
                                     $defaultUserPlacement = $groupObject[0]['node_id'];
                                 } else {
                                     if (count($groupObject) > 0) {
                                         $extraNodeAssignments[] = $groupObject[0]['node_id'];
                                     }
                                 }
                             }
                         } else {
                             $groupName = $db->escapeString($LDAPUserGroup);
                             $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                             FROM ezcontentobject, ezcontentobject_tree\n                                            WHERE ezcontentobject.name like '{$groupName}'\n                                              AND ezcontentobject.id=ezcontentobject_tree.contentobject_id\n                                              AND ezcontentobject.contentclass_id={$userGroupClassID}";
                             $groupObject = $db->arrayQuery($groupQuery);
                             if (count($groupObject) > 0) {
                                 $defaultUserPlacement = $groupObject[0]['node_id'];
                             }
                         }
                     } else {
                         if ($LDAPUserGroupType == "id") {
                             if (is_array($LDAPUserGroup)) {
                                 foreach (array_keys($LDAPUserGroup) as $key) {
                                     $groupID = $LDAPUserGroup[$key];
                                     $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                                 FROM ezcontentobject, ezcontentobject_tree\n                                                WHERE ezcontentobject.id='{$groupID}'\n                                                  AND ezcontentobject.id=ezcontentobject_tree.contentobject_id\n                                                  AND ezcontentobject.contentclass_id={$userGroupClassID}";
                                     $groupObject = $db->arrayQuery($groupQuery);
                                     if (count($groupObject) > 0 and $key == 0) {
                                         $defaultUserPlacement = $groupObject[0]['node_id'];
                                     } else {
                                         if (count($groupObject) > 0) {
                                             $extraNodeAssignments[] = $groupObject[0]['node_id'];
                                         }
                                     }
                                 }
                             } else {
                                 $groupID = $LDAPUserGroup;
                                 $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                             FROM ezcontentobject, ezcontentobject_tree\n                                            WHERE ezcontentobject.id='{$groupID}'\n                                              AND ezcontentobject.id=ezcontentobject_tree.contentobject_id\n                                              AND ezcontentobject.contentclass_id={$userGroupClassID}";
                                 $groupObject = $db->arrayQuery($groupQuery);
                                 if (count($groupObject) > 0) {
                                     $defaultUserPlacement = $groupObject[0]['node_id'];
                                 }
                             }
                         }
                     }
                 }
                 // read group mapping LDAP settings
                 $LDAPGroupMappingType = $LDAPIni->variable('LDAPSettings', 'LDAPGroupMappingType');
                 $LDAPUserGroupMap = $LDAPIni->variable('LDAPSettings', 'LDAPUserGroupMap');
                 if (!is_array($LDAPUserGroupMap)) {
                     $LDAPUserGroupMap = array();
                 }
                 // group mapping constants
                 $ByMemberAttribute = 'SimpleMapping';
                 // by group's member attributes (with mapping)
                 $ByMemberAttributeHierarhicaly = 'GetGroupsTree';
                 // by group's member attributes hierarhically
                 $ByGroupAttribute = 'UseGroupAttribute';
                 // by user's group attribute (old style)
                 $groupMappingTypes = array($ByMemberAttribute, $ByMemberAttributeHierarhicaly, $ByGroupAttribute);
                 $userData =& $info[0];
                 // default mapping using old style
                 if (!in_array($LDAPGroupMappingType, $groupMappingTypes)) {
                     $LDAPGroupMappingType = $ByGroupAttribute;
                 }
                 if ($LDAPDebugTrace) {
                     $debugArray = array('stage' => '4/5: group mapping init', 'LDAPUserGroupType' => $LDAPUserGroupType, 'LDAPGroupMappingType' => $LDAPGroupMappingType, 'LDAPUserGroup' => $LDAPUserGroup, 'defaultUserPlacement' => $defaultUserPlacement, 'extraNodeAssignments' => $extraNodeAssignments);
                     eZDebug::writeNotice(var_export($debugArray, true), __METHOD__);
                 }
                 if ($LDAPGroupMappingType == $ByMemberAttribute or $LDAPGroupMappingType == $ByMemberAttributeHierarhicaly) {
                     $LDAPGroupBaseDN = $LDAPIni->variable('LDAPSettings', 'LDAPGroupBaseDN');
                     $LDAPGroupBaseDN = str_replace($LDAPEqualSign, '=', $LDAPGroupBaseDN);
                     $LDAPGroupClass = $LDAPIni->variable('LDAPSettings', 'LDAPGroupClass');
                     $LDAPGroupNameAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPGroupNameAttribute'));
                     $LDAPGroupMemberAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPGroupMemberAttribute'));
                     $LDAPGroupDescriptionAttribute = strtolower($LDAPIni->variable('LDAPSettings', 'LDAPGroupDescriptionAttribute'));
                     $groupSearchingDepth = $LDAPGroupMappingType == '1' ? 1 : 1000;
                     // now, get all parents for currently ldap authenticated user
                     $requiredParams = array();
                     $requiredParams['LDAPLoginAttribute'] = $LDAPLoginAttribute;
                     $requiredParams['LDAPGroupBaseDN'] = $LDAPGroupBaseDN;
                     $requiredParams['LDAPGroupClass'] = $LDAPGroupClass;
                     $requiredParams['LDAPGroupNameAttribute'] = $LDAPGroupNameAttribute;
                     $requiredParams['LDAPGroupMemberAttribute'] = $LDAPGroupMemberAttribute;
                     $requiredParams['LDAPGroupDescriptionAttribute'] = $LDAPGroupDescriptionAttribute;
                     $requiredParams['ds'] =& $ds;
                     if ($LDAPIni->variable('LDAPSettings', 'LDAPGroupRootNodeId') !== '') {
                         $requiredParams['TopUserGroupNodeID'] = $LDAPIni->variable('LDAPSettings', 'LDAPGroupRootNodeId');
                     } else {
                         $requiredParams['TopUserGroupNodeID'] = 5;
                     }
                     $groupsTree = array();
                     $stack = array();
                     $newfilter = '(&(objectClass=' . $LDAPGroupClass . ')(' . $LDAPGroupMemberAttribute . '=' . $userData['dn'] . '))';
                     $groupsTree[$userData['dn']] = array('data' => &$userData, 'parents' => array(), 'children' => array());
                     eZLDAPUser::getUserGroupsTree($requiredParams, $newfilter, $userData['dn'], $groupsTree, $stack, $groupSearchingDepth);
                     $userRecord =& $groupsTree[$userData['dn']];
                     if ($LDAPGroupMappingType == $ByMemberAttribute) {
                         if (count($userRecord['parents']) > 0) {
                             $remappedGroupNames = array();
                             foreach (array_keys($userRecord['parents']) as $key) {
                                 $parentGroup =& $userRecord['parents'][$key];
                                 if (isset($parentGroup['data'][$LDAPGroupNameAttribute])) {
                                     $ldapGroupName = $parentGroup['data'][$LDAPGroupNameAttribute];
                                     if (is_array($ldapGroupName)) {
                                         $ldapGroupName = $ldapGroupName['count'] > 0 ? $ldapGroupName[0] : '';
                                     }
                                     // remap group name and check that group exists
                                     if (array_key_exists($ldapGroupName, $LDAPUserGroupMap)) {
                                         $remmapedGroupName = $db->escapeString($LDAPUserGroupMap[$ldapGroupName]);
                                         $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                                         FROM ezcontentobject, ezcontentobject_tree\n                                                        WHERE ezcontentobject.name like '{$remmapedGroupName}'\n                                                          AND ezcontentobject.id=ezcontentobject_tree.contentobject_id\n                                                          AND ezcontentobject.contentclass_id={$userGroupClassID}";
                                         $groupRow = $db->arrayQuery($groupQuery);
                                         if (count($groupRow) > 0) {
                                             $userRecord['new_parents'][] = $groupRow[0]['node_id'];
                                         }
                                     }
                                 }
                             }
                         }
                     } else {
                         if ($LDAPGroupMappingType == $ByMemberAttributeHierarhicaly) {
                             $stack = array();
                             self::goAndPublishGroups($requiredParams, $userData['dn'], $groupsTree, $stack, $groupSearchingDepth, true);
                         }
                     }
                     if (isset($userRecord['new_parents']) and count($userRecord['new_parents']) > 0) {
                         $defaultUserPlacement = $userRecord['new_parents'][0];
                         $extraNodeAssignments = array_merge($extraNodeAssignments, $userRecord['new_parents']);
                     }
                 } else {
                     if ($LDAPGroupMappingType == $ByGroupAttribute) {
                         if ($LDAPUserGroupAttributeType) {
                             // Should we create user groups that are specified in LDAP, but not found in eZ Publish?
                             $createMissingGroups = $LDAPIni->variable('LDAPSettings', 'LDAPCreateMissingGroups') === 'enabled';
                             if ($LDAPIni->variable('LDAPSettings', 'LDAPGroupRootNodeId') !== '') {
                                 $parentNodeID = $LDAPIni->variable('LDAPSettings', 'LDAPGroupRootNodeId');
                             } else {
                                 $parentNodeID = 5;
                             }
                             $groupAttributeCount = $info[0][$LDAPUserGroupAttribute]['count'];
                             if ($LDAPUserGroupAttributeType == "name") {
                                 for ($i = 0; $i < $groupAttributeCount; $i++) {
                                     if ($isUtf8Encoding) {
                                         $groupName = utf8_decode($info[0][$LDAPUserGroupAttribute][$i]);
                                     } else {
                                         $groupName = $info[0][$LDAPUserGroupAttribute][$i];
                                     }
                                     // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                     self::getNodeAssignmentsForGroupName($groupName, $i == 0, $defaultUserPlacement, $extraNodeAssignments, $createMissingGroups, $parentNodeID);
                                 }
                             } else {
                                 if ($LDAPUserGroupAttributeType == "id") {
                                     for ($i = 0; $i < $groupAttributeCount; $i++) {
                                         if ($isUtf8Encoding) {
                                             $groupID = utf8_decode($info[0][$LDAPUserGroupAttribute][$i]);
                                         } else {
                                             $groupID = $info[0][$LDAPUserGroupAttribute][$i];
                                         }
                                         $groupName = "LDAP {$groupID}";
                                         // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                         self::getNodeAssignmentsForGroupName($groupName, $i == 0, $defaultUserPlacement, $extraNodeAssignments, $createMissingGroups, $parentNodeID);
                                     }
                                 } else {
                                     if ($LDAPUserGroupAttributeType == "dn") {
                                         for ($i = 0; $i < $groupAttributeCount; $i++) {
                                             $groupDN = $info[0][$LDAPUserGroupAttribute][$i];
                                             $groupName = self::getGroupNameByDN($ds, $groupDN);
                                             if ($groupName) {
                                                 // Save group node id to either defaultUserPlacement or extraNodeAssignments
                                                 self::getNodeAssignmentsForGroupName($groupName, $i == 0, $defaultUserPlacement, $extraNodeAssignments, $createMissingGroups, $parentNodeID);
                                             }
                                         }
                                     } else {
                                         eZDebug::writeError("Bad LDAPUserGroupAttributeType '{$LDAPUserGroupAttributeType}'. It must be either 'name', 'id' or 'dn'.", __METHOD__);
                                         $user = false;
                                         return $user;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 // remove ' last_name' from first_name if cn is used for first name
                 if ($LDAPFirstNameIsCN && isset($userData[$LDAPFirstNameAttribute]) && isset($userData[$LDAPLastNameAttribute])) {
                     $userData[$LDAPFirstNameAttribute][0] = str_replace(' ' . $userData[$LDAPLastNameAttribute][0], '', $userData[$LDAPFirstNameAttribute][0]);
                 }
                 if (isset($userData[$LDAPEmailAttribute])) {
                     $LDAPuserEmail = $userData[$LDAPEmailAttribute][0];
                 } else {
                     if (trim($LDAPIni->variable('LDAPSettings', 'LDAPEmailEmptyAttributeSuffix'))) {
                         $LDAPuserEmail = $login . $LDAPIni->variable('LDAPSettings', 'LDAPEmailEmptyAttributeSuffix');
                     } else {
                         $LDAPuserEmail = false;
                     }
                 }
                 $userAttributes = array('login' => $login, 'first_name' => isset($userData[$LDAPFirstNameAttribute]) ? $userData[$LDAPFirstNameAttribute][0] : false, 'last_name' => isset($userData[$LDAPLastNameAttribute]) ? $userData[$LDAPLastNameAttribute][0] : false, 'email' => $LDAPuserEmail);
                 if ($LDAPDebugTrace) {
                     $debugArray = array('stage' => '5/5: storing user', 'userAttributes' => $userAttributes, 'isUtf8Encoding' => $isUtf8Encoding, 'defaultUserPlacement' => $defaultUserPlacement, 'extraNodeAssignments' => $extraNodeAssignments);
                     eZDebug::writeNotice(var_export($debugArray, true), __METHOD__);
                 }
                 $oldUser = clone eZUser::currentUser();
                 $existingUser = eZLDAPUser::publishUpdateUser($extraNodeAssignments, $defaultUserPlacement, $userAttributes, $isUtf8Encoding);
                 if (is_object($existingUser)) {
                     eZUser::setCurrentlyLoggedInUser($existingUser, $existingUser->attribute('contentobject_id'));
                 } else {
                     eZUser::setCurrentlyLoggedInUser($oldUser, $oldUser->attribute('contentobject_id'));
                 }
                 ldap_close($ds);
                 return $existingUser;
             } else {
                 eZDebug::writeError('Cannot initialize connection for LDAP server', __METHOD__);
                 $user = false;
                 return $user;
             }
         } else {
             // Increase number of failed login attempts.
             if (isset($userID)) {
                 eZUser::setFailedLoginAttempts($userID);
             }
             eZDebug::writeWarning('User does not exist or LDAP is not enabled in php', __METHOD__);
             $user = false;
             return $user;
         }
     }
 }
コード例 #27
0
/**
 * File containing the updatechildren CLI script
 *
 * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
 * @license http://ez.no/licenses/gnu_gpl GNU GPLv2
 * @package ezmbpaex
 */
$mbpaexIni = eZINI::instance('mbpaex.ini');
// Fetch the user to use in the process
$updateChildrenUser = $mbpaexIni->variable('mbpaexSettings', 'UpdateChildrenUser');
// Default to admin if user is not found in the ini
if (!trim($updateChildrenUser)) {
    $updateChildrenUser = '******';
}
$user = eZUser::fetchByName($updateChildrenUser);
eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id'));
if ($user->isLoggedIn()) {
    $cli->output("eZPaEx: Update children process start");
    ini_set('max_execution_time', 0);
    ini_set('memory_limit', '-1');
    eZDebug::addTimingPoint('Fetch update pending list');
    // Get list of paex objects marked to updatechildren
    $pendingList = eZPaEx::fetchUpdateChildrenPendingList();
    $pendingListCount = count($pendingList);
    if (!$pendingListCount) {
        $cli->output("No pending update subtrees found");
    } else {
        $cli->output("Found " . $pendingListCount . " ezpaex objects with pending updatechildren");
        $pendingIdList = array();
        foreach ($pendingList as $pendingObject) {
            $pendingIdList[] = $pendingObject->attribute('contentobject_id');
コード例 #28
0
 function LogInOpenIDUser($identifier = false, $email = false)
 {
     $moduleINI = eZINI::instance('module.ini');
     $attributeID = $moduleINI->variable('ModuleSettings', 'OpenIDAttributeID');
     $nodeID = $moduleINI->variable('ModuleSettings', 'DefaultUserPlacement');
     if ($email) {
         $userByEmail = eZUser::fetchByEmail($email);
         if ($userByEmail and $userByEmail->isEnabled()) {
             $userID = $userByEmail->attribute('contentobject_id');
             eZUser::setCurrentlyLoggedInUser($userByEmail, $userID);
             eZUser::updateLastVisit($userID);
             eZUser::setFailedLoginAttempts($userID, 0);
             return $userByEmail;
         }
     } else {
         $params = array('AttributeFilter' => array(array($attributeID, '=', $identifier)), 'ClassFilterType' => 'include', 'ClassFilterArray' => array('user'), 'Limit' => 1, 'Limitation' => array());
         $userSubTree = eZContentObjectTreeNode::subTreeByNodeID($params, $nodeID);
         if (count($userSubTree) == 1) {
             $userContentObjectID = $userSubTree[0]->attribute('contentobject_id');
             $user = eZUser::fetch($userContentObjectID, true);
             if ($user and $user->isEnabled()) {
                 $userID = $user->attribute('contentobject_id');
                 eZUser::setCurrentlyLoggedInUser($user, $userID);
                 eZUser::updateLastVisit($userID);
                 eZUser::setFailedLoginAttempts($userID, 0);
                 return $user;
             }
         }
     }
     return false;
 }
コード例 #29
0
    /**
     * Regression test for issue #16949
     * 1) Test there is no pending object in sub objects
     * 2) Test there is one pending object in sub objects
     */
    public function testIssue16949()
    {
        //create object
        $top = new ezpObject( 'article', 2 );
        $top->title = 'TOP ARTICLE';
        $top->publish();
        $child = new ezpObject( 'article', $top->mainNode->node_id );
        $child->title = 'THIS IS AN ARTICLE';
        $child->publish();

        $adminUser = eZUser::fetchByName( 'admin' );
        $adminUserID = $adminUser->attribute( 'contentobject_id' );
        $currentUser = eZUser::currentUser();
        $currentUserID = eZUser::currentUserID();
        eZUser::setCurrentlyLoggedInUser( $adminUser, $adminUserID );

        $result = eZContentObjectTreeNode::subtreeRemovalInformation( array( $top->mainNode->node_id ) );
        $this->assertFalse( $result['has_pending_object'] );
        $workflowArticle = new ezpObject( 'article', $top->mainNode->node_id );
        $workflowArticle->title = 'THIS IS AN ARTICLE WITH WORKFLOW';
        $workflowArticle->publish();
        $version = $workflowArticle->currentVersion();
        $version->setAttribute( 'status', eZContentObjectVersion::STATUS_PENDING );
        $version->store();
        $result = eZContentObjectTreeNode::subtreeRemovalInformation( array( $top->mainNode->node_id ) );
        $this->assertTrue( $result['has_pending_object'] );

        eZUser::setCurrentlyLoggedInUser( $currentUser, $currentUserID );
    }
コード例 #30
0
                        if (!in_array($otherNode['parent_node_id'], $noAddAssignmentList)) {
                            $newVersion->assignToNode($otherNode['parent_node_id'], $otherNode['is_main']);
                        }
                    }
                }
                if ($hasLDAPNodeType) {
                    foreach ($newLDAPNodeArray as $newLDAPNode) {
                        if (!in_array($newLDAPNode['parent_node_id'], $noAddAssignmentList)) {
                            $newVersion->assignToNode($newLDAPNode['parent_node_id'], $newLDAPNode['is_main']);
                        }
                        $assignment = eZNodeAssignment::fetch($contentObject->attribute('id'), $newVersionNr, $newLDAPNode['parent_node_id']);
                        $assignment->setAttribute('parent_remote_id', uniqid('LDAP_'));
                        $assignment->store();
                    }
                }
                if (!$hasOtherNodeType and !$hasLDAPNodeType) {
                    if (!in_array($defaultUserPlacement, $noAddAssignmentList)) {
                        $newVersion->assignToNode($defaultUserPlacement, 1);
                    }
                }
                $adminUser = eZUser::fetchByName('admin');
                $adminUserContentObjectID = $adminUser->attribute('contentobject_id');
                eZUser::setCurrentlyLoggedInUser($adminUser, $adminUserContentObjectID);
                $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $userID, 'version' => $newVersionNr));
                $cli->output($cli->stylize('emphasize', $existUser->attribute('login')) . " has changed group, updated.");
            }
        }
    }
}
$db->commit();
$cli->output("All LDAP users have been updated!");