Пример #1
0
 function validateClassAttributeHTTPInput($http, $base, $classAttribute)
 {
     //checking if the recaptcha key is set up if recaptcha is enabled
     $ini = eZINI::instance('ezcomments.ini');
     $fields = $ini->variable('FormSettings', 'AvailableFields');
     if (in_array('recaptcha', $fields)) {
         $publicKey = $ini->variable('RecaptchaSetting', 'PublicKey');
         $privateKey = $ini->variable('RecaptchaSetting', 'PrivateKey');
         if ($publicKey === '' || $privateKey === '') {
             eZDebug::writeNotice('reCAPTCHA key is not set up. For help please visit http://projects.ez.no/ezcomments', __METHOD__);
         }
     }
     if ($http->hasPostVariable('StoreButton') || $http->hasPostVariable('ApplyButton')) {
         // find the class and count how many Comments dattype
         $cond = array('contentclass_id' => $classAttribute->attribute('contentclass_id'), 'version' => eZContentClass::VERSION_STATUS_TEMPORARY, 'data_type_string' => $classAttribute->attribute('data_type_string'));
         $classAttributeList = eZContentClassAttribute::fetchFilteredList($cond);
         // if there is more than 1 comment attribute, return it as INVALID
         if (!is_null($classAttributeList) && count($classAttributeList) > 1) {
             if ($classAttributeList[0]->attribute('id') == $classAttribute->attribute('id')) {
                 eZDebug::writeNotice('There are more than 1 comment attribute in the class.', __METHOD__);
                 return eZInputValidator::STATE_INVALID;
             }
         }
     }
     return eZInputValidator::STATE_ACCEPTED;
 }
Пример #2
0
function updateAutoload($tpl = null)
{
    $autoloadGenerator = new eZAutoloadGenerator();
    try {
        $autoloadGenerator->buildAutoloadArrays();
        $messages = $autoloadGenerator->getMessages();
        foreach ($messages as $message) {
            eZDebug::writeNotice($message, 'eZAutoloadGenerator');
        }
        $warnings = $autoloadGenerator->getWarnings();
        foreach ($warnings as &$warning) {
            eZDebug::writeWarning($warning, "eZAutoloadGenerator");
            // For web output we want to mark some of the important parts of
            // the message
            $pattern = '@^Class\\s+(\\w+)\\s+.* file\\s(.+\\.php).*\\n(.+\\.php)\\s@';
            preg_match($pattern, $warning, $m);
            $warning = str_replace($m[1], '<strong>' . $m[1] . '</strong>', $warning);
            $warning = str_replace($m[2], '<em>' . $m[2] . '</em>', $warning);
            $warning = str_replace($m[3], '<em>' . $m[3] . '</em>', $warning);
        }
        if ($tpl !== null) {
            $tpl->setVariable('warning_messages', $warnings);
        }
    } catch (Exception $e) {
        eZDebug::writeError($e->getMessage());
    }
}
 function execute($process, $event)
 {
     $parameters = $process->attribute('parameter_list');
     $http = eZHTTPTool::instance();
     eZDebug::writeNotice($parameters, "parameters");
     $orderID = $parameters['order_id'];
     $order = eZOrder::fetch($orderID);
     if (empty($orderID) || get_class($order) != 'ezorder') {
         eZDebug::writeWarning("Can't proceed without a Order ID.", "SimpleStockCheck");
         return eZWorkflowEventType::STATUS_FETCH_TEMPLATE_REPEAT;
     }
     // Decrement the quantitity field
     $order = eZOrder::fetch($orderID);
     $productCollection = $order->productCollection();
     $ordereditems = $productCollection->itemList();
     foreach ($ordereditems as $item) {
         $contentObject = $item->contentObject();
         $contentObjectVersion = $contentObject->version($contentObject->attribute('current_version'));
         $contentObjectAttributes = $contentObjectVersion->contentObjectAttributes();
         foreach (array_keys($contentObjectAttributes) as $key) {
             $contentObjectAttribute = $contentObjectAttributes[$key];
             $contentClassAttribute = $contentObjectAttribute->contentClassAttribute();
             // Each attribute has an attribute identifier called 'quantity' that identifies it.
             if ($contentClassAttribute->attribute("identifier") == "quantity") {
                 $contentObjectAttribute->setAttribute("data_int", $contentObjectAttribute->attribute("value") - $item->ItemCount);
                 $contentObjectAttribute->store();
             }
         }
     }
     return eZWorkflowEventType::STATUS_ACCEPTED;
 }
Пример #4
0
function getXMLString($name = false, $data, $ret = false, $debug = false)
{
    // given string $data, will return the text string content of the $name attribute content of a given valid xml document.
    if ($debug) {
        ezDebug::writeNotice($name, 'getXMLString:name');
    }
    // get information out of eZXML
    $xml = new eZXML();
    $xmlDoc = $data;
    if ($debug) {
        ezDebug::writeNotice($data, 'getXMLString:data');
    }
    // continue only with content
    if ($xmlDoc != null and $name != null) {
        $dom = $xml->domTree($xmlDoc);
        $element = $dom->elementsByName("{$name}");
        if (is_object($element[0])) {
            $string = $element[0]->textContent();
            $ret = $string;
        } else {
            eZDebug::writeNotice('Key "' . $name . '" does not exist.', 'wrap_operator');
        }
    }
    if ($debug) {
        ezDebug::writeNotice($ret, 'getXMLString:ret');
    }
    return $ret;
}
Пример #5
0
 function setDiffEngineType($diffEngineType)
 {
     if (isset($diffEngineType)) {
         $this->DiffEngine = $diffEngineType;
         eZDebug::writeNotice("Changing diff engine to type: " . $diffEngineType, 'eZDiff');
     }
 }
Пример #6
0
    static function createClass( $tpl,
                                 $module,
                                 $stepArray,
                                 $basePath,
                                 $storageName = false,
                                 $metaData = false )
    {
        if ( !$storageName )
        {
            $storageName = 'eZWizard';
        }

        if ( !$metaData )
        {
            $http = eZHTTPTool::instance();
            $metaData = $http->sessionVariable( $storageName . '_meta' );
        }

        if ( !isset( $metaData['current_step'] ) ||
             $metaData['current_step'] < 0 )
        {
            $metaData['current_step'] = 0;
            eZDebug::writeNotice( 'Setting wizard step to : ' . $metaData['current_step'], __METHOD__ );
        }
        $currentStep = $metaData['current_step'];

        if ( count( $stepArray ) <= $currentStep )
        {
            eZDebug::writeError( 'Invalid wizard step count: ' . $currentStep, __METHOD__ );
            return false;
        }

        $filePath = $basePath . $stepArray[$currentStep]['file'];
        if ( !file_exists( $filePath ) )
        {
            eZDebug::writeError( 'Wizard file not found : ' . $filePath, __METHOD__ );
            return false;
        }

        include_once( $filePath );

        $className = $stepArray[$currentStep]['class'];
        eZDebug::writeNotice( 'Creating class : ' . $className, __METHOD__ );
        $returnClass =  new $className( $tpl, $module, $storageName );

        if ( isset( $stepArray[$currentStep]['operation'] ) )
        {
            $operation = $stepArray[$currentStep]['operation'];
            return $returnClass->$operation();
            eZDebug::writeNotice( 'Running : "' . $className . '->' . $operation . '()". Specified in StepArray', __METHOD__ );
        }

        if ( isset( $metaData['current_stage'] ) )
        {
            $returnClass->setMetaData( 'current_stage', $metaData['current_stage'] );
            eZDebug::writeNotice( 'Setting wizard stage to : ' . $metaData['current_stage'], __METHOD__ );
        }

        return $returnClass;
    }
