public function execute()
 {
     $widgetId = $this->getRequestParameter("wid");
     $widget = widgetPeer::retrieveByPK($widgetId);
     if (!$widget) {
         KalturaLog::err("Widget id [{$widgetId}] not found");
         die;
     }
     $entry = $widget->getentry();
     $entryId = $widget->getEntryId();
     if (!$entry) {
         KalturaLog::err("Entry id [{$entryId}] not found");
         die;
     }
     $uiConf = $widget->getuiConf();
     $uiConfId = $widget->getUiConfId();
     if (!$uiConf) {
         KalturaLog::err("UI Conf id [{$uiConfId}] not found");
         die;
     }
     $widgetPath = "/kwidget/wid/{$widgetId}/entry_id/{$entryId}/ui_conf/{$uiConfId}";
     $this->widget = $widget;
     $this->entry = $entry;
     $this->uiConf = $uiConf;
     $this->entryThumbUrl = $entry->getThumbnailUrl();
     $this->entryThumbSecureUrl = $entry->getThumbnailUrl(null, 'https');
     $this->widgetUrl = 'http://' . kConf::get('www_host') . $widgetPath;
     $this->widgetSecureUrl = 'https://' . kConf::get('www_host') . $widgetPath;
 }
Example #2
0
 public static function isRelativeTimeEnabled()
 {
     if (!kConf::hasParam('disable_relative_time_partners')) {
         return true;
     }
     return !in_array(kCurrentContext::getCurrentPartnerId(), kConf::get('disable_relative_time_partners'));
 }
 protected function partnerPermissionEnabled(Partner $partner)
 {
     $templatePartner = PartnerPeer::retrieveByPK($partner->getI18nTemplatePartnerId() ? $partner->getI18nTemplatePartnerId() : kConf::get('template_partner_id'));
     if ($templatePartner) {
         $this->copyEventNotificationTemplates($templatePartner, $partner, true);
     }
 }
Example #4
0
 /**
  * @param int $partnerId
  * @param string $objectType
  * @return AuditTrailConfig
  */
 protected static function getAuditTrailConfig($partnerId, $objectType)
 {
     $config = null;
     if (isset(self::$cachedPartnerConfig[$partnerId])) {
         $config = self::$cachedPartnerConfig[$partnerId];
     } else {
         $cacheFolder = kConf::get("cache_root_path") . "/audit";
         if (!is_dir($cacheFolder)) {
             mkdir($cacheFolder, 0777);
         }
         $cachePath = "{$cacheFolder}/{$partnerId}.cfg";
         if (file_exists($cachePath)) {
             $config = unserialize(file_get_contents($cachePath));
         } else {
             $auditTrailConfigs = AuditTrailConfigPeer::retrieveByPartnerId($partnerId);
             $config = array();
             if (count($auditTrailConfigs)) {
                 foreach ($auditTrailConfigs as $auditTrailConfig) {
                     $config[$auditTrailConfig->getObjectType()] = $auditTrailConfig;
                 }
             }
             file_put_contents($cachePath, serialize($config));
         }
         self::$cachedPartnerConfig[$partnerId] = $config;
     }
     if (!isset($config[$objectType])) {
         KalturaLog::info("Object type [{$objectType}] not audited");
         return null;
     }
     return $config[$objectType];
 }
Example #5
0
 public function execute()
 {
     $this->result = 0;
     if (@$_REQUEST["exit"] == "true") {
         $this->systemLogout();
         $login = NULL;
         $password = NULL;
     } else {
         $login = @$_REQUEST["login"];
         $password = @$_REQUEST["pwd"];
     }
     //echo "login: $login, password: $password";
     $this->login = $login;
     $this->sign_in_referer = @$_REQUEST["sign_in_referer"];
     if (empty($this->sign_in_referer)) {
         $this->sign_in_referer = $this->getFlash("sign_in_referer");
     }
     if (empty($login) || empty($password)) {
         $this->result = 0;
     } else {
         if (kConf::hasParam("system_pages_login_password") && sha1($password) == kConf::get("system_pages_login_password")) {
             $this->systemAuthenticated();
             if (empty($this->sign_in_referer)) {
                 // should go back - the original hit was to this page - no reason to go back or refresh
                 $this->result = 2;
             } else {
                 $this->result = 1;
             }
         } else {
             $this->result = -1;
         }
     }
 }
 private static function parse($content)
 {
     $items = array();
     $message = '';
     $doc = new DOMDocument();
     if ($doc->loadXML($content)) {
         $xpath = new DOMXPath($doc);
         $itemNodes = $xpath->query("//item");
         if (!$itemNodes->length) {
             $status = "error";
         } else {
             foreach ($itemNodes as $itemNode) {
                 $ns = "http://search.yahoo.com/mrss/";
                 $id = self::getXmlNodeValue($itemNode, "id");
                 $title = self::getXmlNodeValue($itemNode, "title");
                 $thumbnail = "http://s.mcstatic.com/thumb/" . $id . ".jpg";
                 $duration = self::getXmlNodeValue($itemNode, "content", "duration", $ns);
                 $description = self::getXmlNodeValue($itemNode, "description", null, $ns);
                 $description = strip_tags($description);
                 $tags = self::getXmlNodeValue($itemNode, "keywords", null, $ns);
                 $credit = self::getXmlNodeValue($itemNode, "credit", null, $ns);
                 $link = self::getXmlNodeValue($itemNode, "link");
                 $items[] = array('id' => $id, 'title' => $title, 'thumb' => $thumbnail, 'description' => $description, 'tags' => $tags, 'license' => '', 'credit' => $credit, 'source_link' => $link, 'url' => "http://" . kConf::get("www_host") . "/index.php/extservices/metacafeRedirect/itemId/" . $id);
             }
             $status = "ok";
         }
     } else {
         $status = "error";
     }
     return array('status' => $status, 'message' => $message, 'objects' => $items, "needMediaInfo" => self::$NEED_MEDIA_INFO);
 }
