public function checkIsLive($url)
 {
     KalturaLog::info('url to check:' . $url);
     $parts = parse_url($url);
     parse_str($parts['query'], $query);
     $token = $query[$this->getParamName()];
     $data = $this->urlExists($url, array($this->getHdsManifestContentType()));
     if (!$data) {
         KalturaLog::Info("URL [{$url}] returned no valid data. Exiting.");
         return false;
     }
     KalturaLog::info('Velocix HDS manifest data:' . $data);
     $dom = new KDOMDocument();
     $dom->loadXML($data);
     $element = $dom->getElementsByTagName('baseURL')->item(0);
     if (!$element) {
         KalturaLog::Info("No base url was given");
         return false;
     }
     $baseUrl = $element->nodeValue;
     foreach ($dom->getElementsByTagName('media') as $media) {
         $href = $media->getAttribute('href');
         $streamUrl = $baseUrl . $href;
         $streamUrl .= $token ? '?' . $this->getParamName() . "={$token}" : '';
         if ($this->urlExists($streamUrl, array(), '0-0') !== false) {
             KalturaLog::info('is live:' . $streamUrl);
             return true;
         }
     }
     return false;
 }
 public function apply(KalturaRelatedFilter $filter, KalturaObject $parentObject)
 {
     $filterProperty = $this->filterProperty;
     $parentProperty = $this->parentProperty;
     KalturaLog::debug("Mapping XPath {$parentProperty} to " . get_class($filter) . "::{$filterProperty}");
     if (!$parentObject instanceof KalturaMetadata) {
         throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_TYPE, get_class($parentObject));
     }
     if (!property_exists($filter, $filterProperty)) {
         throw new KalturaAPIException(KalturaErrors::PROPERTY_IS_NOT_DEFINED, $filterProperty, get_class($filter));
     }
     $xml = $parentObject->xml;
     $doc = new KDOMDocument();
     $doc->loadXML($xml);
     $xpath = new DOMXPath($doc);
     $metadataElements = $xpath->query($parentProperty);
     if ($metadataElements->length == 1) {
         $filter->{$filterProperty} = $metadataElements->item(0)->nodeValue;
     } elseif ($metadataElements->length > 1) {
         $values = array();
         foreach ($metadataElements as $element) {
             $values[] = $element->nodeValue;
         }
         $filter->{$filterProperty} = implode(',', $values);
     } elseif (!$this->allowNull) {
         return false;
     }
     return true;
 }
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;
}
예제 #4
0
 public static function validateXsdData($xsdData, &$errorMessage)
 {
     // validates the xsd
     libxml_use_internal_errors(true);
     libxml_clear_errors();
     $xml = new KDOMDocument();
     if (!$xml->loadXML($xsdData)) {
         $errorMessage = kXml::getLibXmlErrorDescription($xsdData);
         return false;
     }
     libxml_clear_errors();
     libxml_use_internal_errors(false);
     return true;
 }