Пример #7
0
 /**
  * Determine object's product category.
  *
  * \private
  * \static
  */
 function getProductCategory($object)
 {
     $ini = eZINI::instance('shop.ini');
     if (!$ini->hasVariable('VATSettings', 'ProductCategoryAttribute')) {
         eZDebug::writeError("Cannot find product category: please specify its attribute identifier " . "in the following setting: shop.ini.[VATSettings].ProductCategoryAttribute");
         return null;
     }
     $categoryAttributeName = $ini->variable('VATSettings', 'ProductCategoryAttribute');
     if (!$categoryAttributeName) {
         eZDebug::writeError("Cannot find product category: empty attribute name specified " . "in the following setting: shop.ini.[VATSettings].ProductCategoryAttribute");
         return null;
     }
     $productDataMap = $object->attribute('data_map');
     if (!isset($productDataMap[$categoryAttributeName])) {
         eZDebug::writeError("Cannot find product category: there is no attribute '{$categoryAttributeName}' in object '" . $object->attribute('name') . "' of class '" . $object->attribute('class_name') . "'.");
         return null;
     }
     $categoryAttribute = $productDataMap[$categoryAttributeName];
     $productCategory = $categoryAttribute->attribute('content');
     if ($productCategory === null) {
         eZDebug::writeNotice("Product category is not specified in object '" . $object->attribute('name') . "' of class '" . $object->attribute('class_name') . "'.");
         return null;
     }
     return $productCategory;
 }
 public function generateMarkup()
 {
     $ttlInfos = $this->parseTTL();
     $markup = '<esi:include src="' . $this->Src . '" ttl="' . $ttlInfos['ttl_value'] . $ttlInfos['ttl_unit'] . '" onerror="continue"/>';
     eZDebug::writeNotice($markup, __METHOD__);
     return $markup;
 }
 public function attribute($key)
 {
     if ($this->hasAttribute($key)) {
         switch ($key) {
             case 'object':
                 return $this->getObject();
                 break;
             case 'node':
                 return $this->getNode();
                 break;
             default:
                 return $this->data[$key];
         }
     }
     eZDebug::writeNotice("Attribute {$key} does not exist");
 }
 private function mkDir($path)
 {
     $dirList = explode("/", $path);
     $path = "";
     foreach ($dirList as $dir) {
         $path .= "/" . $dir;
         if (!@ftp_chdir($this->ConnectionResource, $path)) {
             @ftp_chdir($this->ConnectionResource, "/");
             if (!@ftp_mkdir($this->ConnectionResource, $path)) {
                 return false;
             }
             eZDebug::writeNotice('Creating ' . $path, __METHOD__);
         }
     }
     // returning to root folder : lots of moves but cleaner
     ftp_chdir($this->ConnectionResource, "/");
     return true;
 }
 public static function clearCache()
 {
     eZDebug::writeNotice("Clear calendar taxonomy cache", __METHOD__);
     $ini = eZINI::instance();
     if ($ini->hasVariable('SiteAccessSettings', 'RelatedSiteAccessList') && ($relatedSiteAccessList = $ini->variable('SiteAccessSettings', 'RelatedSiteAccessList'))) {
         if (!is_array($relatedSiteAccessList)) {
             $relatedSiteAccessList = array($relatedSiteAccessList);
         }
         $relatedSiteAccessList[] = $GLOBALS['eZCurrentAccess']['name'];
         $siteAccesses = array_unique($relatedSiteAccessList);
     } else {
         $siteAccesses = $ini->variable('SiteAccessSettings', 'AvailableSiteAccessList');
     }
     $cacheBaseDir = eZDir::path(array(eZSys::cacheDirectory(), self::cacheDirectory()));
     $fileHandler = eZClusterFileHandler::instance();
     $fileHandler->fileDeleteByDirList($siteAccesses, $cacheBaseDir, '');
     $fileHandler = eZClusterFileHandler::instance($cacheBaseDir);
     $fileHandler->purge();
 }
    /**
     * @param EntityEnclosingRequest|EntityEnclosingRequest[]
     * @return array|\Guzzle\Http\Message\Response
     * @throws \Exception
     * @throws \Guzzle\Common\Exception\ExceptionCollection
     * @throws mixed
     */
    public function send($requests)
    {
        if ( is_array($requests) && count($requests) > 1 )
        {
            \eZDebug::writeError( 'Should not receive multiple guzzle requests', __CLASS__.'::'.__METHOD__ );
            return parent::send($requests);
        }

        /* @var $request EntityEnclosingRequest */
        $request = is_array($requests) ? $requests[0] : $requests;

        if ( $request->getMethod() !== 'POST' )
        {
            \eZDebug::writeNotice( 'Not POST method used ('.$request->getMethod().'). Falling back to default Guzzle behaviour' );
            return parent::send($requests);
        }

        return GuzzleCurlHelper::sendRequest( $request );

    }
Пример #13
0
 /**
  * Logs the string $logString to the logfile webservices.log
  * in the current log directory (usually var/log).
  * If logging is disabled, nothing is done.
  *
  * In dev mode, also writes to the eZP logs to ease debugging (this happens
  * regardless of the logging level set for the extension itself)
  */
 static function appendLogEntry($logString, $debuglevel)
 {
     $ini = eZINI::instance('site.ini');
     if ($ini->variable('DebugSettings', 'DebugOutput') == 'enabled' && $ini->variable('TemplateSettings', 'DevelopmentMode') == 'enabled') {
         switch ($debuglevel) {
             case 'info':
             case 'notice':
                 eZDebug::writeNotice($logString, 'ggwebservices');
                 break;
             case 'debug':
                 eZDebug::writeDebug($logString, 'ggwebservices');
                 break;
             case 'warning':
                 eZDebug::writeWarning($logString, 'ggwebservices');
                 break;
             case 'error':
             case 'critical':
                 eZDebug::writeError($logString, 'ggwebservices');
                 break;
         }
     }
     if (!self::isLoggingEnabled($debuglevel)) {
         return false;
     }
     $varDir = eZSys::varDirectory();
     $logDir = 'log';
     $logName = 'webservices.log';
     $fileName = $varDir . '/' . $logDir . '/' . $logName;
     if (!file_exists($varDir . '/' . $logDir)) {
         //include_once( 'lib/ezfile/classes/ezdir.php' );
         eZDir::mkdir($varDir . '/' . $logDir, 0775, true);
     }
     if ($logFile = fopen($fileName, 'a')) {
         $nowTime = date("Y-m-d H:i:s : ");
         $text = $nowTime . $logString;
         /*if ( $label )
           $text .= ' [' . $label . ']';*/
         fwrite($logFile, $text . "\n");
         fclose($logFile);
     }
 }
 protected static function gmapStaticImageGetData($args)
 {
     extract($args);
     $markers = array();
     $query = array();
     foreach ($parameters as $key => $value) {
         if (is_array($value)) {
             foreach ($value as $markerProperties) {
                 $latLngArray = array();
                 $markerQuery = array();
                 $markerPositions = array();
                 foreach ($markerProperties as $markerPropertyKey => $markerPropertyValue) {
                     if ($markerPropertyKey == '_positions') {
                         foreach ($markerPropertyValue as $position) {
                             if ($position['lat'] > 0 && $position['lng'] > 0) {
                                 $markerPositions[] = "{$position['lat']},{$position['lng']}";
                             }
                         }
                     } else {
                         $markerQuery[] = "{$markerPropertyKey}:{$markerPropertyValue}";
                     }
                 }
                 if (empty($markerPositions)) {
                     throw new Exception("Positions not found in parameters " . var_export($parameters, 1));
                 } else {
                     //markers=color:blue|46.067618,11.117315
                     $query[] = "markers=" . implode('|', $markerQuery) . '|' . implode('|', $markerPositions);
                 }
             }
         } else {
             //zoom=13 size=600x300 maptype=roadmap
             $query[] = "{$key}={$value}";
         }
     }
     $stringQuery = implode('&', $query);
     $baseUrl = 'http://maps.googleapis.com/maps/api/staticmap';
     $url = "{$baseUrl}?{$stringQuery}";
     $data = eZHTTPTool::getDataByURL($url);
     eZDebug::writeNotice("Generate static map for attribute {$attribute->attribute('id')}: {$url}", __METHOD__);
     return 'data:image/PNG;base64,' . base64_encode($data);
 }