Example #7
0
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     $uiConf = uiConfPeer::retrieveByPK($ui_conf_id);
     if (!$uiConf) {
         die;
     }
     $partner_id = $uiConf->getPartnerId();
     $subp_id = $uiConf->getSubpId();
     $host = myPartnerUtils::getHost($partner_id);
     $ui_conf_swf_url = $uiConf->getSwfUrl();
     if (!$ui_conf_swf_url) {
         $ui_conf_swf_url = "/swf/simpleeditor.swf";
     }
     if (kString::beginsWith($ui_conf_swf_url, "http")) {
         $swf_url = $ui_conf_swf_url;
         // absolute URL
     } else {
         $use_cdn = $uiConf->getUseCdn();
         $cdn_host = $use_cdn ? myPartnerUtils::getCdnHost($partner_id) : myPartnerUtils::getHost($partner_id);
         $swf_url = $cdn_host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url;
         // relative to the current host
     }
     // handle buggy case for backward compatiblity
     $partner_host = $host;
     if ($partner_host == "http://www.kaltura.com") {
         $partner_host = 1;
     }
     // otherwise the kse will build a flawed url with [[IMPORT]]
     $params = "contentUrl=" . urlencode($swf_url) . "&host=" . str_replace("http://", "", str_replace("https://", "", $partner_host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", myPartnerUtils::getCdnHost($partner_id))) . "&uiConfId=" . $ui_conf_id . "&disableurlhashing=" . kConf::get('disable_url_hashing');
     $wrapper_swf = myContentStorage::getFSFlashRootPath() . "/flexwrapper/" . kConf::get('editors_flex_wrapper_version') . "/FlexWrapper.swf";
     $this->redirect($host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "{$wrapper_swf}?{$params}");
 }
Example #8
0
 public function myCache($namespace, $expiry = NULL)
 {
     $this->m_namespace = $namespace;
     if (self::$s_memcache == NULL) {
         if (!function_exists('memcache_connect')) {
             return;
         }
         self::$s_memcache = new Memcache();
         //self::$s_memcache->pconnect(self::SERVER, self::PORT) // this will use a persistent connection
         try {
             $res = @self::$s_memcache->connect(kConf::get("memcache_host"), kConf::get("memcache_port"));
         } catch (Exception $e) {
             $res = false;
         }
         if (!$res) {
             kLog::log("ERROR: Error while trying to connect to memcache. Make sure it is properly running on " . kConf::get("memcache_host") . ":" . kConf::get("memcache_port"));
             //throw new Exception ("Error while trying to connect to memcache. Make sure it is properly running on " . self::SERVER . ":" . self::PORT );
         } else {
             self::$s_ready = true;
         }
         //				or die ("Error while trying to connect to memcache. Make sure it is properly running on " . self::SERVER . ":" . self::PORT );
     }
     if ($expiry != null) {
         $this->m_expiry = $expiry;
     }
     if ($this->calculateStats()) {
         $this->m_stats = $this->getStatsObj();
         if ($this->m_stats == NULL) {
             $this->m_stats = new cacheStats();
         }
     } else {
         $this->m_stats = new cacheStats();
     }
 }
 protected function validateNestedObjects($maxPageSize = null, $maxNestingLevel = null)
 {
     $relatedProfiles = $this->relatedProfiles;
     if (!$relatedProfiles) {
         return;
     }
     if (is_null($maxPageSize)) {
         $maxPageSize = kConf::get('response_profile_max_page_size', 'local', 100);
     }
     if (is_null($maxNestingLevel)) {
         $maxNestingLevel = kConf::get('response_profile_max_nesting_level', 'local', 2);
     }
     if ($maxNestingLevel > 0) {
         foreach ($relatedProfiles as $relatedProfile) {
             /* @var $relatedProfile KalturaDetachedResponseProfile */
             $relatedProfile->validateNestedObjects($maxPageSize, $maxNestingLevel - 1);
             $pager = $relatedProfile->pager;
             if ($pager) {
                 $pager->validatePropertyMaxValue('pageSize', $maxPageSize, true);
             }
         }
     } elseif (count($relatedProfiles)) {
         throw new KalturaAPIException(KalturaErrors::RESPONSE_PROFILE_MAX_NESTING_LEVEL);
     }
 }
Example #10
0
function getExcludeFileSyncMap()
{
    $result = array();
    $dcConfig = kConf::getMap("dc_config");
    if (isset($dcConfig['sync_exclude_types'])) {
        foreach ($dcConfig['sync_exclude_types'] as $syncExcludeType) {
            $configObjectType = $syncExcludeType;
            $configObjectSubType = null;
            if (strpos($syncExcludeType, ':') > 0) {
                list($configObjectType, $configObjectSubType) = explode(':', $syncExcludeType, 2);
            }
            // translate api dynamic enum, such as contentDistribution.EntryDistribution - {plugin name}.{object name}
            if (!is_numeric($configObjectType)) {
                $configObjectType = kPluginableEnumsManager::apiToCore('FileSyncObjectType', $configObjectType);
            }
            // translate api dynamic enum, including the enum type, such as conversionEngineType.mp4box.Mp4box - {enum class name}.{plugin name}.{object name}
            if (!is_null($configObjectSubType) && !is_numeric($configObjectSubType)) {
                list($enumType, $configObjectSubType) = explode('.', $configObjectSubType);
                $configObjectSubType = kPluginableEnumsManager::apiToCore($enumType, $configObjectSubType);
            }
            if (!isset($result[$configObjectType])) {
                $result[$configObjectType] = array();
            }
            if (!is_null($configObjectSubType)) {
                $result[$configObjectType][] = $configObjectSubType;
            }
        }
    }
    return $result;
}
 public function __construct(KalturaDistributionJobData $distributionJobData = null)
 {
     parent::__construct($distributionJobData);
     $this->notificationBaseUrl = 'http://' . kConf::get('cdn_api_host');
     if (!$distributionJobData) {
         return;
     }
     if (!$distributionJobData->distributionProfile instanceof KalturaUnicornDistributionProfile) {
         return;
     }
     $entryDistributionDb = EntryDistributionPeer::retrieveByPK($distributionJobData->entryDistributionId);
     $distributionProfileDb = DistributionProfilePeer::retrieveByPK($distributionJobData->distributionProfileId);
     /* @var $distributionProfileDb UnicornDistributionProfile */
     $flavorAssetIds = explode(',', $entryDistributionDb->getFlavorAssetIds());
     $flavorAssetId = reset($flavorAssetIds);
     $flavorAsset = assetPeer::retrieveById($flavorAssetId);
     $flavorAssetOldVersion = $entryDistributionDb->getFromCustomData(kUnicornDistributionJobProviderData::CUSTOM_DATA_FLAVOR_ASSET_OLD_VERSION);
     $flavorAssetNewVersion = null;
     if ($flavorAsset) {
         $flavorAssetNewVersion = $flavorAsset->getVersion();
     }
     $values = $distributionProfileDb->getAllFieldValues($entryDistributionDb);
     $this->catalogGuid = $values[UnicornDistributionField::CATALOG_GUID];
     $this->title = $values[UnicornDistributionField::TITLE];
     $this->flavorAssetVersion = $flavorAssetNewVersion;
     $this->mediaChanged = $flavorAssetOldVersion != $flavorAssetNewVersion;
 }
Example #12
0
 public function __construct()
 {
     // check that rabbit_mq.ini file exists
     if (kConf::hasMap('rabbit_mq')) {
         // check configuration is correctly set
         $rabbitConfig = kConf::getMap('rabbit_mq');
         if (isset($rabbitConfig['username'])) {
             $this->username = $rabbitConfig['username'];
         }
         if (isset($rabbitConfig['password'])) {
             $this->password = $rabbitConfig['password'];
         }
         if (isset($rabbitConfig['server'])) {
             $this->MQserver = $rabbitConfig['server'];
         }
         if (isset($rabbitConfig['port'])) {
             $this->port = $rabbitConfig['port'];
         }
         if (isset($rabbitConfig['curl_port'])) {
             $this->curlPort = $rabbitConfig['curl_port'];
         }
         if (isset($rabbitConfig['timeout'])) {
             $this->timeout = $rabbitConfig['timeout'];
         }
     } else {
         KalturaLog::err("RabbitMQ configuration file (rabbit_mq.ini) wasn't found!");
     }
 }
Example #13
0
 /**
  * Add new CategoryUser
  * 
  * @action add
  * @param KalturaCategoryUser $categoryUser
  * @return KalturaCategoryUser
  */
 function addAction(KalturaCategoryUser $categoryUser)
 {
     $dbCategoryKuser = $categoryUser->toInsertableObject();
     /* @var $dbCategoryKuser categoryKuser */
     $category = categoryPeer::retrieveByPK($categoryUser->categoryId);
     if (!$category) {
         throw new KalturaAPIException(KalturaErrors::CATEGORY_NOT_FOUND, $categoryUser->categoryId);
     }
     $maxUserPerCategory = kConf::get('max_users_per_category');
     if ($category->getMembersCount() >= $maxUserPerCategory) {
         throw new KalturaAPIException(KalturaErrors::CATEGORY_MAX_USER_REACHED, $maxUserPerCategory);
     }
     $currentKuserCategoryKuser = categoryKuserPeer::retrievePermittedKuserInCategory($categoryUser->categoryId, kCurrentContext::getCurrentKsKuserId());
     if (!kEntitlementUtils::getEntitlementEnforcement()) {
         $dbCategoryKuser->setStatus(CategoryKuserStatus::ACTIVE);
         $dbCategoryKuser->setPermissionLevel($categoryUser->permissionLevel);
     } elseif ($currentKuserCategoryKuser && $currentKuserCategoryKuser->getPermissionLevel() == CategoryKuserPermissionLevel::MANAGER) {
         //Current Kuser is manager
         $dbCategoryKuser->setStatus(CategoryKuserStatus::ACTIVE);
     } elseif ($category->getUserJoinPolicy() == UserJoinPolicyType::AUTO_JOIN) {
         $dbCategoryKuser->setPermissionLevel($category->getDefaultPermissionLevel());
         $dbCategoryKuser->setStatus(CategoryKuserStatus::ACTIVE);
     } elseif ($category->getUserJoinPolicy() == UserJoinPolicyType::REQUEST_TO_JOIN) {
         $dbCategoryKuser->setPermissionLevel($category->getDefaultPermissionLevel());
         $dbCategoryKuser->setStatus(CategoryKuserStatus::PENDING);
     } else {
         throw new KalturaAPIException(KalturaErrors::CATEGORY_USER_JOIN_NOT_ALLOWED, $categoryUser->categoryId);
     }
     $dbCategoryKuser->setCategoryFullIds($category->getFullIds());
     $dbCategoryKuser->setPartnerId($this->getPartnerId());
     $dbCategoryKuser->save();
     $categoryUser->fromObject($dbCategoryKuser, $this->getResponseProfile());
     return $categoryUser;
 }
 /**
  * @param int $type
  * @return kBaseCacheWrapper or null on error
  */
 public static function getCache($type)
 {
     if (array_key_exists($type, self::$caches)) {
         return self::$caches[$type];
     }
     if (!array_key_exists($type, self::$cacheConfigs)) {
         return null;
     }
     $config = self::$cacheConfigs[$type];
     $className = "k{$config[0]}CacheWrapper";
     require_once dirname(__FILE__) . '/' . $className . '.php';
     $cache = new $className();
     // get required kConf params
     $config = array_slice($config, 1);
     foreach ($config as $index => $value) {
         if (is_string($value) && substr($value, 0, strlen(self::KCONF_PARAM_PREFIX)) == self::KCONF_PARAM_PREFIX) {
             $value = substr($value, strlen(self::KCONF_PARAM_PREFIX));
             if (!kConf::hasParam($value)) {
                 self::$caches[$type] = null;
                 return null;
             }
             $config[$index] = kConf::get($value);
         }
     }
     // initialize the cache
     if (call_user_func_array(array($cache, 'init'), $config) === false) {
         $cache = null;
     }
     self::$caches[$type] = $cache;
     return $cache;
 }
Example #15
0
 protected function init()
 {
     if (!parent::init()) {
         return false;
     }
     // ignore params which may hurt caching such as callback, playSessionId
     if (kConf::hasParam('playmanifest_ignore_params')) {
         $ignoreParams = kConf::get('playmanifest_ignore_params');
         foreach ($ignoreParams as $paramName) {
             unset($this->_params[$paramName]);
         }
     }
     $this->_playbackContext = isset($this->_params['playbackContext']) ? $this->_params['playbackContext'] : null;
     unset($this->_params['playbackContext']);
     $this->_deliveryCode = isset($this->_params['deliveryCode']) ? $this->_params['deliveryCode'] : null;
     unset($this->_params['deliveryCode']);
     // take only the hostname part of the referrer parameter of baseEntry.getContextData
     if (isset($this->_params['referrer'])) {
         $referrer = base64_decode(str_replace(" ", "+", $this->_params['referrer']));
         if (!is_string($referrer)) {
             $referrer = "";
         }
         unset($this->_params['referrer']);
     } else {
         $referrer = self::getHttpReferrer();
     }
     $this->_referrers[] = $referrer;
     $this->finalizeCacheKey();
     $this->addExtraFields();
     return true;
 }
Example #16
0
 /**
  * Retrieve all records larger than the id
  *
  * @param      array $servers<SphinxLogServer>
  * @param	   int $gap
  * @param      int $limit
  * @param	   array $handledEntries	
  * @param      PropelPDO $con the connection to use
  * @return     SphinxLog
  */
 public static function retrieveByLastId(array $servers, $gap = 0, $limit = 1000, array $handledEntries = null, PropelPDO $con = null)
 {
     $criteria = new Criteria();
     $criterions = null;
     if (count($servers)) {
         $criterions = $criteria->getNewCriterion(SphinxLogPeer::ID, null, Criteria::ISNULL);
     }
     foreach ($servers as $server) {
         $dc = $server->getDc();
         $crit = $criteria->getNewCriterion(SphinxLogPeer::ID, $server->getLastLogId() - $gap, Criteria::GREATER_THAN);
         $crit->addAnd($criteria->getNewCriterion(SphinxLogPeer::DC, $dc));
         if (!is_null($handledEntries)) {
             $crit->addAnd($criteria->getNewCriterion(SphinxLogPeer::ID, $handledEntries[$dc], Criteria::NOT_IN));
         }
         $criterions->addOr($crit);
     }
     if ($criterions) {
         $criteria->addAnd($criterions);
     }
     $disabledPartnerIds = kConf::get('disable_sphinx_indexing_partners', 'local', array());
     if ($disabledPartnerIds) {
         $criteria->add(SphinxLogPeer::PARTNER_ID, $disabledPartnerIds, Criteria::NOT_IN);
     }
     $criteria->addAscendingOrderByColumn(SphinxLogPeer::ID);
     $criteria->setLimit($limit);
     return SphinxLogPeer::doSelect($criteria, $con);
 }
 public function entryHandled(entry $dbEntry)
 {
     parent::entryHandled($dbEntry);
     $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($dbEntry->getId());
     $syncKey = $originalFlavorAsset->getSyncKey(asset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
     $sourceFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey);
     // call mediaInfo for file
     $dbMediaInfo = new mediaInfo();
     try {
         $mediaInfoParser = new KMediaInfoMediaParser($sourceFilePath, kConf::get('bin_path_mediainfo'));
         $mediaInfo = $mediaInfoParser->getMediaInfo();
         $dbMediaInfo = $mediaInfo->toInsertableObject($dbMediaInfo);
         $dbMediaInfo->setFlavorAssetId($originalFlavorAsset->getId());
         $dbMediaInfo->save();
     } catch (Exception $e) {
         KalturaLog::err("Getting media info: " . $e->getMessage());
         $dbMediaInfo = null;
     }
     // fix flavor asset according to mediainfo
     if ($dbMediaInfo) {
         KDLWrap::ConvertMediainfoCdl2FlavorAsset($dbMediaInfo, $originalFlavorAsset);
         $flavorTags = KDLWrap::CDLMediaInfo2Tags($dbMediaInfo, array(flavorParams::TAG_WEB, flavorParams::TAG_MBR));
         $originalFlavorAsset->setTags(implode(',', array_unique($flavorTags)));
     }
     $originalFlavorAsset->setStatusLocalReady();
     $originalFlavorAsset->save();
     $dbEntry->setStatus(entryStatus::READY);
     $dbEntry->save();
 }
Example #18
0
 protected static function init()
 {
     if (!kConf::hasParam('monitor_uri')) {
         return null;
     }
     $uri = kConf::get('monitor_uri');
     $pathInfo = parse_url($uri);
     if (isset($pathInfo['host']) && $pathInfo['port']) {
         $host = $pathInfo['host'];
         if (isset($pathInfo['scheme'])) {
             $host = $pathInfo['scheme'] . "://{$host}";
         }
         $errno = null;
         $errstr = null;
         self::$stream = fsockopen($host, $pathInfo['port'], $errno, $errstr, 1);
         if (self::$stream) {
             return true;
         }
         if (class_exists('KalturaLog')) {
             KalturaLog::err("Open socket failed: {$errstr}");
         }
     }
     self::$stream = fopen($uri, 'a');
     if (self::$stream) {
         return true;
     }
     self::$stream = false;
     // prevent init from being called again
     return false;
 }
Example #19
0
 protected function processKs($ksStr, $requiredPermission = null)
 {
     try {
         kCurrentContext::initKsPartnerUser($ksStr);
     } catch (Exception $ex) {
         KalturaLog::err($ex);
         return false;
     }
     if (kCurrentContext::$ks_object->type != ks::SESSION_TYPE_ADMIN) {
         KalturaLog::err('Ks is not admin');
         return false;
     }
     try {
         kPermissionManager::init(kConf::get('enable_cache'));
     } catch (Exception $ex) {
         if (strpos($ex->getCode(), 'INVALID_ACTIONS_LIMIT') === false) {
             KalturaLog::err($ex);
             return false;
         }
     }
     if ($requiredPermission) {
         if (!kPermissionManager::isPermitted(PermissionName::ADMIN_PUBLISHER_MANAGE)) {
             KalturaLog::err('Ks is missing "ADMIN_PUBLISHER_MANAGE" permission');
             return false;
         }
     }
     return true;
 }
Example #20
0
 public static function createThumbnailAssetFromFile(entry $entry, $filePath)
 {
     try {
         $fileLocation = tempnam(sys_get_temp_dir(), $entry->getId());
         $res = KCurlWrapper::getDataFromFile($filePath, $fileLocation, kConf::get('thumb_size_limit'));
     } catch (Exception $e) {
         KalturaLog::debug($e->getMessage());
         throw new Exception("Data Retrieval Failed");
     }
     if (!$res) {
         KalturaLog::debug("thumbnail cannot be created from {$filePath} " . error_get_last());
         throw new Exception("thumbnail file path is not valid");
     }
     $thumbAsset = new thumbAsset();
     $thumbAsset->setPartnerId($entry->getPartnerId());
     $thumbAsset->setEntryId($entry->getId());
     $thumbAsset->setStatus(thumbAsset::ASSET_STATUS_QUEUED);
     $thumbAsset->incrementVersion();
     $thumbAsset->save();
     $fileSyncKey = $thumbAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET);
     kFileSyncUtils::moveFromFile($fileLocation, $fileSyncKey);
     $finalPath = kFileSyncUtils::getLocalFilePathForKey($fileSyncKey);
     $ext = pathinfo($finalPath, PATHINFO_EXTENSION);
     $thumbAsset->setFileExt($ext);
     list($width, $height, $type, $attr) = getimagesize($finalPath);
     $thumbAsset->setWidth($width);
     $thumbAsset->setHeight($height);
     $thumbAsset->setSize(filesize($finalPath));
     $thumbAsset->setStatus(thumbAsset::ASSET_STATUS_READY);
     $thumbAsset->save();
     kBusinessConvertDL::setAsDefaultThumbAsset($thumbAsset);
     myNotificationMgr::createNotification(kNotificationJobData::NOTIFICATION_TYPE_ENTRY_UPDATE_THUMBNAIL, $entry);
 }
 /**
  * @param string $type
  * @return KalturaTypeReflector
  */
 static function get($type)
 {
     if (!self::$_enabled) {
         return new KalturaTypeReflector($type);
     }
     if (!array_key_exists($type, self::$_loadedTypeReflectors)) {
         $cachedDir = KAutoloader::buildPath(kConf::get("cache_root_path"), "api_v3", "typeReflector");
         if (!is_dir($cachedDir)) {
             mkdir($cachedDir);
             chmod($cachedDir, 0755);
         }
         $cachedFilePath = $cachedDir . DIRECTORY_SEPARATOR . $type . ".cache";
         $typeReflector = null;
         if (file_exists($cachedFilePath)) {
             $cachedData = file_get_contents($cachedFilePath);
             $typeReflector = unserialize($cachedData);
         }
         if (!$typeReflector) {
             $typeReflector = new KalturaTypeReflector($type);
             $cachedData = serialize($typeReflector);
             $bytesWritten = kFile::safeFilePutContents($cachedFilePath, $cachedData);
             if (!$bytesWritten) {
                 $folderPermission = substr(decoct(fileperms(dirname($cachedFilePath))), 2);
                 error_log("Kaltura type reflector could not be saved to path [{$cachedFilePath}] type [{$type}] folder permisisons [{$folderPermission}]");
             }
         }
         self::$_loadedTypeReflectors[$type] = $typeReflector;
     }
     return self::$_loadedTypeReflectors[$type];
 }