예제 #5
0
 public function checkIsLive($url)
 {
     $data = $this->urlExists($url, array('video/f4m'));
     if (is_bool($data)) {
         return $data;
     }
     $element = new KDOMDocument();
     $element->loadXML($data);
     $streamType = $element->getElementsByTagName('streamType')->item(0);
     if ($streamType->nodeValue == 'live') {
         return true;
     }
     return false;
 }
 public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser)
 {
     if (!$puser_kuser) {
         $this->addError(APIErrors::INVALID_USER_ID, $puser_id);
         return;
     }
     $entry_id = $this->getPM("entry_id");
     $entry = entryPeer::retrieveByPK($entry_id);
     // TODO - verify the user is allowed to modify the entry
     $source_entry_id = $this->getP("source_entry_id");
     if ($source_entry_id) {
         $source_entry = entryPeer::retrieveByPK($source_entry_id);
         if (!$source_entry) {
             return;
         }
     } else {
         $source_entry = $entry;
     }
     $time_offset = $this->getP("time_offset", -1);
     if (!myEntryUtils::createThumbnailFromEntry($entry, $source_entry, $time_offset)) {
         $this->addError(APIErrors::INVALID_ENTRY_TYPE, "ENTRY_TYPE_MEDIACLIP");
         return;
     }
     if ($entry->getType() == entryType::MIX) {
         /*			
         		$roughcutPath = myContentStorage::getFSContentRootPath() . $entry->getDataPath(); // replaced__getDataPath
         		$xml_doc = new KDOMDocument();
         		$xml_doc->load( $roughcutPath );
         	
         		if (myMetadataUtils::updateThumbUrl($xml_doc, $entry->getThumbnailUrl()))
         			$xml_doc->save($roughcutPath);
         */
         $sync_key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA);
         $xml_doc = new KDOMDocument();
         $xml_doc->loadXML(kFileSyncUtils::file_get_contents($sync_key));
         if (myMetadataUtils::updateThumbUrl($xml_doc, $entry->getThumbnailUrl())) {
             $entry->setMetadata(null, $xml_doc->saveXML(), true, null, null);
             //$entry->getVersion() );
         }
         myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE_THUMBNAIL, $entry);
     }
     $wrapper = objectWrapperBase::getWrapperClass($entry, objectWrapperBase::DETAIL_LEVEL_DETAILED);
     $wrapper->removeFromCache("entry", $entry->getId());
     $this->addMsg("entry", $wrapper);
 }
 /**
  * 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;
 }
예제 #8
0
 public static function modifiedByKeditor($content)
 {
     $xml_doc = new KDOMDocument();
     $xml_doc->loadXML($content);
     $xpath = new DOMXPath($xml_doc);
     $metadata_elem = $xpath->query("//Metadata");
     $modified_by_keditor_list = $metadata_elem->getElementsByTagName("Modified");
     if ($modified_by_keditor_list != null && $modified_by_keditor_list->length > 0) {
         $modified_by_keditor = $modified_by_keditor_list->item(0)->nodeValue;
         return $content;
         //$modified_by_keditor->setValue
     } else {
         $newTextNode = $xml_doc->createTextNode("keditor");
         $modified = $xml_doc->createElement("Modified");
         //, "keditor" );
         $modified->appendChild($newTextNode);
         $metadata_elem->appendChild($modified);
     }
     return $xml_doc->saveXML();
 }
예제 #9
0
파일: AvnFeed.php 프로젝트: DBezemer/server
 /**
  * @param string $xsd
  * @return array
  */
 protected function getAvnCategoriesFromXsd($xsd)
 {
     $categories = array();
     $doc = new KDOMDocument();
     $doc->loadXML($xsd);
     $xpath = new DOMXPath($doc);
     $xpath->registerNamespace('xsd', 'http://www.w3.org/2001/XMLSchema');
     $categoryNodes = $xpath->query("//xsd:element[@name='AVNCategory']/xsd:simpleType/xsd:restriction[@base='listType']/xsd:enumeration/@value");
     foreach ($categoryNodes as $categoryNode) {
         $categories[] = $categoryNode->nodeValue;
     }
     return $categories;
 }