Пример #15
0
 function parseText($text)
 {
     $returnArray = array();
     $pos = 0;
     while ($pos < strlen($text)) {
         // find the next tag
         $tagStart = strpos($text, "<", $pos);
         if ($tagStart !== false) {
             if ($tagStart - $pos >= 1) {
                 $textChunk = substr($text, $pos, $tagStart - $pos);
                 $pos += $tagStart - $pos;
                 if (strlen(trim($textChunk)) != 0) {
                     $returnArray[] = array("Type" => eZTextInputParser::CHUNK_TEXT, "Text" => $textChunk, "TagName" => "#text");
                     eZDebug::writeNotice($textChunk, "New text chunk in input");
                 }
             }
             // get the tag
             $tagEnd = strpos($text, ">", $pos);
             $tagChunk = substr($text, $pos, $tagEnd - $pos + 1);
             $tagName = preg_replace("#^\\<(.+)?(\\s.*|\\>)#m", "\\1", $tagChunk);
             // check for end tag
             if ($tagName[0] == "/") {
                 print "endtag";
             }
             $returnArray[] = array("Type" => eZTextInputParser::CHUNK_TAG, "TagName" => $tagName, "Text" => $tagChunk);
             $pos += $tagEnd - $pos;
             eZDebug::writeNotice($tagChunk, "New tag chunk in input");
         } else {
             // just plain text in the rest
             $textChunk = substr($text, $pos, strlen($text));
             eZDebug::writeNotice($textChunk, "New text chunk in input");
             if (strlen(trim($textChunk)) != 0) {
                 $returnArray[] = array("Type" => eZTextInputParser::CHUNK_TEXT, "Text" => $textChunk, "TagName" => "#text");
             }
             $pos = strlen($text);
         }
         $pos++;
     }
     return $returnArray;
 }
 public function execute($process, $event)
 {
     //echo('*** workflow importcomunicati ***<pre>');
     $parameters = $process->attribute('parameter_list');
     try {
         $object = eZContentObject::fetch($parameters['object_id']);
         // if a newer object is the current version, abort this workflow.
         $currentVersion = $object->attribute('current_version');
         $version = $object->version($parameters['version']);
         $classIdentifier = $version->ContentObject->ClassIdentifier;
         // Verifica se la classe è corretta
         if ($classIdentifier == self::PUBLISH_CLASS) {
             $objectAttributes = $version->attribute('contentobject_attributes');
             // cicla sugl iattributi
             foreach ($objectAttributes as $objectAttribute) {
                 $contentClassAttributeIdentifier = $objectAttribute->ContentClassAttributeIdentifier;
                 if ($contentClassAttributeIdentifier == 'published') {
                     // recupera la data di pubblicazione
                     $publisheddate = $objectAttribute->attribute('content');
                 }
             }
             // set della data di pubblicazione
             if ($publisheddate instanceof eZDateTime || $publisheddate instanceof eZDate) {
                 $object->setAttribute('published', $publisheddate->timeStamp());
                 $object->store();
                 eZContentOperationCollection::registerSearchObject($object->attribute('id'));
                 eZDebug::writeNotice('Workflow change object publish date', __METHOD__);
             }
             //echo('<br>*** die workflow ***');
             //die();
         }
         return eZWorkflowType::STATUS_ACCEPTED;
     } catch (Exception $e) {
         eZDebug::writeError($e->getMessage(), __METHOD__);
         return eZWorkflowType::STATUS_REJECTED;
     }
 }
 /**
  * Pushes the configuration XML to Solr through a custom requestHandler ( HTTP/ReST ).
  * The requestHandler ( Solr extension ) will take care of reloading the configuration.
  *
  * @see $configurationXML
  * @return void
  */
 protected static function pushConfigurationToSolr($shard = null)
 {
     $params = array('qt' => 'ezfind', self::CONF_PARAM_NAME => self::getConfiguration());
     // Keep previous behaviour, but should not be needed
     if ($shard === null) {
         $shard = new eZSolrBase();
     }
     $result = $shard->pushElevateConfiguration($params);
     if (!$result) {
         $message = ezpI18n::tr('extension/ezfind/elevate', 'An unknown error occured in updating Solr\'s elevate configuration.');
         eZDebug::writeError($message, __METHOD__);
         throw new Exception($message);
     } elseif (isset($result['error'])) {
         eZDebug::writeError($result['error'], __METHOD__);
         throw new Exception($result['error']);
     } else {
         eZDebug::writeNotice("Successful update of Solr's configuration.", __METHOD__);
     }
 }
