} // Check for redirection to current page if ($module->hasActionParameter('UploadRedirectBack')) { if ($module->actionParameter('UploadRedirectBack') == 1) { $parameters['result_uri'] = eZRedirectManager::redirectURI($module, 'content/view/full/2', true); } else { if ($module->actionParameter('UploadRedirectBack') == 2) { $parameters['result_uri'] = eZRedirectManager::redirectURI($module, 'content/view/full/2', false); } } } // Check for redirection to specific page if ($module->hasActionParameter('UploadRedirectURI')) { $parameters['result_uri'] = $module->actionParameter('UploadRedirectURI'); } eZContentUpload::upload($parameters, $module); return; } else { if (!isset($result)) { return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel'); } } } } } } } } } } }
function fetchNodeInfo( &$node ) { // When finished, we'll return an array of attributes/properties. $entry = array(); // Grab settings from the ini file: $webdavINI = eZINI::instance( eZWebDAVContentServer::WEBDAV_INI_FILE ); $iniSettings = $webdavINI->variable( 'DisplaySettings', 'FileAttribute' ); $classIdentifier = $node->attribute( 'class_identifier' ); $object = $node->attribute( 'object' ); // By default, everything is displayed as a folder: // Trim the name of the node, it is in some cases whitespace in eZ Publish $entry["name"] = trim( $node->attribute( 'name' ) ); $entry["size"] = 0; $entry["mimetype"] = 'httpd/unix-directory'; $entry["ctime"] = $object->attribute( 'published' ); $entry["mtime"] = $object->attribute( 'modified' ); $upload = new eZContentUpload(); $info = $upload->objectFileInfo( $object ); $suffix = ''; $class = $object->contentClass(); $isObjectFolder = $this->isObjectFolder( $object, $class ); if ( $isObjectFolder ) { // We do nothing, the default is to see it as a folder } else if ( $info ) { $filePath = $info['filepath']; $entry["mimetype"] = false; $entry["size"] = false; if ( isset( $info['filesize'] ) ) $entry['size'] = $info['filesize']; if ( isset( $info['mime_type'] ) ) $entry['mimetype'] = $info['mime_type']; // Fill in information from the actual file if they are missing. $file = eZClusterFileHandler::instance( $filePath ); if ( !$entry['size'] and $file->exists() ) { $entry["size"] = $file->size(); } if ( !$entry['mimetype'] ) { $mimeInfo = eZMimeType::findByURL( $filePath ); $entry["mimetype"] = $mimeInfo['name']; $suffix = $mimeInfo['suffix']; if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } else { // eZMimeType returns first suffix in its list // this could be another one than the original file extension // so let's try to get the suffix from the file path first $suffix = eZFile::suffix( $filePath ); if ( !$suffix ) { $mimeInfo = eZMimeType::findByName( $entry['mimetype'] ); $suffix = $mimeInfo['suffix']; } if ( strlen( $suffix ) > 0 ) $entry["name"] .= '.' . $suffix; } if ( $file->exists() ) { $entry["ctime"] = $file->mtime(); $entry["mtime"] = $file->mtime(); } } else { // Here we only show items as folders if they have // is_container set to true, otherwise it's an unknown binary file if ( !$class->attribute( 'is_container' ) ) { $entry['mimetype'] = 'application/octet-stream'; } } $scriptURL = eZSys::instance()->RequestURI; if ( strlen( $scriptURL ) > 0 and $scriptURL[ strlen( $scriptURL ) - 1 ] != "/" ) $scriptURL .= "/"; $trimmedScriptURL = trim( $scriptURL, '/' ); $scriptURLParts = explode( '/', $trimmedScriptURL ); $siteAccess = $scriptURLParts[0]; $virtualFolder = $scriptURLParts[1]; $startURL = '/' . $siteAccess . '/' . $virtualFolder . '/'; // Set the href attribute (note that it doesn't just equal the name). if ( !isset( $entry['href'] ) ) { if ( strlen( $suffix ) > 0 ) $suffix = '.' . $suffix; $alias = $node->urlAlias(); if ( $virtualFolder == eZWebDAVContentServer::virtualMediaFolderName() ) { // remove the real media node url alias, the virtual media folder is already in $startURL $aliasParts = explode( '/', $alias ); array_shift( $aliasParts ); $alias = implode( '/', $aliasParts ); } $entry["href"] = $startURL . $alias . $suffix; } // Return array of attributes/properties (name, size, mime, times, etc.). return $entry; }
/** * Handles data storage on the content tree level. * * It will try to find the parent node of the wanted placement and * create a new object with data from $tempFile. * * @param string $currentSite Eg. 'plain_site_user' * @param string $virtualFolder Eg. 'Content' * @param string $target Eg. 'Folder1/file1.txt' * @param string $tempFile The temporary file holding the contents * @return bool * @todo remove/replace eZContentUpload */ protected function putContentData($currentSite, $virtualFolder, $target, $tempFile) { $nodePath = $this->internalNodePath($virtualFolder, $target); $parentNode = $this->fetchParentNodeByTranslation($nodePath); if ($parentNode === null) { // The node does not exist, so we cannot put the file return false; // @as self::FAILED_CONFLICT; } // Can we put content in the parent node if (!$parentNode->canRead()) { return false; // @as self::FAILED_FORBIDDEN; } $parentNodeID = $parentNode->attribute('node_id'); $existingNode = $this->fetchNodeByTranslation($nodePath); $upload = new eZContentUpload(); if (!$upload->handleLocalFile($result, $tempFile, $parentNodeID, $existingNode)) { if ($result['status'] === eZContentUpload::STATUS_PERMISSION_DENIED) { return false; // @as self::FAILED_FORBIDDEN; } else { return false; // @as self::FAILED_UNSUPPORTED; } } return true; // @as self::OK_CREATED; }
<?php /** * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://ez.no/Resources/Software/Licenses/eZ-Business-Use-License-Agreement-eZ-BUL-Version-2.1 eZ Business Use License Agreement eZ BUL Version 2.1 * @version 4.7.0 * @package kernel */ $tpl = eZTemplate::factory(); $http = eZHTTPTool::instance(); $module = $Params['Module']; $upload = new eZContentUpload(); $errors = array(); if ( $module->isCurrentAction( 'CancelUpload' ) ) { $url = false; if ( $upload->attribute( 'cancel_uri' ) ) { $url = $upload->attribute( 'cancel_uri' ); } else if ( $upload->attribute( 'result_uri' ) ) { $url = $module->redirectTo( $upload->attribute( 'result_uri' ) ); } else if ( $upload->attribute( 'result_module' ) ) { $info = $upload->attribute( 'result_module' ); $moduleName = isset( $info[0] ) ? $info[0] : false;
/** * Creates the eZContentObject from the uploaded file * * @param eZHTTPFile $file * @param eZContentObjectTreeNode $location * @param string $name * @return eZContentObject * @throw InvalidArgumentException if the parent location does not exists * @throw RuntimeException if the object can not be created */ public function createObject($file, $parentNodeId, $name = '') { $result = array(); $parentNode = eZContentObjectTreeNode::fetch($parentNodeId); if (!$parentNode instanceof eZContentObjectTreeNode) { throw new InvalidArgumentException(ezpI18n::tr('extension/ezjscore/ajaxuploader', 'Location not found.')); } $upload = new eZContentUpload(); $r = $upload->handleLocalFile($result, $file, $parentNodeId, null, $name, $this->attribute->attribute('language_code')); if (!$r || !$result['contentobject'] instanceof eZContentObject) { throw new RuntimeException(ezpI18n::tr('extension/ezjscore/ajaxuploader', 'Unable to create the content object to add to the relation: %detail', null, array('%detail', $result['errors'][0]['description']))); } return $result['contentobject']; }
/** * Creates a new content or updates an existing one based on $file * * @param string $file the file to import * @param int $placeNodeID the node id where to place the new document or * the node of the document to update * @param string $originalFileName * @param string $importType "import" or "replace" * @param eZContentUpload|null $upload (not used in this method) * @param string|false $locale the locale to use while creating/updating * the content * @return array|false false if something went wrong */ function import($file, $placeNodeID, $originalFileName, $importType = "import", $upload = null, $locale = false) { $ooINI = eZINI::instance('odf.ini'); //$tmpDir = $ooINI->variable( 'ODFSettings', 'TmpDir' ); // Use var-directory as temporary directory $tmpDir = getcwd() . "/" . eZSys::cacheDirectory(); $allowedTypes = $ooINI->variable('DocumentType', 'AllowedTypes'); $convertTypes = $ooINI->variable('DocumentType', 'ConvertTypes'); $originalFileType = array_slice(explode('.', $originalFileName), -1, 1); $originalFileType = strtolower($originalFileType[0]); if (!in_array($originalFileType, $allowedTypes, false) and !in_array($originalFileType, $convertTypes, false)) { $this->setError(self::ERROR_UNSUPPORTEDTYPE, ezpI18n::tr('extension/ezodf/import/error', "Filetype: ") . $originalFileType); return false; } // If replacing/updating the document we need the ID. if ($importType == "replace") { $GLOBALS["OOImportObjectID"] = $placeNodeID; } // Check if we have access to node $place_node = eZContentObjectTreeNode::fetch($placeNodeID); $importClassIdentifier = $ooINI->variable('ODFImport', 'DefaultImportClass'); // Check if class exist $class = eZContentClass::fetchByIdentifier($importClassIdentifier); if (!is_object($class)) { eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist."); $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier); return false; } if (!is_object($place_node)) { $locationOK = false; if ($upload !== null) { $parentNodes = false; $parentMainNode = false; $locationOK = $upload->detectLocations($importClassIdentifier, $class, $placeNodeID, $parentNodes, $parentMainNode); } if ($locationOK === false || $locationOK === null) { $this->setError(self::ERROR_UNKNOWNNODE, ezpI18n::tr('extension/ezodf/import/error', "Unable to fetch node with id ") . $placeNodeID); return false; } $placeNodeID = $parentMainNode; $place_node = eZContentObjectTreeNode::fetch($placeNodeID); } // Check if document conversion is needed // // Alex 2008/04/21 - added !== false if (in_array($originalFileType, $convertTypes, false) !== false) { $uniqueStamp = md5(time()); $tmpFromFile = $tmpDir . "/convert_from_{$uniqueStamp}.doc"; $tmpToFile = $tmpDir . "/ooo_converted_{$uniqueStamp}.odt"; copy(realpath($file), $tmpFromFile); /// Convert document using the eZ Publish document conversion daemon if (!$this->daemonConvert($tmpFromFile, $tmpToFile)) { if ($this->getErrorNumber() == 0) { $this->setError(self::ERROR_CONVERT); } return false; } // At this point we can unlink the sourcefile for conversion unlink($tmpFromFile); // Overwrite the file location $file = $tmpToFile; } $importResult = array(); $unzipResult = ""; $uniqueImportDir = $this->ImportDir; eZDir::mkdir($uniqueImportDir, false, true); $http = eZHTTPTool::instance(); $archiveOptions = new ezcArchiveOptions(array('readOnly' => true)); $archive = ezcArchive::open($file, null, $archiveOptions); $archive->extract($uniqueImportDir); $fileName = $uniqueImportDir . "content.xml"; $dom = new DOMDocument('1.0', 'UTF-8'); $success = $dom->load($fileName); $sectionNodeHash = array(); // At this point we could unlink the destination file from the conversion, if conversion was used if (isset($tmpToFile)) { unlink($tmpToFile); } if (!$success) { $this->setError(self::ERROR_PARSEXML); return false; } // Fetch the automatic document styles $automaticStyleArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'automatic-styles'); if ($automaticStyleArray->length == 1) { $this->AutomaticStyles = $automaticStyleArray->item(0)->childNodes; } // Fetch the body section content $sectionNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_TEXT, 'section'); $customClassFound = false; if ($sectionNodeArray->length > 0) { $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray'); // Check the defined sections in OO document $sectionNameArray = array(); foreach ($sectionNodeArray as $sectionNode) { $sectionNameArray[] = strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, "name")); } // Check if there is a coresponding eZ Publish class for this document foreach ($registeredClassArray as $className) { $attributeArray = $ooINI->variable($className, 'Attribute'); if (!empty($attributeArray)) { // Convert space to _ in section names foreach ($sectionNameArray as $key => $value) { $sectionNameArray[$key] = str_replace(" ", "_", $value); } sort($attributeArray); sort($sectionNameArray); $diff = array_diff($attributeArray, $sectionNameArray); if (empty($diff)) { $importClassIdentifier = $className; $customClassFound = true; break; } } } if ($customClassFound == true) { foreach ($sectionNodeArray as $sectionNode) { $sectionName = str_replace(" ", "_", strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, 'name'))); $xmlText = ""; $level = 1; $childArray = $sectionNode->childNodes; $nodeCount = 1; foreach ($childArray as $childNode) { if ($childNode->nodeType === XML_ELEMENT_NODE) { $isLastTag = $nodeCount == $childArray->length; $xmlText .= self::handleNode($childNode, $level, $isLastTag); } $nodeCount++; } $endSectionPart = ""; $levelDiff = 1 - $level; if ($levelDiff < 0) { $endSectionPart = str_repeat("</section>", abs($levelDiff)); } $charset = eZTextCodec::internalCharset(); // Store the original XML for each section, since some datatypes needs to handle the XML specially $sectionNodeHash[$sectionName] = $sectionNode; $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . " xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>"; } } } if ($customClassFound == false) { // No defined sections. Do default import. $bodyNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'text'); // Added by Soushi // check the parent-style-name [ eZSectionDefinition ] $eZSectionDefinitionStyleName = array(); foreach ($automaticStyleArray->item(0)->childNodes as $child) { if ($child->nodeType === XML_ELEMENT_NODE && $child->getAttributeNS(self::NAMESPACE_STYLE, 'parent-style-name') === 'eZSectionDefinition') { $eZSectionDefinitionStyleName[] = $child->getAttributeNS(self::NAMESPACE_STYLE, 'name'); } } $sectionNameArray = array(); $sectionNodeArray = array(); $paragraphSectionName = NULL; $firstChildFlag = false; $paragraphSectionNodeArray = array(); foreach ($bodyNodeArray->item(0)->childNodes as $childNode) { $firstChildFlag = true; if ($childNode->nodeType === XML_ELEMENT_NODE && (in_array($childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name'), $eZSectionDefinitionStyleName) || $childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name') === 'eZSectionDefinition')) { $firstChildFlag = false; $childNodeChildren = $childNode->childNodes; $paragraphSectionName = trim($childNodeChildren->item(0)->textContent); $sectionNameArray[] = $paragraphSectionName; } if ($paragraphSectionName && $firstChildFlag) { $paragraphSectionNodeArray[$paragraphSectionName][] = $childNode; } } $sectionNodeArray = array(); foreach ($paragraphSectionNodeArray as $key => $childNodes) { $sectionNode = $dom->createElement('section'); foreach ($childNodes as $childNode) { $sectionNode->appendChild($childNode); } $sectionNodeArray[$key] = $sectionNode; } $customClassFound = false; if ($sectionNameArray) { $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray'); // Check if there is a coresponding eZ Publish class for this document foreach ($registeredClassArray as $className) { $attributeArray = $ooINI->variable($className, 'Attribute'); if (!empty($attributeArray)) { // Convert space to _ in section names foreach ($sectionNameArray as $key => $value) { $sectionNameArray[$key] = str_replace(" ", "_", $value); } sort($attributeArray); sort($sectionNameArray); $diff = array_diff($attributeArray, $sectionNameArray); if (empty($diff)) { $importClassIdentifier = $className; $customClassFound = true; break; } } } } if ($sectionNameArray && $customClassFound == true) { foreach ($sectionNodeArray as $key => $sectionNode) { $sectionName = str_replace(" ", "_", $key); $xmlText = ""; $level = 1; foreach ($sectionNode->childNodes as $childNode) { $isLastTag = !isset($childNode->nextSibling); $xmlText .= self::handleNode($childNode, $level, $isLastTag); } $endSectionPart = ""; $levelDiff = 1 - $level; if ($levelDiff < 0) { $endSectionPart = str_repeat("</section>", abs($levelDiff)); } $charset = eZTextCodec::internalCharset(); // Store the original XML for each section, since some datatypes needs to handle the XML specially $sectionNodeHash[$sectionName] = $sectionNode; $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . " xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>"; } } else { if ($bodyNodeArray->length === 1) { $xmlText = ""; $level = 1; foreach ($bodyNodeArray->item(0)->childNodes as $childNode) { $xmlText .= self::handleNode($childNode, $level); } $endSectionPart = ""; $levelDiff = 1 - $level; if ($levelDiff < 0) { $endSectionPart = str_repeat("</section>", abs($levelDiff)); } $charset = eZTextCodec::internalCharset(); $xmlTextBody = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . " xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>"; } } } if ($importType == "replace") { // Check if we are allowed to edit the node $functionCollection = new eZContentFunctionCollection(); $access = $functionCollection->checkAccess('edit', $place_node, false, false, $locale); } else { // Check if we are allowed to create a node under the node $functionCollection = new eZContentFunctionCollection(); $access = $functionCollection->checkAccess('create', $place_node, $importClassIdentifier, $place_node->attribute('class_identifier'), $locale); } if ($access['result']) { // Check if we should replace the current object or import a new if ($importType !== "replace") { $class = eZContentClass::fetchByIdentifier($importClassIdentifier); $place_object = $place_node->attribute('object'); $sectionID = $place_object->attribute('section_id'); $creatorID = $this->currentUserID; $parentNodeID = $placeNodeID; if (!is_object($class)) { eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist."); $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier); return false; } $object = $class->instantiate($creatorID, $sectionID, false, $locale); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1)); $nodeAssignment->store(); $version = $object->version(1); $version->setAttribute('modified', eZDateTime::currentTimeStamp()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $dataMap = $object->dataMap(); } else { // Check if class is supported before we start changing anything $placeClassIdentifier = $place_node->attribute('class_identifier'); if ($ooINI->hasVariable($placeClassIdentifier, 'DefaultImportTitleAttribute') && $ooINI->hasVariable($placeClassIdentifier, 'DefaultImportBodyAttribute')) { $titleAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportTitleAttribute'); $bodyAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportBodyAttribute'); // Extra check to see if attributes exist in dataMap (config is not wrong) $dataMap = $place_node->attribute('data_map'); if (!isset($dataMap[$titleAttribute]) || !isset($dataMap[$bodyAttribute])) { $this->setError(self::ERROR_IMPORTING, "Error in configuration for {$placeClassIdentifier}, please check configuration file."); return false; } unset($dataMap); } else { $this->setError(self::ERROR_IMPORTING, "No settings for replacing node of type {$placeClassIdentifier}. Stopping."); return false; } // Change class for importing $importClassIdentifier = $placeClassIdentifier; // already fetched: $node = eZContentObjectTreeNode::fetch( $placeNodeID ); $object = $place_node->attribute('object'); $version = $object->createNewVersionIn($locale); $dataMap = $version->dataMap(); } $contentObjectID = $object->attribute('id'); if ($customClassFound == true) { // Initialize the actual object attributes $attributeArray = $ooINI->variable($importClassIdentifier, 'Attribute'); foreach ($attributeArray as $attributeIdentifier => $sectionName) { switch ($dataMap[$attributeIdentifier]->DataTypeString) { case "ezstring": case "eztext": if (!isset($xmlTextArray[$sectionName])) { continue; } $eztextDom = new DOMDOcument('1.0', 'UTF-8'); $eztextDom->loadXML($xmlTextArray[$sectionName]); $text = $eztextDom->documentElement->textContent; $dataMap[$attributeIdentifier]->setAttribute('data_text', trim($text)); $dataMap[$attributeIdentifier]->store(); break; case "ezxmltext": if (!isset($xmlTextArray[$sectionName])) { continue; } $dataMap[$attributeIdentifier]->setAttribute('data_text', $xmlTextArray[$sectionName]); $dataMap[$attributeIdentifier]->store(); break; case "ezdate": // Only support date formats as a single paragraph in a section with the format: // day/month/year if (!isset($xmlTextArray[$sectionName])) { continue; } $dateString = strip_tags($xmlTextArray[$sectionName]); $dateArray = explode("/", $dateString); if (count($dateArray) == 3) { $year = $dateArray[2]; $month = $dateArray[1]; $day = $dateArray[0]; $date = new eZDate(); $contentClassAttribute = $dataMap[$attributeIdentifier]; $date->setMDY($month, $day, $year); $dataMap[$attributeIdentifier]->setAttribute('data_int', $date->timeStamp()); $dataMap[$attributeIdentifier]->store(); } break; case "ezdatetime": // Only support date formats as a single paragraph in a section with the format: // day/month/year 14:00 if (!isset($xmlTextArray[$sectionName])) { continue; } $dateString = trim(strip_tags($xmlTextArray[$sectionName])); $dateTimeArray = explode(" ", $dateString); $dateArray = explode("/", $dateTimeArray[0]); $timeArray = explode(":", $dateTimeArray[1]); if (count($dateArray) == 3 and count($timeArray) == 2) { $year = $dateArray[2]; $month = $dateArray[1]; $day = $dateArray[0]; $hour = $timeArray[0]; $minute = $timeArray[1]; $dateTime = new eZDateTime(); $contentClassAttribute = $dataMap[$attributeIdentifier]; $dateTime->setMDYHMS($month, $day, $year, $hour, $minute, 0); $dataMap[$attributeIdentifier]->setAttribute('data_int', $dateTime->timeStamp()); $dataMap[$attributeIdentifier]->store(); } break; case "ezimage": $hasImage = false; // Images are treated as an image object inside a paragrah. // We fetch the first image object if there are multiple and ignore the rest if (is_object($sectionNodeHash[$sectionName])) { // Look for paragraphs in the section foreach ($sectionNodeHash[$sectionName]->childNodes as $paragraph) { if (!$paragraph->hasChildNodes()) { continue; } // Look for frame node foreach ($paragraph->childNodes as $frame) { // finally look for the image node $children = $frame->childNodes; $imageNode = $children->item(0); if ($imageNode && $imageNode->localName == "image") { $fileName = ltrim($imageNode->getAttributeNS(self::NAMESPACE_XLINK, 'href'), '#'); $filePath = $this->ImportDir . $fileName; if (file_exists($filePath)) { $imageContent = $dataMap[$attributeIdentifier]->attribute('content'); $imageContent->initializeFromFile($filePath, false, basename($filePath)); $imageContent->store($dataMap[$attributeIdentifier]); $dataMap[$attributeIdentifier]->store(); } $hasImage = true; } } } } if (!$hasImage) { $imageHandler = $dataMap[$attributeIdentifier]->attribute('content'); if ($imageHandler) { $imageHandler->removeAliases($dataMap[$attributeIdentifier]); } } break; case "ezmatrix": $matrixHeaderArray = array(); // Fetch the current defined columns in the matrix $matrix = $dataMap[$attributeIdentifier]->content(); $columns = $matrix->attribute("columns"); foreach ($columns['sequential'] as $column) { $matrixHeaderArray[] = $column['name']; } $headersValid = true; $originalHeaderCount = count($matrixHeaderArray); $headerCount = 0; $rowCount = 0; $cellArray = array(); // A matrix is supported as a table inside sections. If multiple tables are present we take the first. if (is_object($sectionNodeHash[$sectionName])) { // Look for paragraphs in the section foreach ($sectionNodeHash[$sectionName]->childNodes as $table) { if ($table->localName == "table") { // Loop the rows in the table foreach ($table->childNodes as $row) { // Check the headers and compare with the defined matrix if ($row->localName == "table-header-rows") { $rowArray = $row->childNodes; if ($rowArray->length == 1) { foreach ($rowArray->item(0)->childNodes as $headerCell) { if ($headerCell->localName == "table-cell") { $paragraphArray = $headerCell->childNodes; if ($paragraphArray->length == 1) { $headerName = $paragraphArray->item(0)->textContent; if ($matrixHeaderArray[$headerCount] != $headerName) { $headersValid = false; } $headerCount++; } } } } } // Check the rows if ($row->localName == "table-row") { foreach ($row->childNodes as $cell) { if ($cell->childNodes->length >= 1) { $firstParagraph = $cell->childNodes->item(0); $cellArray[] = $firstParagraph->textContent; } } $rowCount++; } } } } } if ($headerCount == $originalHeaderCount and $headersValid == true) { // Remove all existing rows for ($i = 0; $i < $matrix->attribute("rowCount"); $i++) { $matrix->removeRow($i); } // Insert new rows $matrix->addRow(false, $rowCount); $matrix->Cells = $cellArray; $dataMap[$attributeIdentifier]->setAttribute('data_text', $matrix->xmlString()); $matrix->decodeXML($dataMap[$attributeIdentifier]->attribute('data_text')); $dataMap[$attributeIdentifier]->setContent($matrix); $dataMap[$attributeIdentifier]->store(); } break; default: eZDebug::writeError("Unsupported datatype for OpenOffice.org import: " . $dataMap[$attributeIdentifier]->DataTypeString); break; } } } else { // Check if attributes are already fetched if (!isset($titleAttribute) || !isset($bodyAttribute)) { // Set attributes accorring to import class $titleAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportTitleAttribute'); $bodyAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportBodyAttribute'); } $objectName = basename($originalFileName); // Remove extension from name $objectName = preg_replace("/(\\....)\$/", "", $objectName); // Convert _ to spaces and upcase the first character $objectName = ucfirst(str_replace("_", " ", $objectName)); $dataMap[$titleAttribute]->setAttribute('data_text', $objectName); $dataMap[$titleAttribute]->store(); $dataMap[$bodyAttribute]->setAttribute('data_text', $xmlTextBody); $dataMap[$bodyAttribute]->store(); } $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => $version->attribute('version'))); $storeImagesInMedia = $ooINI->variable("ODFImport", "PlaceImagesInMedia") == "true"; if ($storeImagesInMedia == true) { // Fetch object to get correct name $object = eZContentObject::fetch($contentObjectID); $contentINI = eZINI::instance('content.ini'); $mediaRootNodeID = $contentINI->variable("NodeSettings", "MediaRootNode"); $node = eZContentObjectTreeNode::fetch($mediaRootNodeID); $articleFolderName = $object->attribute('name'); $importFolderName = $ooINI->variable('ODFImport', 'ImportedImagesMediaNodeName'); $importNode = self::createSubNode($node, $importFolderName); $articleNode = self::createSubNode($importNode, $articleFolderName); $imageRootNode = $articleNode->attribute("node_id"); } else { $imageRootNode = $object->attribute("main_node_id"); } // Publish all embedded images as related objects foreach ($this->RelatedImageArray as $image) { // Publish related images $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $image['ID'], 'contentobject_version' => 1, 'parent_node' => $imageRootNode, 'is_main' => 1)); $nodeAssignment->store(); eZOperationHandler::execute('content', 'publish', array('object_id' => $image['ID'], 'version' => 1)); $object->addContentObjectRelation($image['ID'], 1); } $mainNode = $object->attribute('main_node'); // Create object stop. $importResult['Object'] = $object; $importResult['Published'] = $operationResult['status'] == eZModuleOperationInfo::STATUS_CONTINUE; if ($mainNode instanceof eZContentObjectTreeNode) { $importResult['MainNode'] = $mainNode; $importResult['URLAlias'] = $mainNode->attribute('url_alias'); $importResult['NodeName'] = $mainNode->attribute('name'); } else { $importResult['MainNode'] = false; $importResult['URLAlias'] = false; $importResult['NodeName'] = false; } $importResult['ClassIdentifier'] = $importClassIdentifier; } else { $this->setError(self::ERROR_ACCESSDENIED); return false; } // Clean up eZDir::recursiveDelete($uniqueImportDir); return $importResult; }
static function result($actionName, $cleanup = true) { $upload = new eZContentUpload(); $isNodeSelection = $upload->attribute('return_type') == 'NodeID'; $resultData = $upload->attribute('result'); $result = false; if ($isNodeSelection) { $result = $resultData['node_id']; } else { $result = $resultData['object_id']; } if ($cleanup) { eZContentUpload::cleanup($actionName); } return $result; }
function checkRelationActions($module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $fromLanguage) { $http = eZHTTPTool::instance(); if ($module->isCurrentAction('BrowseForObjects')) { $objectID = $object->attribute('id'); $assignedNodes = $object->attribute('assigned_nodes'); $assignedNodesIDs = array(); foreach ($assignedNodes as $node) { $assignedNodesIDs = $node->attribute('node_id'); } unset($assignedNodes); eZContentBrowse::browse(array('action_name' => 'AddRelatedObject', 'description_template' => 'design:content/browse_related.tpl', 'content' => array('object_id' => $objectID, 'object_version' => $editVersion, 'object_language' => $editLanguage), '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' => $assignedNodesIDs, 'from_page' => $module->redirectionURI('content', 'edit', array($objectID, $editVersion, $editLanguage, $fromLanguage))), $module); return eZModule::HOOK_STATUS_CANCEL_RUN; } if ($module->isCurrentAction('UploadFileRelation')) { $objectID = $object->attribute('id'); $section = eZSection::fetch($object->attribute('section_id')); $navigationPart = false; if ($section) { $navigationPart = $section->attribute('navigation_part_identifier'); } $location = false; if ($module->hasActionParameter('UploadRelationLocation')) { $location = $module->actionParameter('UploadRelationLocation'); } // We only do direct uploading if we have the uploaded HTTP file // if not we need to go to the content/upload page. if (eZHTTPFile::canFetch('UploadRelationFile')) { $upload = new eZContentUpload(); if ($upload->handleUpload($result, 'UploadRelationFile', $location, false)) { $relatedObjectID = $result['contentobject_id']; if ($relatedObjectID) { $db = eZDB::instance(); $db->begin(); $object->addContentObjectRelation($relatedObjectID, $editVersion); $db->commit(); } } } else { eZContentUpload::upload(array('action_name' => 'RelatedObjectUpload', 'description_template' => 'design:content/upload_related.tpl', 'navigation_part_identifier' => $navigationPart, 'content' => array('object_id' => $objectID, 'object_version' => $editVersion, 'object_language' => $editLanguage), 'keys' => array('class' => $class->attribute('id'), 'class_id' => $class->attribute('identifier'), 'classgroup' => $class->attribute('ingroup_id_list'), 'section' => $object->attribute('section_id')), 'result_action_name' => 'UploadedFileRelation', 'ui_context' => 'edit', 'result_module' => array('content', 'edit', array($objectID, $editVersion, $editLanguage, $fromLanguage))), $module); return eZModule::HOOK_STATUS_CANCEL_RUN; } } if ($module->isCurrentAction('DeleteRelation')) { $objectID = $object->attribute('id'); if ($http->hasPostVariable('DeleteRelationIDArray')) { $relationObjectIDs = $http->postVariable('DeleteRelationIDArray'); } else { $relationObjectIDs = array(); } $db = eZDB::instance(); $db->begin(); foreach ($relationObjectIDs as $relationObjectID) { $object->removeContentObjectRelation($relationObjectID, $editVersion); } $db->commit(); } if ($module->isCurrentAction('NewObject')) { if ($http->hasPostVariable('ClassID')) { if ($http->hasPostVariable('SectionID')) { $sectionID = $http->postVariable('SectionID'); } else { $sectionID = 0; /* Will be changed later */ } $contentClassID = $http->postVariable('ClassID'); $class = eZContentClass::fetch($contentClassID); $db = eZDB::instance(); $db->begin(); $relatedContentObject = $class->instantiate(false, $sectionID); $db->commit(); $newObjectID = $relatedContentObject->attribute('id'); $relatedContentVersion = $relatedContentObject->attribute('current'); if ($relatedContentObject->attribute('can_edit')) { $db = eZDB::instance(); $db->begin(); $assignmentHandler = new eZContentObjectAssignmentHandler($relatedContentObject, $relatedContentVersion); $sectionID = (int) $assignmentHandler->setupAssignments(array('group-name' => 'RelationAssignmentSettings', 'default-variable-name' => 'DefaultAssignment', 'specific-variable-name' => 'ClassSpecificAssignment', 'section-id-wanted' => true, 'fallback-node-id' => $object->attribute('main_node_id'))); $http->setSessionVariable('ParentObject', array($object->attribute('id'), $editVersion, $editLanguage)); $http->setSessionVariable('NewObjectID', $newObjectID); /* Change section ID to the same one as the main node placement */ $db->query("UPDATE ezcontentobject SET section_id = {$sectionID} WHERE id = {$newObjectID}"); $db->commit(); $module->redirectToView('edit', array($relatedContentObject->attribute('id'), $relatedContentObject->attribute('current_version'), false)); } else { $db = eZDB::instance(); $db->begin(); $relatedContentObject->purge(); $db->commit(); } return; } } }
<?php $http = eZHTTPTool::instance(); $tpl = eZTemplate::factory(); $module = $Params['Module']; $parentNodeID = $Params['ParentNodeID']; $message = json_encode("error"); if ($module->isCurrentAction('Upload')) { $result = array('errors' => array()); // Exec multiupload handlers preUpload method eZMultiuploadHandler::exec('preUpload', $result); // Handle file upload only if there was no errors if (empty($result['errors'])) { // Handle file upload. All checkes are performed by eZContentUpload::handleUpload() // and available in $result array $upload = new eZContentUpload(); $upload->handleUpload($result, 'Filedata', $parentNodeID, false); } // Exec multiupload handlers postUpload method eZMultiuploadHandler::exec('postUpload', $result); unset($result['contentobject_main_node']); unset($result['contentobject']); $id = md5((string) mt_rand() . (string) microtime()); $response = array('id' => $id, 'result' => $result); $message = json_encode($response); } header('Content-Type: application/json'); echo $message; eZExecution::cleanExit();
$imageIni = eZINI::instance('image.ini'); $params = array('dataMap' => array('image')); if (!$object instanceof eZContentObject || !$object->canEdit()) { echo ezpI18n::tr('design/standard/ezoe', 'Invalid parameter: %parameter = %value', null, array('%parameter' => 'ObjectId', '%value' => $objectID)); eZExecution::cleanExit(); } // is this a upload? // forcedUpload is needed since hasPostVariable returns false if post size exceeds // allowed size set in max_post_size in php.ini if ($http->hasPostVariable('uploadButton') || $forcedUpload) { $version = eZContentObjectVersion::fetchVersion($objectVersion, $objectID); if (!$version) { echo ezpI18n::tr('design/standard/ezoe', 'Invalid parameter: %parameter = %value', null, array('%parameter' => 'ObjectVersion', '%value' => $objectVersion)); eZExecution::cleanExit(); } $upload = new eZContentUpload(); $location = false; if ($http->hasPostVariable('location')) { $location = $http->postVariable('location'); if ($location === 'auto' || trim($location) === '') { $location = false; } } $objectName = ''; if ($http->hasPostVariable('objectName')) { $objectName = trim($http->postVariable('objectName')); } try { $uploadedOk = $upload->handleUpload($result, 'fileName', $location, false, $objectName, $version->attribute('initial_language')->attribute('locale'), false); if (!$uploadedOk) { throw new RuntimeException("Upload failed");
<?php $parentNodeId = (int) $_REQUEST['parent_node_id']; if ($parentNodeId && !empty($_FILES)) { $return = array(); $upload = new eZContentUpload(); foreach ($_FILES as $key => $values) { if (substr($key, 0, 5) == 'files') { $upload->handleUpload($result, $key, $parentNodeId, false); $return[] = array('name' => $values['name'], 'errors' => implode(', ', $result['errors']), 'contentobject_id' => $result['contentobject_id']); } } } else { die('missing input parameters'); } header('Content-type: application/json'); echo json_encode($return); eZExecution::cleanExit();
/** * Crea un oggetto a partire da un fieldArray di tipo ezimage, ezbinaryfile * @see eZContentUpload * @params array $fieldArray * @return int content object id */ protected function createMedia($fieldArray) { $filePath = SQLIContentUtils::getRemoteFile($fieldArray['value']); $upload = new eZContentUpload(); $result = array(); if ($upload->handleLocalFile($result, $filePath, 'auto', false) == true) { return $result['contentobject_id']; } eZDebug::writeNotice(var_export($result['notices']), __METHOD__); eZDebug::writeError(var_export($result['errors']), __METHOD__); return ''; }
/** * Handles image upload operation * * @static */ public static function uploadImage() { $contentINI = eZINI::instance('ezstyleeditor.ini'); $rep = $contentINI->variable('StyleEditor', 'ImageRepository'); if (is_numeric($rep)) { $contentNode = eZContentObjectTreeNode::fetch($rep); } else { $nodeID = eZURLAliasML::fetchNodeIDByPath($rep); $contentNode = eZContentObjectTreeNode::fetch($nodeID); } $upload = new eZContentUpload(); $location = false; if (is_object($contentNode)) { $location = $contentNode->attribute('node_id'); } $http = eZHTTPTool::instance(); $fileName = ''; if ($http->hasPostVariable('FileName')) { $fileName = $http->postVariable('FileName'); } $success = $upload->handleUpload($result, 'File', $location, false, $fileName); }
$canUpload = $parentNode instanceof eZContentObjectTreeNode && $parentNode->canCreate(); } $response = array(); if ($canUpload) { $siteaccess = eZSiteAccess::current(); $options['upload_dir'] = eZSys::cacheDirectory() . '/fileupload/'; $options['download_via_php'] = true; $options['param_name'] = "files"; $options['image_versions'] = array(); $options['max_file_size'] = $http->variable("upload_max_file_size", null); $uploadHandler = new UploadHandler($options, false); $data = $uploadHandler->post(false); foreach ($data[$options['param_name']] as $file) { $filePath = $options['upload_dir'] . $file->name; $behaviour = new ezpContentPublishingBehaviour(); $behaviour->isTemporary = true; $behaviour->disableAsynchronousPublishing = false; ezpContentPublishingBehaviour::setBehaviour($behaviour); $upload = new eZContentUpload(); $upload->handleLocalFile($response, $filePath, $parentNodeID, false); } $file = eZClusterFileHandler::instance($filePath); if ($file->exists()) { $file->delete(); } } else { $response = array('errors' => array('Not Allowed')); } header('Content-Type: application/json'); echo json_encode($response); eZExecution::cleanExit();