예제 #10
0
 /**
  * @param string $xml
  * @param string $xslt
  * @param array $xsltParams
  * @return string  
  */
 public static function transformXmlUsingXslt($xmlStr, $xslt, $xsltParams = array(), &$xsltErrors = array())
 {
     $xml = new KDOMDocument();
     if (!$xml->loadXML($xmlStr)) {
         KalturaLog::debug("Could not load xmlStr");
         return null;
     }
     $xsl = new KDOMDocument();
     if (!$xsl->loadXML($xslt)) {
         KalturaLog::debug("Could not load xslt");
         return null;
     }
     $proc = new XSLTProcessor();
     foreach ($xsltParams as $key => $value) {
         $proc->setParameter('', $key, $value);
     }
     $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions());
     @$proc->importStyleSheet($xsl);
     $errorHandler = new XSLTErrorCollector();
     $xml = @$proc->transformToDoc($xml);
     $errorHandler->restoreErrorHandler();
     $xsltErrors = $errorHandler->errors;
     if (!$xml) {
         KalturaLog::err("XML Transformation failed");
         return null;
     }
     if (isset($xml->documentElement)) {
         $xml->documentElement->removeAttributeNS('http://php.net/xsl', 'php');
     }
     return $xml->saveXML();
 }
 /**
  * @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;
 }
예제 #12
0
 /**
  * Validate the XML against the profile XSD and set the metadata status
  *
  * @param int $metadataProfileId
  * @param string $metadata
  * @param string $errorMessage
  * @param int $compareAgainstPreviousVersion leave it false to use the latest metadata profile version
  *
  * returns bool
  */
 public static function validateMetadata($metadataProfileId, $metadata, &$errorMessage, $compareAgainstPreviousVersion = false)
 {
     KalturaLog::debug("Validating metadata [{$metadata}]");
     $metadataProfile = MetadataProfilePeer::retrieveByPK($metadataProfileId);
     if (!$metadataProfile) {
         $errorMessage = "Metadata profile [{$metadataProfileId}] not found";
         KalturaLog::err($errorMessage);
         return false;
     }
     $metadataProfileFSVersion = null;
     if ($compareAgainstPreviousVersion) {
         $metadataProfileFSVersion = $metadataProfile->getPreviousFileSyncVersion();
     }
     $metadataProfileKey = $metadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_DEFINITION, $metadataProfileFSVersion);
     $xsdData = kFileSyncUtils::file_get_contents($metadataProfileKey, true, false);
     if (!$xsdData) {
         $errorMessage = "Metadata profile xsd not found";
         KalturaLog::err($errorMessage);
         return false;
     }
     libxml_use_internal_errors(true);
     libxml_clear_errors();
     $xml = new KDOMDocument();
     $xml->loadXML($metadata);
     if ($xml->schemaValidateSource($xsdData)) {
         if (!self::validateMetadataObjects($metadataProfileId, $xml, $errorMessage)) {
             KalturaLog::err($errorMessage);
             return false;
         }
         KalturaLog::debug("Metadata is valid");
         return true;
     }
     $errorMessage = kXml::getLibXmlErrorDescription($metadata);
     KalturaLog::err("Metadata is invalid:\n{$errorMessage}");
     return false;
 }
예제 #13
0
<?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);
 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();
 }
예제 #15
0
 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 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;
 }