Пример #18
0
 function install($package, $installType, $parameters, $name, $os, $filename, $subdirectory, $content, &$installParameters, &$installData)
 {
     $serializedNameListNode = $content->getElementsByTagName('serialized-name-list')->item(0);
     $serializedNameList = $serializedNameListNode ? $serializedNameListNode->textContent : false;
     $classNameList = new eZContentClassNameList($serializedNameList);
     if ($classNameList->isEmpty()) {
         $classNameList->initFromString($content->getElementsByTagName('name')->item(0)->textContent);
         // for backward compatibility( <= 3.8 )
     }
     $classNameList->validate();
     $serializedDescriptionListNode = $content->getElementsByTagName('serialized-description-list')->item(0);
     $serializedDescriptionList = $serializedDescriptionListNode ? $serializedDescriptionListNode->textContent : false;
     $classDescriptionList = new eZSerializedObjectNameList($serializedDescriptionList);
     $classIdentifier = $content->getElementsByTagName('identifier')->item(0)->textContent;
     $classRemoteID = $content->getElementsByTagName('remote-id')->item(0)->textContent;
     $classObjectNamePattern = $content->getElementsByTagName('object-name-pattern')->item(0)->textContent;
     $classURLAliasPattern = is_object($content->getElementsByTagName('url-alias-pattern')->item(0)) ? $content->getElementsByTagName('url-alias-pattern')->item(0)->textContent : null;
     $classIsContainer = $content->getAttribute('is-container');
     if ($classIsContainer !== false) {
         $classIsContainer = $classIsContainer == 'true' ? 1 : 0;
     }
     $classRemoteNode = $content->getElementsByTagName('remote')->item(0);
     $classID = $classRemoteNode->getElementsByTagName('id')->item(0)->textContent;
     $classGroupsNode = $classRemoteNode->getElementsByTagName('groups')->item(0);
     $classCreated = $classRemoteNode->getElementsByTagName('created')->item(0)->textContent;
     $classModified = $classRemoteNode->getElementsByTagName('modified')->item(0)->textContent;
     $classCreatorNode = $classRemoteNode->getElementsByTagName('creator')->item(0);
     $classModifierNode = $classRemoteNode->getElementsByTagName('modifier')->item(0);
     $classAttributesNode = $content->getElementsByTagName('attributes')->item(0);
     $dateTime = time();
     $classCreated = $dateTime;
     $classModified = $dateTime;
     $userID = false;
     if (isset($installParameters['user_id'])) {
         $userID = $installParameters['user_id'];
     }
     $class = eZContentClass::fetchByRemoteID($classRemoteID);
     if ($class) {
         $className = $class->name();
         $description = ezpI18n::tr('kernel/package', "Class '%classname' already exists.", false, array('%classname' => $className));
         $choosenAction = $this->errorChoosenAction(self::ERROR_EXISTS, $installParameters, $description, $this->HandlerType);
         switch ($choosenAction) {
             case eZPackage::NON_INTERACTIVE:
             case self::ACTION_REPLACE:
                 if (eZContentClassOperations::remove($class->attribute('id')) == false) {
                     eZDebug::writeWarning("Unable to remove class '{$className}'.");
                     return true;
                 }
                 eZDebug::writeNotice("Class '{$className}' will be replaced.", 'eZContentClassPackageHandler');
                 break;
             case self::ACTION_SKIP:
                 return true;
             case self::ACTION_NEW:
                 $class->setAttribute('remote_id', eZRemoteIdUtility::generate('class'));
                 $class->store();
                 $classNameList->appendGroupName(" (imported)");
                 break;
             default:
                 $installParameters['error'] = array('error_code' => self::ERROR_EXISTS, 'element_id' => $classRemoteID, 'description' => $description, 'actions' => array());
                 if ($class->isRemovable()) {
                     $errorMsg = ezpI18n::tr('kernel/package', "Replace existing class");
                     $objectsCount = eZContentObject::fetchSameClassListCount($class->attribute('id'));
                     if ($objectsCount) {
                         $errorMsg .= ' ' . ezpI18n::tr('kernel/package', "(Warning! {$objectsCount} content object(s) and their sub-items will be removed)");
                     }
                     $installParameters['error']['actions'][self::ACTION_REPLACE] = $errorMsg;
                 }
                 $installParameters['error']['actions'][self::ACTION_SKIP] = ezpI18n::tr('kernel/package', 'Skip installing this class');
                 $installParameters['error']['actions'][self::ACTION_NEW] = ezpI18n::tr('kernel/package', 'Keep existing and create a new one');
                 return false;
         }
     }
     unset($class);
     // Try to create a unique class identifier
     $currentClassIdentifier = $classIdentifier;
     $unique = false;
     while (!$unique) {
         $classList = eZContentClass::fetchByIdentifier($currentClassIdentifier);
         if ($classList) {
             // "increment" class identifier
             if (preg_match('/^(.*)_(\\d+)$/', $currentClassIdentifier, $matches)) {
                 $currentClassIdentifier = $matches[1] . '_' . ($matches[2] + 1);
             } else {
                 $currentClassIdentifier = $currentClassIdentifier . '_1';
             }
         } else {
             $unique = true;
         }
         unset($classList);
     }
     $classIdentifier = $currentClassIdentifier;
     $values = array('version' => 0, 'serialized_name_list' => $classNameList->serializeNames(), 'serialized_description_list' => $classDescriptionList->serializeNames(), 'create_lang_if_not_exist' => true, 'identifier' => $classIdentifier, 'remote_id' => $classRemoteID, 'contentobject_name' => $classObjectNamePattern, 'url_alias_name' => $classURLAliasPattern, 'is_container' => $classIsContainer, 'created' => $classCreated, 'modified' => $classModified);
     if ($content->hasAttribute('sort-field')) {
         $values['sort_field'] = eZContentObjectTreeNode::sortFieldID($content->getAttribute('sort-field'));
     } else {
         eZDebug::writeNotice('The sort field was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     if ($content->hasAttribute('sort-order')) {
         $values['sort_order'] = $content->getAttribute('sort-order');
     } else {
         eZDebug::writeNotice('The sort order was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     if ($content->hasAttribute('always-available')) {
         $values['always_available'] = $content->getAttribute('always-available') === 'true' ? 1 : 0;
     } else {
         eZDebug::writeNotice('The default object availability was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     // create class
     $class = eZContentClass::create($userID, $values);
     $class->store();
     $classID = $class->attribute('id');
     if (!isset($installData['classid_list'])) {
         $installData['classid_list'] = array();
     }
     if (!isset($installData['classid_map'])) {
         $installData['classid_map'] = array();
     }
     $installData['classid_list'][] = $class->attribute('id');
     $installData['classid_map'][$classID] = $class->attribute('id');
     // create class attributes
     $classAttributeList = $classAttributesNode->getElementsByTagName('attribute');
     foreach ($classAttributeList as $classAttributeNode) {
         $isNotSupported = strtolower($classAttributeNode->getAttribute('unsupported')) == 'true';
         if ($isNotSupported) {
             continue;
         }
         $attributeDatatype = $classAttributeNode->getAttribute('datatype');
         $attributeIsRequired = strtolower($classAttributeNode->getAttribute('required')) == 'true';
         $attributeIsSearchable = strtolower($classAttributeNode->getAttribute('searchable')) == 'true';
         $attributeIsInformationCollector = strtolower($classAttributeNode->getAttribute('information-collector')) == 'true';
         $attributeIsTranslatable = strtolower($classAttributeNode->getAttribute('translatable')) == 'true';
         $attributeSerializedNameListNode = $classAttributeNode->getElementsByTagName('serialized-name-list')->item(0);
         $attributeSerializedNameListContent = $attributeSerializedNameListNode ? $attributeSerializedNameListNode->textContent : false;
         $attributeSerializedNameList = new eZSerializedObjectNameList($attributeSerializedNameListContent);
         if ($attributeSerializedNameList->isEmpty()) {
             $attributeSerializedNameList->initFromString($classAttributeNode->getElementsByTagName('name')->item(0)->textContent);
         }
         // for backward compatibility( <= 3.8 )
         $attributeSerializedNameList->validate();
         $attributeSerializedDescriptionListNode = $classAttributeNode->getElementsByTagName('serialized-description-list')->item(0);
         $attributeSerializedDescriptionListContent = $attributeSerializedDescriptionListNode ? $attributeSerializedDescriptionListNode->textContent : false;
         $attributeSerializedDescriptionList = new eZSerializedObjectNameList($attributeSerializedDescriptionListContent);
         $attributeCategoryNode = $classAttributeNode->getElementsByTagName('category')->item(0);
         $attributeCategory = $attributeCategoryNode ? $attributeCategoryNode->textContent : '';
         $attributeSerializedDataTextNode = $classAttributeNode->getElementsByTagName('serialized-description-text')->item(0);
         $attributeSerializedDataTextContent = $attributeSerializedDataTextNode ? $attributeSerializedDataTextNode->textContent : false;
         $attributeSerializedDataText = new eZSerializedObjectNameList($attributeSerializedDataTextContent);
         $attributeIdentifier = $classAttributeNode->getElementsByTagName('identifier')->item(0)->textContent;
         $attributePlacement = $classAttributeNode->getElementsByTagName('placement')->item(0)->textContent;
         $attributeDatatypeParameterNode = $classAttributeNode->getElementsByTagName('datatype-parameters')->item(0);
         $classAttribute = $class->fetchAttributeByIdentifier($attributeIdentifier);
         if (!$classAttribute) {
             $classAttribute = eZContentClassAttribute::create($class->attribute('id'), $attributeDatatype, array('version' => 0, 'identifier' => $attributeIdentifier, 'serialized_name_list' => $attributeSerializedNameList->serializeNames(), 'serialized_description_list' => $attributeSerializedDescriptionList->serializeNames(), 'category' => $attributeCategory, 'serialized_data_text' => $attributeSerializedDataText->serializeNames(), 'is_required' => $attributeIsRequired, 'is_searchable' => $attributeIsSearchable, 'is_information_collector' => $attributeIsInformationCollector, 'can_translate' => $attributeIsTranslatable, 'placement' => $attributePlacement));
             $dataType = $classAttribute->dataType();
             $classAttribute->store();
             $dataType->unserializeContentClassAttribute($classAttribute, $classAttributeNode, $attributeDatatypeParameterNode);
             $classAttribute->sync();
         }
     }
     // add class to a class group
     $classGroupsList = $classGroupsNode->getElementsByTagName('group');
     foreach ($classGroupsList as $classGroupNode) {
         $classGroupName = $classGroupNode->getAttribute('name');
         $classGroup = eZContentClassGroup::fetchByName($classGroupName);
         if (!$classGroup) {
             $classGroup = eZContentClassGroup::create();
             $classGroup->setAttribute('name', $classGroupName);
             $classGroup->store();
         }
         $classGroup->appendClass($class);
     }
     return true;
 }
Пример #19
0
 /**
  * Build facet parameter list. This function extracts the facet parameter from
  * the ezfeZPSolrQueryBuilder::search( ...,$params parameter.
  *
  * @todo specify dedicated facet fields (may be mapped to sort fields)
  *
  * @param array Parameter list array
  *
  * @return array List of Facet query parameter. The facet parameter corrosponds to
  * the parameters defined here : http://wiki.apache.org/solr/SimpleFacetParameters
  */
 protected function buildFacetQueryParamList($parameterList)
 {
     $parameterList = array_change_key_case($parameterList, CASE_LOWER);
     $queryParamList = array();
     if (empty($parameterList['facet'])) {
         return $queryParamList;
     }
     // Loop through facet definitions, and build facet query.
     foreach ($parameterList['facet'] as $facetDefinition) {
         if (empty($facetDefinition['field']) and empty($facetDefinition['query']) and empty($facetDefinition['date']) and empty($facetDefinition['range']) and empty($facetDefinition['prefix'])) {
             eZDebug::writeDebug('No facet field or query provided.', __METHOD__);
             continue;
         }
         $queryPart = array();
         if (!empty($facetDefinition['field'])) {
             switch ($facetDefinition['field']) {
                 case 'author':
                     $queryPart['field'] = eZSolr::getMetaFieldName('owner_id', 'facet');
                     break;
                 case 'class':
                     $queryPart['field'] = eZSolr::getMetaFieldName('contentclass_id', 'facet');
                     break;
                 case 'installation':
                     $queryPart['field'] = eZSolr::getMetaFieldName('installation_id', 'facet');
                     break;
                 case 'translation':
                     $queryPart['field'] = eZSolr::getMetaFieldName('language_code', 'facet');
                     break;
                 default:
                     $fieldName = eZSolr::getFieldName($facetDefinition['field'], false, 'facet');
                     if (!$fieldName and empty($facetDefinition['date'])) {
                         eZDebug::writeNotice('Facet field does not exist in local installation, but may still be valid: ' . $facetDefinition['field'], __METHOD__);
                         continue;
                     }
                     $queryPart['field'] = $fieldName;
                     break;
             }
         }
         // Get query part.
         if (!empty($facetDefinition['query'])) {
             list($field, $query) = explode(':', $facetDefinition['query'], 2);
             $field = eZSolr::getFieldName($field, false, 'facet');
             if (!$field) {
                 eZDebug::writeNotice('Invalid query field provided: ' . $facetDefinition['query'], __METHOD__);
                 continue;
             }
             $queryPart['query'] = $field . ':' . $query;
         }
         // Get prefix.
         // TODO: make this per mandatory per field in order to construct f.<fieldname>.facet.prefix queries
         if (!empty($facetDefinition['prefix'])) {
             $queryPart['prefix'] = $facetDefinition['prefix'];
         }
         // range facets: fill the $queryParamList array directly
         if (!empty($facetDefinition['range']) && !empty($facetDefinition['range']['field']) && !empty($facetDefinition['range']['start']) && !empty($facetDefinition['range']['end']) && !empty($facetDefinition['range']['gap'])) {
             $fieldName = '';
             switch ($facetDefinition['range']['field']) {
                 case 'published':
                     $fieldName = eZSolr::getMetaFieldName('published', 'facet');
                     break;
                 case 'modified':
                     $fieldName = eZSolr::getMetaFieldName('modified', 'facet');
                     break;
                 default:
                     $fieldName = eZSolr::getFieldName($facetDefinition['field'], false, 'facet');
             }
             $perFieldRangePrefix = 'f.' . $fieldName . '.facet.range';
             $queryParamList['facet.range'] = $fieldName;
             $queryParamList[$perFieldRangePrefix . '.start'] = $facetDefinition['range']['start'];
             $queryParamList[$perFieldRangePrefix . '.end'] = $facetDefinition['range']['end'];
             $queryParamList[$perFieldRangePrefix . '.gap'] = $facetDefinition['range']['gap'];
             if (!empty($facetDefinition['range']['hardend'])) {
                 $queryParamList[$perFieldRangePrefix . '.hardend'] = $facetDefinition['range']['hardend'];
             }
             if (!empty($facetDefinition['range']['include'])) {
                 $queryParamList[$perFieldRangePrefix . '.include'] = $facetDefinition['range']['include'];
             }
             if (!empty($facetDefinition['range']['other'])) {
                 $queryParamList[$perFieldRangePrefix . '.other'] = $facetDefinition['range']['other'];
             }
         }
         // Get sort option.
         if (!empty($facetDefinition['sort'])) {
             switch (strtolower($facetDefinition['sort'])) {
                 case 'count':
                     $queryPart['sort'] = 'true';
                     break;
                 case 'alpha':
                     $queryPart['sort'] = 'false';
                     break;
                 default:
                     eZDebug::writeWarning('Invalid sort option provided: ' . $facetDefinition['sort'], __METHOD__);
                     break;
             }
         }
         // Get limit option
         if (!empty($facetDefinition['limit'])) {
             $queryPart['limit'] = $facetDefinition['limit'];
         } else {
             $queryPart['limit'] = ezfeZPSolrQueryBuilder::FACET_LIMIT;
         }
         // Get offset
         if (isset($facetDefinition['offset'])) {
             $queryPart['offset'] = $facetDefinition['offset'];
         } else {
             $queryPart['offset'] = ezfeZPSolrQueryBuilder::FACET_OFFSET;
         }
         // Get mincount
         if (isset($facetDefinition['mincount'])) {
             $queryPart['mincount'] = $facetDefinition['mincount'];
         } else {
             $queryPart['mincount'] = ezfeZPSolrQueryBuilder::FACET_MINCOUNT;
         }
         // Get missing option.
         if (!empty($facetDefinition['missing'])) {
             $queryPart['missing'] = 'true';
         }
         // Get date start option - may add validation later.
         if (!empty($facetDefinition['date'])) {
             $fieldName = eZSolr::getFieldName($facetDefinition['date'], false, 'facet');
             if (!$fieldName) {
                 eZDebug::writeNotice('Facet field does not exist in local installation, but may still be valid: ' . $facetDefinition['date'], __METHOD__);
                 continue;
             } else {
                 $queryPart['date'] = $fieldName;
             }
         }
         // Get date start option - may add validation later.
         if (!empty($facetDefinition['date.start'])) {
             $queryPart['date.start'] = $facetDefinition['date.start'];
         }
         // Get date end option - may add validation later.
         if (!empty($facetDefinition['date.end'])) {
             $queryPart['date.end'] = $facetDefinition['date.end'];
         }
         // Get date gap option - may add validation later.
         if (!empty($facetDefinition['date.gap'])) {
             $queryPart['date.gap'] = $facetDefinition['date.gap'];
         }
         // Get date hardend option - may add validation later.
         if (!empty($facetDefinition['date.hardend'])) {
             $queryPart['date.hardend'] = $facetDefinition['date.hardend'];
         }
         // Get date hardend option - may add validation later.
         if (!empty($facetDefinition['date.other'])) {
             switch (strtolower($facetDefinition['date.other'])) {
                 case 'before':
                 case 'after':
                 case 'between':
                 case 'none':
                 case 'all':
                     $queryPart['date.other'] = strtolower($facetDefinition['date.other']);
                     break;
                 default:
                     eZDebug::writeWarning('Invalid option gived for date.other: ' . $facetDefinition['date.other'], __METHOD__);
             }
         }
         if (!empty($queryPart)) {
             foreach ($queryPart as $key => $value) {
                 // check for fully prepared parameter names, like the per field options
                 if (strpos($key, 'f.') === 0) {
                     $queryParamList[$key] = $value;
                 } elseif ($key !== 'field' && !empty($queryParamList['facet.' . $key]) && isset($queryPart['field'])) {
                     // local override for one given facet
                     $queryParamList['f.' . $queryPart['field'] . '.facet.' . $key][] = $value;
                 } else {
                     // global value
                     $queryParamList['facet.' . $key][] = $value;
                 }
             }
         }
     }
     if (!empty($queryParamList)) {
         $queryParamList['facet'] = 'true';
     }
     return $queryParamList;
 }
Пример #20
0
     /**
     * isValid
     * Called by handler loading code to see if this is a valid handler.
     *
     * @return bool
     */
    function isValid()
    {
        if ( !$this->currentUserHasAccess() )
        {
            eZDebug::writeNotice('Current user does not have access to ezoe, falling back to normal xml editor!', __METHOD__ );
            return false;
        }

        if ( !self::browserSupportsDHTMLType() )
        {
            if ( $this->currentUserHasAccess( 'disable_editor' ) )
            {
                eZDebug::writeNotice('Current browser is not supported by ezoe, falling back to normal xml editor!', __METHOD__ );
                return false;
            }
            eZDebug::writeWarning('Current browser is not supported by ezoe, but user does not have access to disable editor!', __METHOD__ );
        }

        return true;
    }
Пример #21
0
    /**
     * Returns the correct handler defined in $iniFile configuration file
     * A correct class name for the handler needs to be specified in the
     * ini settings, and the class needs to be present for the autoload system.
     *
     * @static
     * @param object $options, and ezpExtensionOptions object
     * @return null|false|object Returns a valid handler object, null if setting did not exists and false if no handler was found
     */
    public static function getHandlerClass( ezpExtensionOptions $options )
    {
        $iniFile       = $options->iniFile;
        $iniSection    = $options->iniSection;
        $iniVariable   = $options->iniVariable;
        $handlerIndex  = $options->handlerIndex;
        $callMethod    = $options->callMethod;
        $handlerParams = $options->handlerParams;
        $aliasSection  = $options->aliasSection;
        $aliasVariable = $options->aliasVariable;
        $aliasOptionalIndex = $options->aliasOptionalIndex;

        $ini = eZINI::instance( $iniFile );

        if ( !$ini->hasVariable( $iniSection, $iniVariable ) )
        {
            eZDebug::writeError( 'Unable to find variable ' . $iniVariable . ' in section ' . $iniSection . ' in file ' . $iniFile, __METHOD__ );
            return null;
        }

        $handlers = $ini->variable( $iniSection, $iniVariable );

        if ( $handlerIndex !== null )
        {
            if ( is_array( $handlers ) && isset( $handlers[ $handlerIndex  ] ) )
                $handlers = $handlers[ $handlerIndex  ];
            else
                return null;
        }

        // prepend alias settings if defined
        if ( $aliasVariable !== null && is_string( $handlers ) )
        {
            if ( $aliasSection === null )
            {
                $aliasSection = $iniSection;
            }
            $aliasHandlers = $ini->variable( $aliasSection, $aliasVariable );
            if ( $aliasOptionalIndex !== null && isset( $aliasHandlers[ $aliasOptionalIndex ] ) )
            {
                $handlers = array( $aliasHandlers[ $aliasOptionalIndex ], $handlers );
            }
            else if ( isset( $aliasHandlers[ $handlers ] ) )
            {
                $handlers = array( $aliasHandlers[ $handlers ], $handlers );
            }
            else
            {
                $handlers = array( $handlers );
            }
        }
        else if ( !is_array( $handlers ) )
        {
            $handlers = array( $handlers );
        }

        foreach( $handlers as $handler )
        {
            // we rely on the autoload system here
            if ( class_exists( $handler ) )
            {
                // only use reflection if we have params to avoid exception on objects withouth constructor
                if ( $handlerParams !== null && is_array( $handlerParams ) && count( $handlerParams ) > 0 )
                {
                    $reflection = new ReflectionClass( $handler );
                    $object = $reflection->newInstanceArgs( $handlerParams );
                }
                else
                {
                    $object = new $handler();
                }
                // if callMethod is set, then call it so handler can decide if it is a valid handler
                if ( $callMethod !== null )
                {
                    if ( !is_callable( array( $object, $callMethod ) ) )
                    {
                        eZDebug::writeNotice( 'Method ' . $callMethod . ' is not callable on class ' . $handler . " as defined in setting $iniFile [$iniSection] $iniVariable", __METHOD__ );
                        continue;
                    }

                    if ( !call_user_func(array( $object, $callMethod ) ) )
                        continue;
                }
                return $object;
            }
            else
            {
                eZDebug::writeError( "Class '$handler' as defined in setting $iniFile [$iniSection] $iniVariable could not be autoloaded. Did you remember to run bin/php/ezpgenerateautoloads.php after you added extension(s)?", __METHOD__ );
            }
        }

        return false;
    }
Пример #22
0
        }
        $db->commit();
    }
}
$tpl = eZTemplate::factory();
$triggers = eZTrigger::fetchList(array('module' => $moduleName, 'function' => $functionName));
$showModuleList = false;
$showFunctionList = false;
$functionList = array();
$moduleList = array();
if ($moduleName == '*') {
    $showModuleList = true;
    $ini = eZINI::instance('module.ini');
    $moduleList = $ini->variable('ModuleSettings', 'ModuleList');
} elseif ($functionName == '*') {
    $mod = eZModule::exists($moduleName);
    $functionList = array_keys($mod->attribute('available_functions'));
    eZDebug::writeNotice($functionList, "functions");
    $showFunctionList = true;
}
$tpl->setVariable('current_module', $moduleName);
$tpl->setVariable('current_function', $functionName);
$tpl->setVariable('show_functions', $showFunctionList);
$tpl->setVariable('show_modules', $showModuleList);
$tpl->setVariable('possible_triggers', $possibleTriggers);
$tpl->setVariable('modules', $moduleList);
$tpl->setVariable('functions', $functionList);
$tpl->setVariable('triggers', $triggers);
$tpl->setVariable('module', $Module);
$Result['content'] = $tpl->fetch('design:trigger/list.tpl');
$Result['path'] = array(array('text' => ezpI18n::tr('kernel/trigger', 'Trigger'), 'url' => false), array('text' => ezpI18n::tr('kernel/trigger', 'List'), 'url' => false));
Пример #23
0
$userID = $user->id();

if ( $http->hasPostVariable( 'RemoveButton' )  )
{
    if ( $http->hasPostVariable( 'DeleteIDArray' ) )
    {
        $deleteIDArray = $http->postVariable( 'DeleteIDArray' );
        $db = eZDB::instance();
        $db->begin();
        foreach ( $deleteIDArray as $deleteID )
        {
            $version = eZContentObjectVersion::fetch( $deleteID );
            if ( $version instanceof eZContentObjectVersion )
            {
                eZDebug::writeNotice( $deleteID, "deleteID" );
                $version->removeThis();
            }
        }
        $db->commit();
    }
}

if ( $http->hasPostVariable( 'EmptyButton' )  )
{
    $versions = eZContentObjectVersion::fetchForUser( $userID );
    $db = eZDB::instance();
    $db->begin();
    foreach ( $versions as $version )
    {
        $version->removeThis();
Пример #24
0
    /**
     * Report SQL $query to debug system.
     *
     * @param string $fname The function name that started the query, should contain relevant arguments in the text.
     * @param int    $timeTaken Number of seconds the query + related operations took (as float).
     * @param int $numRows Number of affected rows.
     */
    function _report( $query, $fname, $timeTaken, $numRows = false )
    {
        if ( !self::$dbparams['sql_output'] )
            return;

        $rowText = '';
        if ( $numRows !== false )
            $rowText = "$numRows rows, ";
        static $numQueries = 0;
        if ( strlen( $fname ) == 0 )
            $fname = "_query";
        $backgroundClass = ($this->transactionCount > 0  ? "debugtransaction transactionlevel-$this->transactionCount" : "");
        eZDebug::writeNotice( "$query", "cluster::mysql::{$fname}[{$rowText}" . number_format( $timeTaken, 3 ) . " ms] query number per page:" . $numQueries++, $backgroundClass );
    }
 static function getAttributesMapping($oObjectClassIdentifier)
 {
     $oIni = eZINI::instance("metatag.ini");
     if (!$oIni->hasGroup('AttributesMapping')) {
         eZDebug::writeNotice('metatag.ini AttributesMapping is not defined', 'MetatagFunctionCollection::getAttributesMapping');
         return array();
     }
     $nameAttributes = NULL;
     $descriptionAttributes = NULL;
     $keywordsAttributes = NULL;
     $metaAttributes = NULL;
     $namePattern = NULL;
     $descriptionPattern = NULL;
     $keywordsPattern = NULL;
     $sizeLimit = false;
     $disableMapping = array();
     if ($oIni->hasVariable('AttributesMapping', "DisableMapping")) {
         $disableMapping = $oIni->variable('AttributesMapping', "DisableMapping");
     }
     // Checks if mapping has been disabled for this attribute
     if (in_array($oObjectClassIdentifier, $disableMapping)) {
         return array();
     }
     if ($oIni->hasVariable('AttributesMapping', "SpecialMapping") && in_array($oObjectClassIdentifier, $oIni->variable('AttributesMapping', "SpecialMapping"))) {
         // Render the name, pattern is checked before
         if ($oIni->hasVariable($oObjectClassIdentifier, "NamePattern")) {
             $namePattern = $oIni->variable($oObjectClassIdentifier, "NamePattern");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, "Name")) {
             $nameAttributes = $oIni->variable($oObjectClassIdentifier, "Name");
         } else {
             $nameAttributes = $oIni->variable('AttributesMapping', "DefaultName");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, "DescriptionPattern")) {
             $descriptionPattern = $oIni->variable($oObjectClassIdentifier, "DescriptionPattern");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, "Description")) {
             $descriptionAttributes = $oIni->variable($oObjectClassIdentifier, "Description");
         } else {
             $descriptionAttributes = $oIni->variable('AttributesMapping', "DefaultDescription");
         }
         // Render the keywords mapping
         if ($oIni->hasVariable($oObjectClassIdentifier, "KeywordsPattern")) {
             $keywordsPattern = $oIni->variable($oObjectClassIdentifier, "KeywordsPattern");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, "Keywords")) {
             $keywordsAttributes = $oIni->variable($oObjectClassIdentifier, "Keywords");
         } else {
             $keywordsAttributes = $oIni->variable('AttributesMapping', "DefaultKeywords");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, "MetaTagAttributeIdentifier")) {
             $metaAttributes = $oIni->variable($oObjectClassIdentifier, "MetaTagAttributeIdentifier");
         } else {
             $metaAttributes = $oIni->variable('AttributesMapping', "MetatagAttributeIdentifier");
         }
         if ($oIni->hasVariable($oObjectClassIdentifier, 'AttributeSizeLimit')) {
             $sizeLimit = $oIni->variable($oObjectClassIdentifier, 'AttributeSizeLimit');
         } elseif ($oIni->hasVariable('AttributesMapping', 'AttributeSizeLimit')) {
             $sizeLimit = $oIni->variable('AttributesMapping', 'AttributeSizeLimit');
         }
     } else {
         $nameAttributes = $oIni->variable('AttributesMapping', "DefaultName");
         $descriptionAttributes = $oIni->variable('AttributesMapping', "DefaultDescription");
         $keywordsAttributes = $oIni->variable('AttributesMapping', "DefaultKeywords");
         $metaAttributes = $oIni->variable('AttributesMapping', "MetatagAttributeIdentifier");
         if ($oIni->hasVariable('AttributesMapping', 'AttributeSizeLimit')) {
             $sizeLimit = $oIni->variable('AttributesMapping', 'AttributeSizeLimit');
         }
     }
     return array('name' => $nameAttributes, 'description' => $descriptionAttributes, 'keywords' => $keywordsAttributes, 'meta' => $metaAttributes, 'namePattern' => $namePattern, 'descriptionPattern' => $descriptionPattern, 'keywordsPattern' => $keywordsPattern, 'sizeLimit' => $sizeLimit);
 }
 /**
  * Check access to a specific module/function with limitation values.
  * See eZ Publish documentation on more info on module, function and
  * limitation values. Example: a user can have content/read permissions
  * but it can be limited to a specific limitation like a section, a node
  * or node tree. Limitation: returns false if one of provided values
  * don't match but ignores limitations not specified in $limitations.
  *
  * @param string $module
  * @param string $function
  * @param array|null $limitations A hash of limitation keys and values
  * @return bool
  */
 public static function hasAccessToLimitation($module, $function, $limitations = null, $debug = false)
 {
     // Like fetch(user,has_access_to), but with support for limitations
     $user = eZUser::currentUser();
     if (!$user instanceof eZUser) {
         eZDebug::writeDebug('No user instance', __METHOD__);
         return false;
     }
     $result = $user->hasAccessTo($module, $function);
     if ($result['accessWord'] !== 'limited') {
         return $result['accessWord'] === 'yes';
     }
     // Merge limitations before we check access
     $mergedLimitations = array();
     $missingLimitations = array();
     foreach ($result['policies'] as $userLimitationArray) {
         foreach ($userLimitationArray as $userLimitationKey => $userLimitationValues) {
             if (isset($limitations[$userLimitationKey])) {
                 if (isset($mergedLimitations[$userLimitationKey])) {
                     $mergedLimitations[$userLimitationKey] = array_merge($mergedLimitations[$userLimitationKey], $userLimitationValues);
                 } else {
                     $mergedLimitations[$userLimitationKey] = $userLimitationValues;
                 }
             } else {
                 $missingLimitations[] = $userLimitationKey;
             }
         }
     }
     // User has access unless provided limitations don't match
     foreach ($mergedLimitations as $userLimitationKey => $userLimitationValues) {
         // Handle subtree matching specifically as we need to match path string
         if ($userLimitationKey === 'User_Subtree' || $userLimitationKey === 'Subtree') {
             $pathMatch = false;
             foreach ($userLimitationValues as $subtreeString) {
                 if (strstr($limitations[$userLimitationKey], $subtreeString)) {
                     $pathMatch = true;
                     break;
                 }
             }
             if (!$pathMatch) {
                 if ($debug) {
                     eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitations[$userLimitationKey] . ' != ' . $subtreeString, __METHOD__);
                 }
                 return false;
             }
         } else {
             if (is_array($limitations[$userLimitationKey])) {
                 // All provided limitations must exist in $userLimitationValues
                 foreach ($limitations[$userLimitationKey] as $limitationValue) {
                     if (!in_array($limitationValue, $userLimitationValues)) {
                         if ($debug) {
                             eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitationValue . ' != [' . implode(', ', $userLimitationValues) . ']', __METHOD__);
                         }
                         return false;
                     }
                 }
             } else {
                 if (!in_array($limitations[$userLimitationKey], $userLimitationValues)) {
                     if ($debug) {
                         eZDebug::writeDebug("Unmatched[{$module}/{$function}]: " . $userLimitationKey . ' ' . $limitations[$userLimitationKey] . ' != [' . implode(', ', $userLimitationValues) . ']', __METHOD__);
                     }
                     return false;
                 }
             }
         }
     }
     if (!empty($missingLimitations) && $debug) {
         eZDebug::writeNotice("Matched, but missing limitations[{$module}/{$function}]: " . implode(', ', $missingLimitations), __METHOD__);
     }
     return true;
 }