Example #22
0
 /**
  * @param $configName string
  * @param $context string
  */
 public static function InitLogger($configName, $context = null)
 {
     if (KalturaLog::getLogger()) {
         // already initialized
         return;
     }
     if (function_exists('apc_fetch')) {
         $cacheKey = self::LOGGER_APC_CACHE_KEY_PREFIX . $configName;
         $logger = apc_fetch($cacheKey);
         if ($logger) {
             list($logger, $cacheVersionId) = $logger;
             if ($cacheVersionId == kConf::getCachedVersionId()) {
                 KalturaLog::setLogger($logger);
                 return;
             }
         }
     }
     try {
         $config = new Zend_Config(kConf::getMap('logger'));
         KalturaLog::initLog($config->{$configName});
         if ($context) {
             KalturaLog::setContext($context);
         }
         if (function_exists('apc_store')) {
             apc_store($cacheKey, array(KalturaLog::getLogger(), kConf::getCachedVersionId()));
         }
     } catch (Zend_Config_Exception $ex) {
     }
 }
 /**
  * Will forward to the regular swf player according to the widget_id 
  */
 public function execute()
 {
     $ui_conf_id = $this->getRequestParameter("ui_conf_id");
     $uiConf = uiConfPeer::retrieveByPK($ui_conf_id);
     if (!$uiConf) {
         die;
     }
     $partner_id = $uiConf->getPartnerId();
     $subp_id = $uiConf->getSubpId();
     if (!$subp_id) {
         $subp_id = 0;
     }
     $host = myPartnerUtils::getHost($partner_id);
     $ui_conf_swf_url = $uiConf->getSwfUrl();
     if (!$ui_conf_swf_url) {
         $ui_conf_swf_url = "/swf/ContributionWizard.swf";
     }
     if (kString::beginsWith($ui_conf_swf_url, "http")) {
         $swf_url = $ui_conf_swf_url;
         // absolute URL
     } else {
         $use_cdn = $uiConf->getUseCdn();
         $cdn_host = $use_cdn ? myPartnerUtils::getCdnHost($partner_id) : myPartnerUtils::getHost($partner_id);
         $swf_url = $cdn_host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . $ui_conf_swf_url;
         // relative to the current host
     }
     $params = "contentUrl=" . urlencode($swf_url) . "&host=" . str_replace("http://", "", str_replace("https://", "", $host)) . "&cdnHost=" . str_replace("http://", "", str_replace("https://", "", myPartnerUtils::getCdnHost($partner_id))) . "&uiConfId=" . $ui_conf_id;
     $wrapper_swf = myContentStorage::getFSFlashRootPath() . "/flexwrapper/" . kConf::get('kcw_flex_wrapper_version') . "/FlexWrapper.swf";
     $this->redirect($host . myPartnerUtils::getUrlForPartner($partner_id, $subp_id) . "{$wrapper_swf}?{$params}");
 }