예제 #17
0
 protected function getOriginalOrTransformIfNeeded(DropFolder $folder, $xmlPath)
 {
     if (!file_exists($xmlPath) || !filesize($xmlPath)) {
         throw new Exception('Empty file supplied as input');
     }
     if (!$folder->getConversionProfileId()) {
         KalturaLog::debug('No conversion profile found on drop folder [' . $folder->getId() . '] assuming no xsl transformation is needed');
         return file_get_contents($xmlPath);
     }
     $conversionProfile = conversionProfile2Peer::retrieveByPK($folder->getConversionProfileId());
     if (!$conversionProfile || strlen($conversionProfile->getXsl()) == 0) {
         KalturaLog::debug('No conversion profile found Or no xsl transform found');
         return file_get_contents($xmlPath);
     }
     $originalXmlDoc = file_get_contents($xmlPath);
     $origianlXml = new KDOMDocument();
     if (!$origianlXml->loadXML($originalXmlDoc)) {
         KalturaLog::debug('Could not load original xml');
         $errorMessage = kXml::getLibXmlErrorDescription($originalXmlDoc);
         throw new Exception(DropFolderXmlBulkUploadPlugin::MALFORMED_XML_FILE_MESSAGE, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::MALFORMED_XML_FILE));
     }
     libxml_clear_errors();
     $proc = new XSLTProcessor();
     $xsl = new KDOMDocument();
     if (!$xsl->loadXML($conversionProfile->getXsl())) {
         KalturaLog::debug('Could not load xsl ' . $conversionProfile->getXsl());
         $errorMessage = kXml::getLibXmlErrorDescription($conversionProfile->getXsl());
         throw new Exception(DropFolderXmlBulkUploadPlugin::MALFORMED_XML_FILE_MESSAGE, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::MALFORMED_XML_FILE));
     }
     $proc->importStyleSheet($xsl);
     libxml_clear_errors();
     $transformedXml = $proc->transformToXML($origianlXml);
     if (!$transformedXml) {
         KalturaLog::debug('Could not transform xml ' . $conversionProfile->getXsl());
         $errorMessage = kXml::getLibXmlErrorDescription($conversionProfile->getXsl());
         throw new Exception(DropFolderXmlBulkUploadPlugin::MALFORMED_XML_FILE_MESSAGE, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::MALFORMED_XML_FILE));
     }
     $xmlDoc = new KDOMDocument();
     $res = $xmlDoc->loadXML($transformedXml);
     if (!$res) {
         throw new Exception(DropFolderXmlBulkUploadPlugin::MALFORMED_XML_FILE_MESSAGE, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::MALFORMED_XML_FILE));
     }
     return $transformedXml;
 }
예제 #18
0
 /**
  * @param asset $asset
  * @param string $class
  * @param string $encodingProfile
  * @param string $duration
  * @param string $url
  */
 protected function createEnclosureXml(asset $asset, $class, $encodingProfile, $duration)
 {
     /**
      * 
      * In QuickPlay's XML example, the namespace "http://www.quickplaymedia.com" is added to the "enclosure" 
      * element regardless to the fact that it was registerted with the prefix "qpm" on the root element.
      * We cannot set a namespace that was already defined with a prefix because DOMDocument will add the element
      * as "qpm:enclosure" and won't set the namespace explicitly.
      * 
      * The hack is to create a new KDOMDocument with default namespace "http://www.quickplaymedia.com" and then
      * add it to the xml manually (see getXml() method)
      * 
      */
     $syncKey = $asset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $fileSync = kFileSyncUtils::getLocalFileSyncForKey($syncKey);
     $contentNode = $this->_enclosureNode->cloneNode(true);
     kXml::setNodeValue($this->_xpath, '@encodingProfile', $encodingProfile, $contentNode);
     $url = $this->getAssetUrl($asset);
     $mimeType = $this->getContentTypeFromUrl($url);
     $enclosureDoc = new KDOMDocument();
     $enclosureElement = $enclosureDoc->createElementNS('http://www.quickplaymedia.com', 'enclosure');
     $xmlElement = $enclosureDoc->createElement('xml');
     $enclosureDoc->appendChild($xmlElement);
     $enclosureNode = $enclosureDoc->importNode($contentNode, true);
     $enclosureNode->setAttribute('class', $class);
     $link = $enclosureNode->getElementsByTagName('link')->item(0);
     $link->setAttribute('type', $mimeType);
     $link->setAttribute('length', $fileSync->getFileSize());
     $link->setAttribute('duration', $duration);
     $link->setAttribute('url', pathinfo($fileSync->getFilePath(), PATHINFO_BASENAME));
     $xmlElement->appendChild($enclosureNode);
     return $enclosureDoc->saveXML($enclosureNode);
 }
 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();
 }