Пример #27
0
 function validateClassAttributeHTTPInput($http, $base, $classAttribute)
 {
     $minValueName = $base . self::MIN_VARIABLE . $classAttribute->attribute("id");
     $maxValueName = $base . self::MAX_VARIABLE . $classAttribute->attribute("id");
     $defaultValueName = $base . self::DEFAULT_VARIABLE . $classAttribute->attribute("id");
     if ($http->hasPostVariable($minValueName) and $http->hasPostVariable($maxValueName) and $http->hasPostVariable($defaultValueName)) {
         $locale = eZLocale::instance();
         $minValueValue = $http->postVariable($minValueName);
         $minValueValue = str_replace(" ", "", $minValueValue);
         $minValueValue = $locale->internalNumber($minValueValue);
         $maxValueValue = $http->postVariable($maxValueName);
         $maxValueValue = str_replace(" ", "", $maxValueValue);
         $maxValueValue = $locale->internalNumber($maxValueValue);
         $defaultValueValue = $http->postVariable($defaultValueName);
         $defaultValueValue = str_replace(" ", "", $defaultValueValue);
         $defaultValueValue = $locale->internalNumber($defaultValueValue);
         if ($minValueValue == "" && $maxValueValue == "") {
             return eZInputValidator::STATE_ACCEPTED;
         } else {
             if ($minValueValue == "" && $maxValueValue !== "") {
                 $max_state = $this->FloatValidator->validate($maxValueValue);
                 return $max_state;
             } else {
                 if ($minValueValue !== "" && $maxValueValue == "") {
                     $min_state = $this->FloatValidator->validate($minValueValue);
                     return $min_state;
                 } else {
                     $min_state = $this->FloatValidator->validate($minValueValue);
                     $max_state = $this->FloatValidator->validate($maxValueValue);
                     if ($min_state == eZInputValidator::STATE_ACCEPTED and $max_state == eZInputValidator::STATE_ACCEPTED) {
                         if ($minValueValue <= $maxValueValue) {
                             return eZInputValidator::STATE_ACCEPTED;
                         } else {
                             $state = eZInputValidator::STATE_INTERMEDIATE;
                             eZDebug::writeNotice("Integer minimum value great than maximum value.");
                             return $state;
                         }
                     }
                 }
             }
         }
         if ($defaultValueValue == "") {
             $default_state = eZInputValidator::STATE_ACCEPTED;
         } else {
             $default_state = $this->FloatValidator->validate($defaultValueValue);
         }
     }
     return eZInputValidator::STATE_INVALID;
 }