Example #24
0
 /**
  * will return a pair of file_root and file_path
  * This is the only function that should be extended for building a different path
  *
  * @param ISyncableFile $object
  * @param int $subType
  * @param $version
  */
 public function generateFilePathArr(ISyncableFile $object, $subType, $version = null)
 {
     //		$traces = debug_backtrace(false);
     //		foreach($traces as $i => $trace)
     //		{
     //			$file = $trace['file'];
     //			$line = $trace['line'];
     //			$class = $trace['class'];
     //			$function = $trace['function'];
     //			KalturaLog::debug("#$i Called from function [$class::$function] file[$file] line[$line]");
     //		}
     list($root, $path) = $object->generateFilePathArr($subType, $version);
     $root = str_replace('//', '/', $root);
     $path = str_replace('//', '/', $path);
     if (!kConf::hasParam('volumes')) {
         KalturaLog::debug("Path [{$root}{$path}]");
         return array($root, $path);
     }
     if (isset(self::$sessionCache[$path])) {
         return array($root, self::$sessionCache[$path]);
     }
     $volumes = kConf::get('volumes');
     $volume = $volumes[rand(0, count($volumes) - 1)];
     $newPath = str_replace('/content/', "/content/{$volume}/", $path);
     self::$sessionCache[$path] = $newPath;
     $path = $newPath;
     KalturaLog::debug("Path [{$root}{$path}]");
     return array($root, $path);
 }
 public static function handleFlavorReady(BatchJob $dbBatchJob, $flavorAssetId)
 {
     // verifies that flavor asset created
     if (!$flavorAssetId) {
         throw new APIException(APIErrors::INVALID_FLAVOR_ASSET_ID, $flavorAssetId);
     }
     $currentFlavorAsset = assetPeer::retrieveById($flavorAssetId);
     // verifies that flavor asset exists
     if (!$currentFlavorAsset) {
         throw new APIException(APIErrors::INVALID_FLAVOR_ASSET_ID, $flavorAssetId);
     }
     // if the flavor deleted then it shouldn't be taken into ready calculations
     if ($currentFlavorAsset->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_DELETED) {
         return $currentFlavorAsset;
     }
     //		Remarked because we want the original flavor ready behavior to work the same as other flavors
     //
     //		$rootBatchJob = $dbBatchJob->getRootJob();
     //
     //		// happens in case of post convert on the original (in case of bypass)
     //		if($rootBatchJob && $currentFlavorAsset->getIsOriginal())
     //		{
     //			kJobsManager::updateBatchJob($rootBatchJob, BatchJob::BATCHJOB_STATUS_FINISHED);
     //			return $dbBatchJob;
     //		}
     $sourceMediaInfo = mediaInfoPeer::retrieveOriginalByEntryId($dbBatchJob->getEntryId());
     $productMediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($currentFlavorAsset->getId());
     $targetFlavor = assetParamsOutputPeer::retrieveByAssetId($currentFlavorAsset->getId());
     $postConvertData = $dbBatchJob->getData();
     $postConvertAssetType = BatchJob::POSTCONVERT_ASSET_TYPE_FLAVOR;
     if ($postConvertData instanceof kPostConvertJobData) {
         $postConvertAssetType = $postConvertData->getPostConvertAssetType();
     }
     // don't validate in case of bypass, in case target flavor or media info are null
     if ($postConvertAssetType != BatchJob::POSTCONVERT_ASSET_TYPE_BYPASS && $targetFlavor && $productMediaInfo) {
         try {
             $productFlavor = KDLWrap::CDLValidateProduct($sourceMediaInfo, $targetFlavor, $productMediaInfo);
         } catch (Exception $e) {
             KalturaLog::err('KDL Error: ' . print_r($e, true));
         }
         $err = kBusinessConvertDL::parseFlavorDescription($productFlavor);
         KalturaLog::debug("BCDL: job id [" . $dbBatchJob->getId() . "] flavor params output id [" . $targetFlavor->getId() . "] flavor asset id [" . $currentFlavorAsset->getId() . "] desc: {$err}");
         if (!$productFlavor->IsValid()) {
             $description = $currentFlavorAsset->getDescription() . "\n{$err}";
             // mark the asset as ready
             $currentFlavorAsset->setDescription($description);
             $currentFlavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
             $currentFlavorAsset->save();
             if (!kConf::get('ignore_cdl_failure')) {
                 kJobsManager::failBatchJob($dbBatchJob, $err);
                 return null;
             }
         }
     }
     // mark the asset as ready
     $currentFlavorAsset->setStatusLocalReady();
     $currentFlavorAsset->save();
     kFlowHelper::generateThumbnailsFromFlavor($dbBatchJob->getEntryId(), $dbBatchJob, $currentFlavorAsset->getFlavorParamsId());
     return $currentFlavorAsset;
 }
