function check(&$msg, $url) { $service = 'session'; $action = 'start'; $secret = '@BATCH_PARTNER_ADMIN_SECRET@'; $partnerId = -1; $userId = 'xymon'; $type = 2; $getKS = "http://{$url}/api_v3/index.php?service={$service}&action={$action}&secret={$secret}&partnerId={$partnerId}&userId={$userId}&type={$type}&nocache"; try { $content = @file_get_contents($getKS); } catch (Exception $e) { $msg = $e->getMessage(); return false; } if (!$content) { $msg = "unable to get data"; return false; } $arr = null; if (!preg_match('/<result>([^<]+)<\\/result>/', $content, $arr)) { $msg = "invalid return data\n{$content}"; return false; } $ks = $arr[1]; $service = 'batchControl'; $action = 'getFullStatus'; $getStatus = "http://{$url}/api_v3/index.php?service={$service}&action={$action}&ks={$ks}&nocache"; // Load the XML source if (class_exists('DOMDocument') && class_exists('XSLTProcessor')) { $xml = new KDOMDocument(); $xml->load($getStatus); //file_put_contents('fullStatus.xml', $xml->saveXML()); $resultElements = $xml->getElementsByTagName("result"); $resultElement = $resultElements->item(0); $resultElement->setAttribute('timestamp', time()); $xsl = new KDOMDocument(); $xsl->load(dirname(__FILE__) . '/fullstatus.xsl'); // Configure the transformer $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); // attach the xsl rules $msg = $proc->transformToXML($xml); } else { $msg = "batches are ok\nXSL is required to parse the XML data."; } // echo "'$msg'\n"; // echo "-----------------------------------------------\n\n"; // echo $xml->saveHTML(); // exit; return true; }
/** * Allows you to add a metadata profile object and metadata profile file associated with Kaltura object type * * @action addFromFile * @param KalturaMetadataProfile $metadataProfile * @param file $xsdFile XSD metadata definition * @param file $viewsFile UI views definition * @return KalturaMetadataProfile * @throws MetadataErrors::METADATA_FILE_NOT_FOUND */ function addFromFileAction(KalturaMetadataProfile $metadataProfile, $xsdFile, $viewsFile = null) { $filePath = $xsdFile['tmp_name']; if (!file_exists($filePath)) { throw new KalturaAPIException(MetadataErrors::METADATA_FILE_NOT_FOUND, $xsdFile['name']); } // validates the xsd libxml_use_internal_errors(true); libxml_clear_errors(); $xml = new KDOMDocument(); if (!$xml->load($filePath)) { $errorMessage = kXml::getLibXmlErrorDescription(file_get_contents($xsdFile)); throw new KalturaAPIException(MetadataErrors::INVALID_METADATA_PROFILE_SCHEMA, $errorMessage); } libxml_clear_errors(); libxml_use_internal_errors(false); // must be validatebefore checking available searchable fields count $metadataProfile->validatePropertyNotNull('metadataObjectType'); kMetadataManager::validateMetadataProfileField($this->getPartnerId(), $xsdFile, false, $metadataProfile->metadataObjectType); $dbMetadataProfile = $metadataProfile->toInsertableObject(); $dbMetadataProfile->setStatus(KalturaMetadataProfileStatus::ACTIVE); $dbMetadataProfile->setPartnerId($this->getPartnerId()); $dbMetadataProfile->save(); $key = $dbMetadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_DEFINITION); kFileSyncUtils::moveFromFile($filePath, $key); if ($viewsFile && $viewsFile['size']) { $filePath = $viewsFile['tmp_name']; if (!file_exists($filePath)) { throw new KalturaAPIException(MetadataErrors::METADATA_FILE_NOT_FOUND, $viewsFile['name']); } $key = $dbMetadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_VIEWS); kFileSyncUtils::moveFromFile($filePath, $key); } kMetadataManager::parseProfileSearchFields($this->getPartnerId(), $dbMetadataProfile); $metadataProfile = new KalturaMetadataProfile(); $metadataProfile->fromObject($dbMetadataProfile); return $metadataProfile; }
/** * @param string $xmlPath * @param int $partnerId * @return array<CuePoint> */ public static function addFromXml($xmlPath, $partnerId) { if (!file_exists($xmlPath)) { throw new kCuePointException("XML file [{$xmlPath}] not found", kCuePointException::XML_FILE_NOT_FOUND); } $xml = new KDOMDocument(); libxml_use_internal_errors(true); libxml_clear_errors(); if (!$xml->load($xmlPath)) { $errorMessage = kXml::getLibXmlErrorDescription(file_get_contents($xmlPath)); throw new kCuePointException("XML [{$xmlPath}] is invalid:\n{$errorMessage}", kCuePointException::XML_INVALID); } $xsdPath = SchemaService::getSchemaPath(CuePointPlugin::getApiValue(CuePointSchemaType::INGEST_API)); libxml_clear_errors(); if (!$xml->schemaValidate($xsdPath)) { $errorMessage = kXml::getLibXmlErrorDescription(file_get_contents($xmlPath)); throw new kCuePointException("XML [{$xmlPath}] is invalid:\n{$errorMessage}", kCuePointException::XML_INVALID); } $pluginInstances = KalturaPluginManager::getPluginInstances('IKalturaCuePointXmlParser'); $scenes = new SimpleXMLElement(file_get_contents($xmlPath)); $cuePoints = array(); foreach ($scenes as $scene) { $cuePoint = null; foreach ($pluginInstances as $pluginInstance) { $cuePoint = $pluginInstance->parseXml($scene, $partnerId, $cuePoint); if ($cuePoint) { $cuePoint->save(); } } if ($cuePoint && $cuePoint instanceof CuePoint) { $cuePoints[] = $cuePoint; } } return $cuePoints; }
function writeCsproj() { $csprojDoc = new KDOMDocument(); $csprojDoc->formatOutput = true; $csprojDoc->load($this->_sourcePath . "/KalturaClient/KalturaClient.csproj"); $csprojXPath = new DOMXPath($csprojDoc); $csprojXPath->registerNamespace("m", "http://schemas.microsoft.com/developer/msbuild/2003"); $compileNodes = $csprojXPath->query("//m:ItemGroup/m:Compile/.."); $compileItemGroupElement = $compileNodes->item(0); foreach ($this->_csprojIncludes as $include) { $compileElement = $csprojDoc->createElement("Compile"); $compileElement->setAttribute("Include", str_replace("/", "\\", $include)); $compileItemGroupElement->appendChild($compileElement); } $this->addFile("KalturaClient/KalturaClient.csproj", $csprojDoc->saveXML(), false); }
/** * @param string $entryId * @param KalturaIdeticDistributionJobProviderData $providerData * @return DOMDocument */ public static function generateXML($entryId, KalturaIdeticDistributionJobProviderData $providerData) { $entry = entryPeer::retrieveByPKNoFilter($entryId); $mrss = kMrssManager::getEntryMrss($entry); if (!$mrss) { KalturaLog::err("No MRSS returned for entry [{$entryId}]"); return null; } $xml = new KDOMDocument(); if (!$xml->loadXML($mrss)) { KalturaLog::err("Could not load MRSS as XML for entry [{$entryId}]"); return null; } $xslPath = realpath(dirname(__FILE__) . '/../') . '/xml/submit.xsl'; if (!file_exists($xslPath)) { KalturaLog::err("XSL file not found [{$xslPath}]"); return null; } $xsl = new KDOMDocument(); $xsl->load($xslPath); // set variables in the xsl $varNodes = $xsl->getElementsByTagName('variable'); foreach ($varNodes as $varNode) { $nameAttr = $varNode->attributes->getNamedItem('name'); if (!$nameAttr) { continue; } $name = $nameAttr->value; if ($name && $providerData->{$name}) { $varNode->textContent = $providerData->{$name}; $varNode->appendChild($xsl->createTextNode($providerData->{$name})); KalturaLog::debug("Set variable [{$name}] to [{$providerData->{$name}}]"); } } $proc = new XSLTProcessor(); $proc->registerPHPFunctions(); $proc->importStyleSheet($xsl); $xml = $proc->transformToDoc($xml); if (!$xml) { KalturaLog::err("XML Transformation failed"); return null; } // TODO create validation XSD $xsdPath = realpath(dirname(__FILE__) . '/../') . '/xml/submit.xsd'; if (file_exists($xsdPath) && !$xml->schemaValidate($xsdPath)) { KalturaLog::err("Schema validation failed"); return null; } return $xml; }
/** * @param Metadata $metadata */ public static function onMetadataChanged(Metadata $metadata, $previousVersion) { if (!ContentDistributionPlugin::isAllowedPartner($metadata->getPartnerId())) { return true; } if ($metadata->getObjectType() != MetadataObjectType::ENTRY) { return true; } KalturaLog::log("Metadata [" . $metadata->getId() . "] for entry [" . $metadata->getObjectId() . "] changed"); $syncKey = $metadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA); $xmlPath = kFileSyncUtils::getLocalFilePathForKey($syncKey); if (!$xmlPath) { KalturaLog::log("Entry metadata xml not found"); return true; } $xml = new KDOMDocument(); $xml->load($xmlPath); $previousXml = null; if ($previousVersion) { $syncKey = $metadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA, $previousVersion); $xmlPath = kFileSyncUtils::getLocalFilePathForKey($syncKey); if ($xmlPath) { $previousXml = new KDOMDocument(); $previousXml->load($xmlPath); } else { KalturaLog::log("Entry metadata previous version xml not found"); } } $entryDistributions = EntryDistributionPeer::retrieveByEntryId($metadata->getObjectId()); foreach ($entryDistributions as $entryDistribution) { if ($entryDistribution->getStatus() != EntryDistributionStatus::QUEUED && $entryDistribution->getStatus() != EntryDistributionStatus::PENDING && $entryDistribution->getStatus() != EntryDistributionStatus::READY) { continue; } $distributionProfileId = $entryDistribution->getDistributionProfileId(); $distributionProfile = DistributionProfilePeer::retrieveByPK($distributionProfileId); if (!$distributionProfile) { KalturaLog::err("Entry distribution [" . $entryDistribution->getId() . "] profile [{$distributionProfileId}] not found"); continue; } $distributionProvider = $distributionProfile->getProvider(); if (!$distributionProvider) { KalturaLog::err("Entry distribution [" . $entryDistribution->getId() . "] provider [" . $distributionProfile->getProviderType() . "] not found"); continue; } if ($entryDistribution->getStatus() == EntryDistributionStatus::PENDING || $entryDistribution->getStatus() == EntryDistributionStatus::QUEUED) { $validationErrors = $distributionProfile->validateForSubmission($entryDistribution, DistributionAction::SUBMIT); $entryDistribution->setValidationErrorsArray($validationErrors); $entryDistribution->save(); if ($entryDistribution->getStatus() == EntryDistributionStatus::QUEUED) { if ($entryDistribution->getDirtyStatus() != EntryDistributionDirtyStatus::SUBMIT_REQUIRED) { self::submitAddEntryDistribution($entryDistribution, $distributionProfile); } } continue; } if ($entryDistribution->getStatus() == EntryDistributionStatus::READY) { if ($entryDistribution->getDirtyStatus() == EntryDistributionDirtyStatus::UPDATE_REQUIRED) { KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] already flaged for updating"); // continue; } if (!$distributionProvider->isUpdateEnabled()) { KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] provider [" . $distributionProvider->getName() . "] does not support update"); continue; } $updateRequiredMetadataXPaths = $distributionProvider->getUpdateRequiredMetadataXPaths($distributionProfileId); $updateRequired = false; foreach ($updateRequiredMetadataXPaths as $updateRequiredMetadataXPath) { $xPath = new DOMXpath($xml); $newElements = $xPath->query($updateRequiredMetadataXPath); $oldElements = null; if ($previousXml) { $xPath = new DOMXpath($previousXml); $oldElements = $xPath->query($updateRequiredMetadataXPath); } if (is_null($newElements) && is_null($oldElements)) { continue; } if (is_null($newElements) xor is_null($oldElements)) { $updateRequired = true; } elseif ($newElements->length == $oldElements->length) { for ($index = 0; $index < $newElements->length; $index++) { $newValue = $newElements->item($index)->textContent; $oldValue = $oldElements->item($index)->textContent; if ($newValue != $oldValue) { $updateRequired = true; break; } } } if ($updateRequired) { break; } } $validationErrors = $distributionProfile->validateForSubmission($entryDistribution, DistributionAction::UPDATE); $entryDistribution->setValidationErrorsArray($validationErrors); $entryDistribution->save(); if (!$updateRequired) { KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] update not required"); continue; } if (!count($validationErrors) && $distributionProfile->getUpdateEnabled() == DistributionProfileActionStatus::AUTOMATIC) { self::submitUpdateEntryDistribution($entryDistribution, $distributionProfile); } else { KalturaLog::log("Entry distribution [" . $entryDistribution->getId() . "] should not be updated automatically"); $entryDistribution->setDirtyStatus(EntryDistributionDirtyStatus::UPDATE_REQUIRED); $entryDistribution->save(); continue; } } } return true; }
public function loadProperties(KalturaDistributionJobData $distributionJobData, KalturaGenericDistributionProfile $distributionProfile, $action) { $actionName = self::$actionAttributes[$action]; $genericProviderAction = GenericDistributionProviderActionPeer::retrieveByProviderAndAction($distributionProfile->genericProviderId, $action); if (!$genericProviderAction) { KalturaLog::err("Generic provider [{$distributionProfile->genericProviderId}] action [{$actionName}] not found"); return; } if (!$distributionJobData->entryDistribution) { KalturaLog::err("Entry Distribution object not provided"); return; } if (!$distributionProfile->{$actionName}->protocol) { $distributionProfile->{$actionName}->protocol = $genericProviderAction->getProtocol(); } if (!$distributionProfile->{$actionName}->serverUrl) { $distributionProfile->{$actionName}->serverUrl = $genericProviderAction->getServerAddress(); } if (!$distributionProfile->{$actionName}->serverPath) { $distributionProfile->{$actionName}->serverPath = $genericProviderAction->getRemotePath(); } if (!$distributionProfile->{$actionName}->username) { $distributionProfile->{$actionName}->username = $genericProviderAction->getRemoteUsername(); } if (!$distributionProfile->{$actionName}->password) { $distributionProfile->{$actionName}->password = $genericProviderAction->getRemotePassword(); } if (!$distributionProfile->{$actionName}->ftpPassiveMode) { $distributionProfile->{$actionName}->ftpPassiveMode = $genericProviderAction->getFtpPassiveMode(); } if (!$distributionProfile->{$actionName}->httpFieldName) { $distributionProfile->{$actionName}->httpFieldName = $genericProviderAction->getHttpFieldName(); } if (!$distributionProfile->{$actionName}->httpFileName) { $distributionProfile->{$actionName}->httpFileName = $genericProviderAction->getHttpFileName(); } $entry = entryPeer::retrieveByPKNoFilter($distributionJobData->entryDistribution->entryId); if (!$entry) { KalturaLog::err("Entry [" . $distributionJobData->entryDistribution->entryId . "] not found"); return; } $mrss = kMrssManager::getEntryMrss($entry); if (!$mrss) { KalturaLog::err("MRSS not returned for entry [" . $entry->getId() . "]"); return; } $xml = new KDOMDocument(); if (!$xml->loadXML($mrss)) { KalturaLog::err("MRSS not is not valid XML:\n{$mrss}\n"); return; } $key = $genericProviderAction->getSyncKey(GenericDistributionProviderAction::FILE_SYNC_DISTRIBUTION_PROVIDER_ACTION_MRSS_TRANSFORMER); if (kFileSyncUtils::fileSync_exists($key)) { $xslPath = kFileSyncUtils::getLocalFilePathForKey($key); if ($xslPath) { $xsl = new KDOMDocument(); $xsl->load($xslPath); // set variables in the xsl $varNodes = $xsl->getElementsByTagName('variable'); foreach ($varNodes as $varNode) { $nameAttr = $varNode->attributes->getNamedItem('name'); if (!$nameAttr) { continue; } $name = $nameAttr->value; if ($name && $distributionJobData->{$name}) { $varNode->textContent = $distributionJobData->{$name}; $varNode->appendChild($xsl->createTextNode($distributionJobData->{$name})); } } $proc = new XSLTProcessor(); $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions()); $proc->importStyleSheet($xsl); $xml = $proc->transformToDoc($xml); if (!$xml) { KalturaLog::err("Transform returned false"); return; } } } $key = $genericProviderAction->getSyncKey(GenericDistributionProviderAction::FILE_SYNC_DISTRIBUTION_PROVIDER_ACTION_MRSS_VALIDATOR); if (kFileSyncUtils::fileSync_exists($key)) { $xsdPath = kFileSyncUtils::getLocalFilePathForKey($key); if ($xsdPath && !$xml->schemaValidate($xsdPath)) { KalturaLog::err("Inavlid XML:\n" . $xml->saveXML()); KalturaLog::err("Schema [{$xsdPath}]:\n" . file_get_contents($xsdPath)); return; } } $this->xml = $xml->saveXML(); $key = $genericProviderAction->getSyncKey(GenericDistributionProviderAction::FILE_SYNC_DISTRIBUTION_PROVIDER_ACTION_RESULTS_TRANSFORMER); if (kFileSyncUtils::fileSync_exists($key)) { $this->resultParseData = kFileSyncUtils::file_get_contents($key, true, false); } $this->resultParserType = $genericProviderAction->getResultsParser(); }
/** * @param string $xsdPath * @param string $appInfoField * @param string $appInfoValue * @return array of xPaths */ public static function findXpathsByAppInfo($xsdPath, $appInfoField, $appInfoValue, $isPath = true) { $xsd = new KDOMDocument(); if ($isPath) { $xsd->load($xsdPath); } else { $xsd->loadXML($xsdPath); } $xPaths = array(); $appInfos = $xsd->getElementsByTagName('appinfo'); foreach ($appInfos as $appInfo) { $fields = $appInfo->getElementsByTagName($appInfoField); $found = false; foreach ($fields as $field) { if ($field->nodeValue == $appInfoValue) { $found = true; } } if (!$found) { continue; } $name = self::getXsdElementName($appInfo); $type = self::getXsdNodeType($appInfo); $xPath = self::getXsdXpath($appInfo); $data = array(); if ($name) { $data['name'] = $name; } if ($type) { $data['type'] = $type; } foreach ($appInfo->childNodes as $childNode) { if ($childNode->nodeType == XML_TEXT_NODE || $childNode->nodeType == XML_COMMENT_NODE) { continue; } $data[$childNode->localName] = $childNode->nodeValue; } $xPaths[$xPath] = $data; } return $xPaths; }
/** * Parse the XML and update the list of search values * * @param Metadata $metadata * @param array $searchValues * * @return array */ public static function getDataSearchValues(Metadata $metadata, $searchValues = array()) { KalturaLog::debug("Parsing metadata [" . $metadata->getId() . "] search values"); $searchTexts = array(); if (isset($searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)])) { foreach ($searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)] as $DataSerachValue) { $searchTexts[] = $DataSerachValue; } } $key = $metadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA); $xmlPath = kFileSyncUtils::getLocalFilePathForKey($key); try { $xml = new KDOMDocument(); $xml->load($xmlPath); $xPath = new DOMXPath($xml); } catch (Exception $ex) { KalturaLog::err('Could not load metadata xml [' . $xmlPath . '] - ' . $ex->getMessage()); return ''; } $profileFields = MetadataProfileFieldPeer::retrieveActiveByMetadataProfileId($metadata->getMetadataProfileId()); $searchItems = array(); $textItems = array(); foreach ($profileFields as $profileField) { /* @var $profileField MetadataProfileField */ $nodes = $xPath->query($profileField->getXpath()); if (!$nodes->length) { continue; } if ($profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_DATE || $profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_INT) { $node = $nodes->item(0); if (!isset($searchValues[MetadataPlugin::SPHINX_DYNAMIC_ATTRIBUTES])) { $searchValues[MetadataPlugin::SPHINX_DYNAMIC_ATTRIBUTES] = array(); } $fieldName = MetadataPlugin::getSphinxFieldName($profileField->getId()); $searchValues[MetadataPlugin::SPHINX_DYNAMIC_ATTRIBUTES][$fieldName] = intval($node->nodeValue); continue; } $searchItemValues = array(); foreach ($nodes as $node) { $searchItemValues[] = $node->nodeValue; } if (!count($searchItemValues)) { continue; } if ($profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_TEXT || $profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_METADATA_OBJECT) { $textItems[] = implode(' ', $searchItemValues); $searchItems[$profileField->getId()] = array(); foreach ($searchItemValues as $searchItemValue) { if (iconv_strlen($searchItemValue, 'UTF-8') >= 128) { continue; } $searchItems[$profileField->getId()][] = $searchItemValue; } if ($profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_METADATA_OBJECT && $profileField->getRelatedMetadataProfileId()) { $subMetadataProfileId = $profileField->getRelatedMetadataProfileId(); $subMetadataProfile = MetadataProfilePeer::retrieveByPK($subMetadataProfileId); if (!$subMetadataProfile) { KalturaLog::err('Sub metadata profile ' . $subMetadataProfileId . ' was not found'); continue; } $subMetadataObjects = MetadataPeer::retrieveByObjects($subMetadataProfileId, $subMetadataProfile->getObjectType(), $searchItemValues); foreach ($subMetadataObjects as $subMetadataObject) { /** @var Metadata $subMetadataObject */ KalturaLog::debug("Found metadata object for profile {$subMetadataProfileId} and id {$subMetadataObject->getObjectId()}, extracting search data"); $subSearchTextsResult = self::getDataSearchValues($subMetadataObject); $subSearchTexts = $subSearchTextsResult[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)]; foreach ($subSearchTexts as $subSearchText) { $searchTexts[] = $subSearchText; } } } } else { $searchItems[$profileField->getId()] = $searchItemValues; } } foreach ($searchItems as $key => $searchItem) { foreach ($searchItem as $searchPhrase) { $searchTexts[] = MetadataPlugin::PLUGIN_NAME . '_' . "{$key} {$searchPhrase} " . kMetadataManager::SEARCH_TEXT_SUFFIX . '_' . $key; } } if (count($textItems)) { $searchTexts['text'] = MetadataSearchFilter::createSphinxSearchCondition($metadata->getPartnerId(), implode(' ', $textItems), true); } $ret = array(); foreach ($searchTexts as $index => $value) { if (is_int($index)) { $ret[$index] = $value; } } if (isset($searchTexts['text'])) { $ret['text'] = $searchTexts['text']; } $searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)] = $ret; return $searchValues; }
/** * @param KalturaDistributionJobData $data * @param KalturaExampleDistributionProfile $distributionProfile * @param KalturaExampleDistributionJobProviderData $providerData */ protected function handleUpdate(KalturaDistributionJobData $data, KalturaExampleDistributionProfile $distributionProfile, KalturaExampleDistributionJobProviderData $providerData) { $entryId = $data->entryDistribution->entryId; $partnerId = $distributionProfile->partnerId; $entry = $this->getEntry($partnerId, $entryId); $feed = new KDOMDocument(); $feed->load($this->updateXmlTemplate); $feed->documentElement->setAttribute('mediaId', $data->remoteId); $nodes = array('title' => 'name', 'description' => 'description', 'width' => 'width', 'height' => 'height'); foreach ($nodes as $nodeName => $entryAttribute) { $nodeElements = $feed->getElementsByTagName($nodeName); foreach ($nodeElements as $nodeElement) { $nodeElement->textContent = $entry->{$entryAttribute}; } } // get the first asset id $thumbAssetIds = explode(',', $data->entryDistribution->thumbAssetIds); $thumbAssetId = reset($thumbAssetIds); $thumbElements = $feed->getElementsByTagName('thumb'); $thumbElement = reset($thumbElements); $thumbElement->textContent = $this->getThumbAssetUrl($thumbAssetId); $videosElements = $feed->getElementsByTagName('videos'); $videosElement = reset($videosElements); $flavorAssets = $this->getFlavorAssets($partnerId, $data->entryDistribution->flavorAssetIds); KBatchBase::impersonate($partnerId); foreach ($flavorAssets as $flavorAsset) { $url = $this->getFlavorAssetUrl($flavorAsset->id); $videoElement = $feed->createElement('video'); $videoElement->textContent = $url; $videosElement->appendChild($videoElement); } KBatchBase::unimpersonate(); $localFile = tempnam(sys_get_temp_dir(), 'example-update-'); $feed->save($localFile); // loads ftp manager $engineOptions = isset(KBatchBase::$taskConfig->engineOptions) ? KBatchBase::$taskConfig->engineOptions->toArray() : array(); $ftpManager = kFileTransferMgr::getInstance(kFileTransferMgrType::FTP, $engineOptions); $ftpManager->login(self::FTP_SERVER_URL, $distributionProfile->username, $distributionProfile->password); // put the XML file on the FTP $remoteFile = $entryId . '.xml'; $ftpManager->putFile($remoteFile, $localFile); return true; }
protected function executeImpl(kshow $kshow, entry &$entry) { $this->res = ""; $likuser_id = $this->getLoggedInUserId(); // if we allow multiple rouchcuts - there is no reason for one suer to override someone else's thumbnail if ($this->allowMultipleRoughcuts()) { if ($likuser_id != $entry->getKuserId()) { // ERROR - attempting to update an entry which doesnt belong to the user return "<xml>!!</xml>"; //$this->securityViolation( $kshow->getId() ); } } $debug = @$_GET["debug"]; /* $kshow_id = @$_GET["kshow_id"]; $debug = @$_GET["debug"]; $this->kshow_id = $kshow_id; if ( $kshow_id == NULL || $kshow_id == 0 ) return; $kshow = kshowPeer::retrieveByPK( $kshow_id ); if ( ! $kshow ) { $this->res = "No kshow " . $kshow_id ; return; } // is the logged-in-user is not an admin or the producer - check if show can be published $likuser_id = $this->getLoggedInUserId(); $viewer_type = myKshowUtils::getViewerType($kshow, $likuser_id); if ( $viewer_type != KshowKuser::KSHOWKUSER_VIEWER_PRODUCER && ( ! $kshow->getCanPublish() ) ) { // ERROR - attempting to publish a non-publishable show return "<xml>!</xml>";//$this->securityViolation( $kshow->getId() ); } // ASSUME - the kshow & roughcut already exist $show_entry_id = $kshow->getShowEntryId(); $roughcut = entryPeer::retrieveByPK( $show_entry_id ); $roughcut = entryPeer::retrieveByPK( $entry_id ); if ( ! $roughcut) { $this->res = "No roughcut for kshow " . $kshow->getId() ; return; } */ // echo "for entry: $show_entry_id current thumb path: " . $entry->getThumbnail() ; $entry->setThumbnail(".jpg"); $entry->setCreateThumb(false); $entry->save(); //$thumb_data = $_REQUEST["ThumbData"]; if (isset($HTTP_RAW_POST_DATA)) { $thumb_data = $HTTP_RAW_POST_DATA; } else { $thumb_data = file_get_contents("php://input"); } // $thumb_data = $GLOBALS["HTTP_RAW_POST_DATA"]; $thumb_data_size = strlen($thumb_data); $bigThumbPath = myContentStorage::getFSContentRootPath() . $entry->getBigThumbnailPath(); kFile::fullMkdir($bigThumbPath); kFile::setFileContent($bigThumbPath, $thumb_data); $path = myContentStorage::getFSContentRootPath() . $entry->getThumbnailPath(); kFile::fullMkdir($path); myFileConverter::createImageThumbnail($bigThumbPath, $path); $roughcutPath = myContentStorage::getFSContentRootPath() . $entry->getDataPath(); $xml_doc = new KDOMDocument(); $xml_doc->load($roughcutPath); if (myMetadataUtils::updateThumbUrl($xml_doc, $entry->getBigThumbnailUrl())) { $xml_doc->save($roughcutPath); } $this->res = $entry->getBigThumbnailUrl(); }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser) { $kshowId = $this->getP("kshow_id"); $numberOfVersions = $this->getP("number_of_versions", 5); // must be int and not more than 50 $numberOfVersions = (int) $numberOfVersions; $numberOfVersions = min($numberOfVersions, 50); $kshow = kshowPeer::retrieveByPK($kshowId); if (!$kshow) { $this->addError(APIErrors::KSHOW_DOES_NOT_EXISTS); return; } $showEntry = $kshow->getShowEntry(); if (!$showEntry) { $this->addError(APIErrors::ROUGHCUT_NOT_FOUND); return; } $sync_key = $showEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); $showEntryDataPath = kFileSyncUtils::getLocalFilePathForKey($sync_key); $versionsInfoFilePath = $showEntryDataPath . '.info'; $lastVersionDoc = new KDOMDocument(); $lastVersionDoc->loadXML(kFileSyncUtils::file_get_contents($sync_key, true, false)); $lastVersion = myContentStorage::getVersion($showEntryDataPath); // check if we need to refresh the data in the info file $refreshInfoFile = true; if (file_exists($versionsInfoFilePath)) { $versionsInfoDoc = new KDOMDocument(); $versionsInfoDoc->load($versionsInfoFilePath); $lastVersionInInfoFile = kXml::getLastElementAsText($versionsInfoDoc, "ShowVersion"); if ($lastVersionInInfoFile && $lastVersion == $lastVersionInInfoFile) { $refreshInfoFile = false; } else { $refreshInfoFile = true; } } else { $refreshInfoFile = true; } // refresh or create the data in the info file if ($refreshInfoFile) { $versionsInfoDoc = new KDOMDocument(); $xmlElement = $versionsInfoDoc->createElement("xml"); // start from the first edited version (100001) and don't use 100000 for ($i = myContentStorage::MIN_OBFUSCATOR_VALUE + 1; $i <= $lastVersion; $i++) { $version_sync_key = $showEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $i); if (kFileSyncUtils::file_exists($version_sync_key, false)) { $xmlContent = kFileSyncUtils::file_get_contents($version_sync_key); //echo "[" . htmlspecialchars( $xmlContent ) . "]<br>"; $xmlDoc = new KDOMDocument(); $xmlDoc->loadXML($xmlContent); $elementToCopy = kXml::getFirstElement($xmlDoc, "MetaData"); //echo "[$i]"; $elementCloned = $elementToCopy->cloneNode(true); $elementImported = $versionsInfoDoc->importNode($elementCloned, true); $xmlElement->appendChild($elementImported); } } $versionsInfoDoc->appendChild($xmlElement); kFile::setFileContent($versionsInfoFilePath, $versionsInfoDoc->saveXML()); // FileSync OK - created a temp file on DC's disk } $metadataNodes = $versionsInfoDoc->getElementsByTagName("MetaData"); $count = 0; $versionsInfo = array(); for ($i = $metadataNodes->length - 1; $i >= 0; $i--) { $metadataNode = $metadataNodes->item($i); $node = kXml::getFirstElement($metadataNode, "ShowVersion"); $showVersion = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "PuserId"); $puserId = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "ScreenName"); $screenName = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "UpdatedAt"); $updatedAt = $node ? $node->nodeValue : ""; $versionsInfo[] = array("version" => $showVersion, "puserId" => $puserId, "screenName" => $screenName, "updatedAt" => $updatedAt); $count++; if ($count >= $numberOfVersions) { break; } } $this->addMsg("show_versions", $versionsInfo); }
<?php $downloadUrl = 'http://' . kConf::get('www_host') . "/api_v3/index.php/service/schema/action/serve/type/{$schemaType}/name/{$schemaType}.xsd"; echo "Download URL: <a href=\"{$downloadUrl};\" target=\"_blank\">{$downloadUrl}</a><br/>\n"; $schemaPath = SchemaService::getSchemaPath($schemaType); $xslPath = dirname(__FILE__) . '/xsl/type.xsl'; // Load the XML source $xml = new KDOMDocument(); $xml->load($schemaPath); if ($xml->firstChild->hasAttribute('version')) { echo "Version: " . $xml->firstChild->getAttribute('version') . "<br/>\n"; } $xsl = new KDOMDocument(); $xsl->load($xslPath); // Configure the transformer $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); // attach the xsl rules echo "<br/>\n"; echo $proc->transformToXML($xml);
public function handle() { $this->tempDirectory = sys_get_temp_dir(); if (!is_dir($this->tempDirectory)) { KalturaLog::err('Missing temporary directory'); return false; } // check prerequisites $checkConfig = $this->checkConfig(); if (!$checkConfig) { KalturaLog::err('Missing required configurations'); return false; } $this->fileTransferMgr = DropFolderBatchUtils::getFileTransferManager($this->dropFolder); if (!$this->fileTransferMgr) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::INTERNAL_ERROR; $this->dropFolderFile->errorDescription = 'Internal server error - cannot initiate file transfer manager'; KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $xmlPath = $this->getLocalXmlFilePath(); if (!$xmlPath) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::ERROR_READING_FILE; $this->dropFolderFile->errorDescription = 'Cannot read file at path [' . $this->dropFolder->path . '/' . $this->dropFolderFile->fileName . ']'; KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $xmlDoc = new KDOMDocument(); $xmlDoc->load($xmlPath); if (!$xmlDoc) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::ERROR_READING_FILE; $this->dropFolderFile->errorDescription = "Cannot parse XML file at [{$xmlPath}]"; KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $localResources = $xmlDoc->getElementsByTagName(self::DROP_FOLDER_RESOURCE_NODE_NAME); if (!$localResources) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::ERROR_READING_FILE; $this->dropFolderFile->errorDescription = "Cannot parse XML file at [{$xmlPath}]"; KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $replaceResources = array(); $localResourcesLength = $localResources->length; foreach ($localResources as $local) { // already have drop folder file id if (!is_null($this->getDropFolderFileId($local))) { continue; } // replacement/modification of $local must not happen inside this foreach loop $dropFolderFileId = $this->checkFileExists($local); if (is_null($dropFolderFileId)) { KalturaLog::debug('Some required files do not exist in the drop folder - changing status to WAITING'); $this->dropFolderFile->status = KalturaDropFolderFileStatus::WAITING; KalturaLog::debug('Changing status to WAITING'); $this->updateDropFolderFile(); return false; } $localVerified = $this->verifyLocalResource($local); if (!$localVerified) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; // error code and description already set KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $replaceResources[] = array($local, $dropFolderFileId); } foreach ($replaceResources as $replace) { $this->replaceResource($replace[0], $replace[1], $xmlDoc); } // create a temporary XML file from the modified $xmlDoc $tempFile = $this->tempDirectory . DIRECTORY_SEPARATOR . uniqid() . '_' . $this->dropFolderFile->fileName; $xmlDoc->save($tempFile); $tempFileRealPath = realpath($tempFile); if (!$tempFileRealPath || !is_file($tempFileRealPath)) { $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::ERROR_WRITING_TEMP_FILE; $this->dropFolderFile->errorDescription = "Error writing temporary file [{$tempFileRealPath}]"; KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); return false; } $conversionProfile = $this->getConversionProfile(); // add bulk upload of type KalturaBulkUploadType::DROP_FOLDER_XML try { $this->impersonate($this->dropFolderFile->partnerId); $this->kClient->bulkUpload->add($conversionProfile->id, $tempFileRealPath, KalturaBulkUploadType::DROP_FOLDER_XML, $this->uploadedBy, $this->dropFolderFile->fileName); $this->unimpersonate(); } catch (Exception $e) { $this->unimpersonate(); $this->dropFolderFile->status = KalturaDropFolderFileStatus::ERROR_HANDLING; $this->dropFolderFile->errorCode = KalturaDropFolderFileErrorCode::ERROR_ADDING_BULK_UPLOAD; $this->dropFolderFile->errorDescription = 'Error adding bulk upload - ' . $e->getMessage(); KalturaLog::err($this->dropFolderFile->errorDescription); $this->updateDropFolderFile(); KalturaLog::err($this->dropFolderFile->errorDescription); return false; } //delete the temporary file @unlink($tempFileRealPath); $dropFolderFilePlugin = KalturaDropFolderClientPlugin::get($this->kClient); $dropFolderFilePlugin->dropFolderFile->updateStatus($this->dropFolderFile->id, KalturaDropFolderFileStatus::HANDLED); KalturaLog::debug('Drop folder file [' . $this->dropFolderFile->id . '] handled successfully'); return true; // file handled }
/** * Parse the XML and update the list of search values * * @param Metadata $metadata * @param array $searchValues * * @return array */ public static function getDataSearchValues(Metadata $metadata, $searchValues = array()) { KalturaLog::debug("Parsing metadata [" . $metadata->getId() . "] search values"); $searchTexts = array(); if (isset($searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)])) { foreach ($searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)] as $DataSerachValue) { $searchTexts[] = $DataSerachValue; } } $key = $metadata->getSyncKey(Metadata::FILE_SYNC_METADATA_DATA); $xmlPath = kFileSyncUtils::getLocalFilePathForKey($key); try { $xml = new KDOMDocument(); $xml->load($xmlPath); $xPath = new DOMXPath($xml); } catch (Exception $ex) { KalturaLog::err('Could not load metadata xml [' . $xmlPath . '] - ' . $ex->getMessage()); return ''; } $profileFields = MetadataProfileFieldPeer::retrieveActiveByMetadataProfileId($metadata->getMetadataProfileId()); $searchItems = array(); $textItems = array(); foreach ($profileFields as $profileField) { /* @var $profileField MetadataProfileField */ $nodes = $xPath->query($profileField->getXpath()); if (!$nodes->length) { continue; } if ($profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_DATE || $profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_INT) { foreach ($nodes as $node) { if (!is_null($profileField->getSearchIndex())) { $searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPENDER_FIELD_INT) . $profileField->getSearchIndex()] = $node->nodeValue; } break; } continue; } $searchItemValues = array(); foreach ($nodes as $node) { $searchItemValues[] = $node->nodeValue; } if (!count($searchItemValues)) { continue; } if ($profileField->getType() == MetadataSearchFilter::KMC_FIELD_TYPE_TEXT) { $textItems[] = implode(' ', $searchItemValues); $searchItems[$profileField->getId()] = array(); foreach ($searchItemValues as $searchItemValue) { if (iconv_strlen($searchItemValue, 'UTF-8') >= 128) { continue; } $searchItems[$profileField->getId()][] = $searchItemValue; } } else { $searchItems[$profileField->getId()] = $searchItemValues; } } foreach ($searchItems as $key => $searchItem) { foreach ($searchItem as $searchPhrase) { $searchTexts[] = MetadataPlugin::PLUGIN_NAME . '_' . "{$key} {$searchPhrase} " . kMetadataManager::SEARCH_TEXT_SUFFIX . '_' . $key; } } if (count($textItems)) { if (!isset($searchTexts['text'])) { $searchTexts['text'] = MetadataPlugin::PLUGIN_NAME . '_text'; } $searchTexts['text'] .= ' ' . implode(' ', $textItems); $searchTexts['text'] .= ' ' . kMetadataManager::SEARCH_TEXT_SUFFIX . '_text'; } $ret = array(); foreach ($searchTexts as $index => $value) { if (is_int($index)) { $ret[$index] = $value; } } if (isset($searchTexts['text'])) { $ret['text'] = $searchTexts['text']; } $searchValues[MetadataPlugin::getSphinxFieldName(MetadataPlugin::SPHINX_EXPANDER_FIELD_DATA)] = $ret; return $searchValues; }