Пример #28
0
 function languageFile($withVariation = false)
 {
     $type = $withVariation ? 'variation' : 'default';
     if (!$this->LanguageINI[$type] instanceof eZINI) {
         $language = $this->languageCode();
         $countryVariation = $this->countryVariation();
         $locale = $language;
         if ($withVariation) {
             if ($countryVariation !== '') {
                 $locale .= '@' . $countryVariation;
             }
         }
         $languageFile = 'language/' . $locale . '.ini';
         if (eZLocale::isDebugEnabled()) {
             eZDebug::writeNotice("Requesting {$languageFile}", __METHOD__);
         }
         if (eZINI::exists($languageFile, 'share/locale')) {
             $this->LanguageINI[$type] = eZINI::instance($languageFile, 'share/locale');
         }
     }
     return $this->LanguageINI[$type];
 }
Пример #29
0
 static function errorChoosenAction($errorCode, &$installParameters, $description, $handlerType, $resetError = true)
 {
     if (isset($installParameters['non-interactive']) && $installParameters['non-interactive']) {
         if ($description) {
             eZDebug::writeNotice($description, 'Package installation conflict');
         }
         return eZPackage::NON_INTERACTIVE;
     }
     if (isset($installParameters['error_default_actions'][$handlerType][$errorCode])) {
         if ($resetError && count($installParameters['error'])) {
             $installParameters['error'] = array();
         }
         return $installParameters['error_default_actions'][$handlerType][$errorCode];
     }
     if (isset($installParameters['error']['error_code']) && $installParameters['error']['error_code'] == $errorCode) {
         if (isset($installParameters['error']['choosen_action'])) {
             $choosenAction = $installParameters['error']['choosen_action'];
             if ($resetError) {
                 $installParameters['error'] = array();
             }
             return $choosenAction;
         }
     }
     return false;
 }