Example #26
0
 public function init($ignore, array $params)
 {
     $this->ignoreErrors = $ignore;
     $dbConf = kConf::getDB();
     $dsn = $dbConf['datasources']['propel']['connection']['dsn'];
     $dsn = explode(":", $dsn);
     $dsnArray = explode(";", $dsn[1]);
     // init with default port
     $this->dbParams = $dbConf['datasources']['propel']['connection'];
     $this->dbParams['port'] = '3306';
     foreach ($dsnArray as $param) {
         $items = explode("=", $param);
         if (count($items) == 2) {
             $this->dbParams[$items[0]] = $items[1];
         }
     }
     foreach ($params as $key => $value) {
         $this->dbParams[$key] = $value;
     }
     foreach ($this->dbParams as $key => $value) {
         echo $key . ' => ';
         if (is_array($value)) {
             var_dump($value);
         } else {
             echo "{$value}\n";
         }
     }
     $this->version = $this->getMaxVersion() + 1;
     $this->alreadyRun = $this->getDeployedScripts();
 }
Example #27
0
 protected static function init()
 {
     if (self::$cacheVersion) {
         return;
     }
     parent::init();
     // check for the reload file
     $cacheDir = self::$envMap['cache_root_path'];
     $reloadFileExists = file_exists("{$cacheDir}/base.reload");
     // fetch the cache version from APC
     $fileHash = md5(realpath(__FILE__));
     $cacheVersionKey = self::APC_CACHE_MAP . $fileHash;
     if (!$reloadFileExists && function_exists('apc_fetch')) {
         self::$cacheVersion = apc_fetch($cacheVersionKey);
         if (self::$cacheVersion) {
             self::$cacheKey = 'kConf-' . self::$cacheVersion;
             return;
         }
     }
     // no cache version in APC - create a new one
     self::$cacheVersion = substr(time(), -6) . substr($fileHash, 0, 4);
     self::$cacheKey = 'kConf-' . self::$cacheVersion;
     // save the cache version
     if (function_exists('apc_store') && PHP_SAPI != 'cli') {
         $res = apc_store($cacheVersionKey, self::$cacheVersion);
         if ($reloadFileExists && $res) {
             $deleted = @unlink("{$cacheDir}/base.reload");
             error_log("Base configuration reloaded");
             if (!$deleted) {
                 error_log("Failed to delete base.reload file");
             }
         }
     }
 }