예제 #20
0
 /**
  * @param array<CuePoint> $cuePoints
  * @return string xml
  */
 public static function generateXml(array $cuePoints)
 {
     $schemaType = CuePointPlugin::getApiValue(CuePointSchemaType::SERVE_API);
     $xsdUrl = "http://" . kConf::get('cdn_host') . "/api_v3/service/schema/action/serve/type/{$schemaType}";
     $scenes = new SimpleXMLElement('<scenes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="' . $xsdUrl . '" />');
     $pluginInstances = KalturaPluginManager::getPluginInstances('IKalturaCuePointXmlParser');
     foreach ($cuePoints as $cuePoint) {
         $scene = null;
         foreach ($pluginInstances as $pluginInstance) {
             $scene = $pluginInstance->generateXml($cuePoint, $scenes, $scene);
         }
     }
     $xmlContent = $scenes->asXML();
     $xml = new KDOMDocument();
     libxml_use_internal_errors(true);
     libxml_clear_errors();
     if (!$xml->loadXML($xmlContent)) {
         $errorMessage = kXml::getLibXmlErrorDescription($xmlContent);
         throw new kCuePointException("XML is invalid:\n{$errorMessage}", kCuePointException::XML_INVALID);
     }
     $xsdPath = SchemaService::getSchemaPath($schemaType);
     libxml_clear_errors();
     if (!$xml->schemaValidate($xsdPath)) {
         $errorMessage = kXml::getLibXmlErrorDescription($xmlContent);
         throw new kCuePointException("XML is invalid:\n{$errorMessage}", kCuePointException::XML_INVALID);
     }
     return $xmlContent;
 }
 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);
 }
 /**
  * @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;
 }
 public function addItemXml($xml)
 {
     $tempDoc = new KDOMDocument('1.0', 'UTF-8');
     $tempDoc->loadXML($xml);
     $importedItem = $this->doc->importNode($tempDoc->firstChild, true);
     $channelNode = $this->xpath->query('/rss/channel')->item(0);
     $channelNode->appendChild($importedItem);
 }
예제 #24
0
 /**
  * @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;
 }
예제 #25
0
 public function getContent($content)
 {
     $xml = new KDOMDocument();
     try {
         $xml->loadXML($content);
     } catch (Exception $e) {
         KalturaLog::err($e->getMessage());
         return null;
     }
     return trim(preg_replace('/\\s+/', ' ', $xml->textContent));
 }
예제 #26
0
 /**
  * Transform Xml file with conversion profile xsl
  * If xsl is not found, original Xml returned
  * @param string $filePath the original xml that was taken from partner file path
  * @return string - transformed Xml
  */
 protected function xslTransform($filePath)
 {
     $xdoc = file_get_contents($filePath);
     if (is_null($xdoc) || is_null($this->conversionProfileXsl)) {
         return $xdoc;
     }
     libxml_clear_errors();
     $xml = new KDOMDocument();
     if (!$xml->loadXML($xdoc)) {
         KalturaLog::debug("Could not load xml");
         $errorMessage = kXml::getLibXmlErrorDescription($xdoc);
         throw new KalturaBatchException("Could not load xml [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     libxml_clear_errors();
     $proc = new XSLTProcessor();
     $proc->registerPHPFunctions(kXml::getXslEnabledPhpFunctions());
     $xsl = new KDOMDocument();
     if (!$xsl->loadXML($this->conversionProfileXsl)) {
         KalturaLog::debug("Could not load xsl" . $this->conversionProfileXsl);
         $errorMessage = kXml::getLibXmlErrorDescription($this->conversionProfileXsl);
         throw new KalturaBatchException("Could not load xsl [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     $proc->importStyleSheet($xsl);
     libxml_clear_errors();
     $transformedXml = $proc->transformToXML($xml);
     if (!$transformedXml) {
         KalturaLog::debug("Could not transform xml" . $this->conversionProfileXsl);
         $errorMessage = kXml::getLibXmlErrorDescription($this->conversionProfileXsl);
         throw new KalturaBatchException("Could not transform xml [{$this->job->id}], {$errorMessage}", KalturaBatchJobAppErrors::BULK_VALIDATION_FAILED);
     }
     return $transformedXml;
 }
 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
 }