Пример #30
0
function checkNodeActions( $module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $fromLanguage )
{
    // If the object has been previously published we do not allow node assignment operations
    if ( $object->attribute( 'status' ) != eZContentObject::STATUS_DRAFT )
    {
        if ( !$module->isCurrentAction( 'BrowseForPrimaryNodes' ) )
        {
            return;
        }
    }

    $http = eZHTTPTool::instance();

    if ( $module->isCurrentAction( 'BrowseForNodes' ) ||
         $module->isCurrentAction( 'BrowseForPrimaryNodes' ) )
    {
        // Remove custom actions from attribute editing.
        $http->removeSessionVariable( 'BrowseCustomAction' );

        $ignoreNodesSelect = array();
        $ignoreNodesClick  = array();
        $assigned = $version->nodeAssignments();
        $publishedAssigned = $object->assignedNodes( false );
        $isTopLevel = false;
        foreach ( $publishedAssigned as $element )
        {
            $append = false;
            if ( $element['parent_node_id'] == 1 )
                $isTopLevel = true;
            foreach ( $assigned as $ass )
            {
                if ( $ass->attribute( 'parent_node' ) == $element['parent_node_id'] )
                    $append = true;
            }

            /* If the current version (draft) has no assigned nodes then
             * we should disallow adding assignments under nodes
             * the previous published version is assignned to.
             * Thus we avoid fatal errors in eZ Publish.
             */
            if ( count($assigned) == 0 )
            {
                $ignoreNodesSelect[] = $element['node_id'];
                $ignoreNodesClick[]  = $element['node_id'];
            }

            if ( $append )
            {
                $ignoreNodesSelect[] = $element['node_id'];
                $ignoreNodesClick[]  = $element['node_id'];
                $ignoreNodesSelect[] = $element['parent_node_id'];
            }
        }
        if ( !$isTopLevel )
        {
            $ignoreNodesSelect = array_unique( $ignoreNodesSelect );
            $objectID = $object->attribute( 'id' );
            $action = 'AddNodeAssignment';
            if ( $module->isCurrentAction( 'BrowseForPrimaryNodes' ) )
            {
                $action = 'AddPrimaryNodeAssignment';
            }
            eZContentBrowse::browse( array( 'action_name' => $action,
                                            'description_template' => 'design:content/browse_placement.tpl',
                                            'keys' => array( 'class' => $class->attribute( 'id' ),
                                                             'class_id' => $class->attribute( 'identifier' ),
                                                             'classgroup' => $class->attribute( 'ingroup_id_list' ),
                                                             'section' => $object->attribute( 'section_id' ) ),
                                            'ignore_nodes_select' => $ignoreNodesSelect,
                                            'ignore_nodes_click'  => $ignoreNodesClick,
                                            'content' => array( 'object_id' => $objectID,
                                                                'object_version' => $editVersion,
                                                                'object_language' => $editLanguage ),
                                            'from_page' => "/content/edit/$objectID/$editVersion/$editLanguage/$fromLanguage" ),
                                     $module );

            return eZModule::HOOK_STATUS_CANCEL_RUN;
        }
    }

    // If node assignment handling is diabled we return
    $useNodeAssigments = true;
    if ( $http->hasPostVariable( 'UseNodeAssigments' ) )
        $useNodeAssigments = (bool)$http->postVariable( 'UseNodeAssigments' );

    if ( !$useNodeAssigments )
        return;

    // Remove custom actions from attribute editing.
    $http->removeSessionVariable( 'BrowseCustomAction' );

    if ( $module->isCurrentAction( 'ConfirmAssignmentDelete' ) && $http->hasPostVariable( 'RemoveNodeID' ) )
    {
        $nodeID = $http->postVariable( 'RemoveNodeID' );
        $db = eZDB::instance();
        $db->begin();
        $version->removeAssignment( $nodeID );
        $db->commit();
    }

    if ( $module->isCurrentAction( 'DeleteNode' ) )
    {

        if ( $http->hasPostVariable( 'RemoveNodeID' ) )
        {
            $nodeID = $http->postVariable( 'RemoveNodeID' );
        }

        $mainNodeID = $http->postVariable( 'MainNodeID' );

//         if ( $nodeID != $mainNodeID )
        {
            $objectID = $object->attribute( 'id' );
            $publishedNode = eZContentObjectTreeNode::fetchNode( $objectID, $nodeID );
            if ( $publishedNode != null )
            {
                $publishParentNodeID = $publishedNode->attribute( 'parent_node_id' );
                if ( $publishParentNodeID > 1 )
                {
                    $childrenCount = $publishedNode->childrenCount();
                    if ( $childrenCount != 0 )
                    {
                        $module->redirectToView( 'removenode', array( $objectID, $editVersion, $editLanguage, $nodeID ) );
                        return eZModule::HOOK_STATUS_CANCEL_RUN;
                    }
                    else
                    {
                        $db = eZDB::instance();
                        $db->begin();
                        $version->removeAssignment( $nodeID );
                        $db->commit();
                    }
                }
            }
            else
            {
                $nodeAssignment = eZNodeAssignment::fetch( $objectID, $version->attribute( 'version' ), $nodeID );
                if ( $nodeAssignment->attribute( 'from_node_id' ) != 0 )
                {
                    $publishedNode = eZContentObjectTreeNode::fetchNode( $objectID, $nodeAssignment->attribute( 'from_node_id' ) );
                    $childrenCount = 0;
                    if ( $publishedNode !== null )
                        $childrenCount = $publishedNode->childrenCount();
                    if ( $childrenCount != 0 )
                    {
                        $module->redirectToView( 'removenode', array( $objectID, $editVersion, $editLanguage, $nodeID ) );
                        return eZModule::HOOK_STATUS_CANCEL_RUN;
                    }
                }
                $db = eZDB::instance();
                $db->begin();
                $version->removeAssignment( $nodeID );
                $db->commit();
            }
        }
    }

    if ( $module->isCurrentAction( 'RemoveAssignments' ) )
    {
        if( $http->hasPostVariable( 'AssignmentIDSelection' ) )
        {
            $selected       = $http->postVariable( 'AssignmentIDSelection' );
            $objectID       = $object->attribute( 'id' );
            $versionInt     = $version->attribute( 'version' );
            $hasChildren    = false;
            $assignmentsIDs = array();
            $assignments    = array();

            // Determine if at least one node of ones we remove assignments for has children.
            foreach ( $selected as $parentNodeID )
            {
                $assignment = eZNodeAssignment::fetch( $objectID, $versionInt, $parentNodeID );
                if( !$assignment )
                {
                    eZDebug::writeWarning( "No assignment found for object $objectID version $versionInt, parent node $parentNodeID" );
                    continue;
                }

                $assignmentID     =  $assignment->attribute( 'id' );
                $assignmentsIDs[] =  $assignmentID;
                $assignments[]    = $assignment;
                $node             = $assignment->attribute( 'node' );

                if( !$node )
                    continue;

                if( $node->childrenCount( false ) > 0 )
                    $hasChildren = true;

                unset( $assignment );
            }

            if ( $hasChildren )
            {
                // We need user confirmation if at least one node we want to remove assignment for contains children.
                // Aactual removal is done in content/removeassignment in this case.
                $http->setSessionVariable( 'AssignmentRemoveData',
                                           array( 'remove_list'   => $assignmentsIDs,
                                                  'object_id'     => $objectID,
                                                  'edit_version'  => $versionInt,
                                                  'edit_language' => $editLanguage,
                                                  'from_language' => $fromLanguage ) );
                $module->redirectToView( 'removeassignment' );
                return eZModule::HOOK_STATUS_CANCEL_RUN;

            }
            else
            {
                // Just remove all the selected locations.
                $mainNodeChanged = false;
                $db = eZDB::instance();
                $db->begin();
                foreach ( $assignments as $assignment )
                {
                    $assignmentID = $assignment->attribute( 'id' );
                    if ( $assignment->attribute( 'is_main' ) )
                        $mainNodeChanged = true;
                    eZNodeAssignment::removeByID( $assignmentID );
                }
                if ( $mainNodeChanged )
                    eZNodeAssignment::setNewMainAssignment( $objectID, $versionInt );
                $db->commit();
                unset( $mainNodeChanged );
            }
            unset( $assignmentsIDs, $assignments );

        }
        else
        {
            eZDebug::writeNotice( 'No nodes to remove selected' );
        }
    }

    if ( $module->isCurrentAction( 'MoveNode' ) )
    {
        $objectID = $object->attribute( 'id' );
        if ( $http->hasPostVariable( 'MoveNodeID' ) )
        {
            $fromNodeID = $http->postVariable( 'MoveNodeID' ); //$sourceNodeID[0];
            $oldAssignmentParentID = $fromNodeID;
            $fromNodeAssignment = eZNodeAssignment::fetch( $objectID, $version->attribute( 'version' ), $fromNodeID );
            $publishParentNodeID = $fromNodeAssignment->attribute( 'parent_node' );
            if ( $publishParentNodeID > 1 )
            {
                if( $fromNodeAssignment->attribute( 'from_node_id' ) != 0 )
                {
                    $fromNodeID = $fromNodeAssignment->attribute( 'from_node_id' );
                    $oldAssignmentParentID = $fromNodeAssignment->attribute( 'parent_node' );
                }

                // we don't allow moving object to itself, to its descendants or parent object(s)
                $objectAssignedNodes = $object->attribute( 'assigned_nodes' );

                // nodes that are not allowed to select (via checkbox or radiobutton) when browsing
                $ignoreNodesSelectArray = array();

                // nodes that are not allowed to click on
                $ignoreNodesClickArray  = array();
                foreach( $objectAssignedNodes as $curAN )
                {
                    // current node should be neither selectable, nor clickable
                    $ignoreNodesClickArray[]  = $curAN->NodeID;
                    $ignoreNodesSelectArray[] = $curAN->NodeID;

                    // parent node should be only clickable, but not selectable
                    $ignoreNodesSelectArray[] = $curAN->ParentNodeID;
                }

                eZContentBrowse::browse( array( 'action_name' => 'MoveNodeAssignment',
                                                'description_template' => 'design:content/browse_move_placement.tpl',
                                                'keys' => array( 'class' => $class->attribute( 'id' ),
                                                                 'class_id' => $class->attribute( 'identifier' ),
                                                                 'classgroup' => $class->attribute( 'ingroup_id_list' ),
                                                                 'section' => $object->attribute( 'section_id' ) ),
                                                'start_node' => $fromNodeID,
                                                'persistent_data' => array( 'FromNodeID' => $fromNodeID,
                                                                            'OldAssignmentParentID' => $oldAssignmentParentID ),
                        'ignore_nodes_select' => $ignoreNodesSelectArray,
                        'ignore_nodes_click'  => $ignoreNodesClickArray,
                                                'content' => array( 'object_id' => $objectID,
                                                                    'previous_node_id' => $fromNodeID,
                                                                    'object_version' => $editVersion,
                                                                    'object_language' => $editLanguage ),
                                                'from_page' => "/content/edit/$objectID/$editVersion/$editLanguage" ),
                                         $module );

                return eZModule::HOOK_STATUS_CANCEL_RUN;
            }
        }
    }
}