Example #28
0
 public static function getPartnerPriorityFactorByPartner($partner)
 {
     $priority = self::getPriority($partner);
     $priority2Factor = kConf::get('priority_factor');
     $priorityFactor = $priority2Factor[$priority];
     return $priorityFactor;
 }
 public static function getIdByStrId($strId)
 {
     // try to get strId to id mapping form cache
     $cacheKey = 'UserRolePeer_role_str_id_' . $strId;
     if (kConf::get('enable_cache') && function_exists('apc_fetch') && function_exists('apc_store')) {
         $id = apc_fetch($cacheKey);
         // try to fetch from cache
         if ($id) {
             KalturaLog::debug("UserRole str_id [{$strId}] mapped to id [{$id}] - fetched from cache");
             return $id;
         }
     }
     // not found in cache - get from database
     $c = new Criteria();
     $c->addSelectColumn(UserRolePeer::ID);
     $c->addAnd(UserRolePeer::STR_ID, $strId, Criteria::EQUAL);
     $c->setLimit(1);
     $stmt = UserRolePeer::doSelectStmt($c);
     $id = $stmt->fetch(PDO::FETCH_COLUMN);
     if ($id) {
         // store the found id in cache for later use
         if (kConf::get('enable_cache') && function_exists('apc_fetch') && function_exists('apc_store')) {
             $success = apc_store($cacheKey, $id, kConf::get('apc_cache_ttl'));
             if ($success) {
                 KalturaLog::debug("UserRole str_id [{$strId}] mapped to id [{$id}] - stored in cache");
             }
         }
     }
     if (!$id) {
         KalturaLog::log("UserRole with str_id [{$strId}] not found in DB!");
     }
     return $id;
 }
 /**
  * 
  * Test the KMC Checks that the starting calls return okay
  * @param array<unknown_type> $params
  * @param array<unknown_type> $results
  * @dataProvider provideData
  */
 public function testCreateEntryForThumbAsset($entryId, $result)
 {
     $filter = new KalturaAssetFilter();
     $filter->entryIdEqual = $entryId;
     $results = $this->client->thumbAsset->listAction($filter, null);
     $assetUrl = $this->client->thumbAsset->getUrl($results->objects[0]->id, null);
     $filePath = dirname(__FILE__) . '/testsData/new_thumb_asset.jpg';
     self::saveApiFileFromUrl($assetUrl, $filePath);
     $tmpFile = tempnam(dirname(__FILE__), 'imageComperingTmp');
     $imageMagick = dirname(kConf::get('bin_path_imagemagick'));
     if ($imageMagick == '.') {
         $compare = 'compare';
     } else {
         $compare = dirname(kConf::get('bin_path_imagemagick')) . '/compare';
     }
     $result = dirname(__FILE__) . '/' . $result;
     $cmd = $compare . ' ' . $filePath . ' ' . $result . ' ' . $tmpFile . ' 2>resultLog.txt';
     $retValue = null;
     $output = null;
     $output = system($cmd, $retValue);
     @unlink($tmpFile);
     // delete tmp comparing file (used to copmpare the two image files)
     @unlink("resultLog.txt");
     // delete tmp log file that was used to retrieve compare return value
     if ($retValue != 0) {
         $this->fail('Files are not equal [' . $filePath . '] [' . $result . ']' . 'Compare return value was' . $retValue);
     }
 }