예제 #1
0
 /**
  * @param sfWebRequest $request
  * @return void
  */
 public function execute($request)
 {
     $this->file = FilePeer::retrieveByPK($request->getParameter('file'));
     $this->forward404Unless($this->file, "File not found");
     $this->branch = BranchPeer::retrieveByPK($this->file->getBranchId());
     $this->forward404Unless($this->branch, "Branch not found");
     $this->repository = RepositoryPeer::retrieveByPK($this->branch->getRepositoryId());
     $this->forward404Unless($this->repository, "Repository not found");
     $this->fileContent = $this->gitCommand->getShowFile($this->repository->getGitDir(), $this->file->getLastChangeCommit(), $this->file->getFilename());
     $this->fileExtension = pathinfo($this->file->getFilename(), PATHINFO_EXTENSION);
 }
예제 #2
0
파일: FilePeer.php 프로젝트: EQ4/smint
 public static function getFilesByExternalKeys($filedescs)
 {
     $fileCriteria = new Criteria();
     sfContext::getInstance()->getLogger()->info('foobar: build criteria start');
     foreach ($filedescs as $key => $file) {
         $tracknr = $file->getTracknr();
         $fileCriteria->addOr($fileCriteria->getNewCriterion(FilePeer::EXTERNAL_KEY, $tracknr));
     }
     sfContext::getInstance()->getLogger()->info('foobar: build criteria done');
     $files = FilePeer::doSelect($fileCriteria);
     sfContext::getInstance()->getLogger()->info('foobar: query finished');
     return $files;
 }
예제 #3
0
파일: BranchPeer.php 프로젝트: ratibus/Crew
 /**
  * @static
  * @param GitCommand $gitCommand
  * @param Repository $repository
  * @param Branch $branch
  * @param bool $deleteOnly
  * @return void
  */
 public static function synchronize(GitCommand $gitCommand, Repository $repository, Branch $branch, $deleteOnly = false)
 {
     $branchGit = $gitCommand->getNoMergedBranchInfos($repository->getGitDir(), $branch->getBaseBranchName(), $branch->getName());
     $branchModel = BranchQuery::create()->filterByRepositoryId($repository->getId())->filterByName($branch->getName())->findOne();
     if ($branchModel) {
         if (is_null($branchGit)) {
             $branchModel->delete();
         } elseif (!$branchModel->getIsBlacklisted() && !$deleteOnly) {
             $lastSynchronizationCommit = $branchModel->getLastCommit();
             $branchModel->setCommitReference($branchGit['commit_reference']);
             $branchModel->setLastCommit($branchGit['last_commit']);
             $branchModel->setLastCommitDesc($branchGit['last_commit_desc']);
             $branchModel->save();
             return FilePeer::synchronize($gitCommand, $branchModel, $lastSynchronizationCommit);
         }
     }
     return 0;
 }
예제 #4
0
 /**
  * @param sfWebRequest $request
  * @return void
  */
 public function execute($request)
 {
     $this->file = FilePeer::retrieveByPK($request->getParameter('file'));
     $this->forward404Unless($this->file, "File not found");
     $this->getResponse()->setTitle(basename($this->file->getFilename()));
     $this->previousFileId = FileQuery::create()->select('Id')->filterByBranchId($this->file->getBranchId())->filterByFilename($this->file->getFilename(), Criteria::LESS_THAN)->filterByIsBinary(false)->orderByFilename(Criteria::DESC)->findOne();
     $this->nextFileId = FileQuery::create()->select('Id')->filterByBranchId($this->file->getBranchId())->filterByFilename($this->file->getFilename(), Criteria::GREATER_THAN)->filterByIsBinary(false)->orderByFilename(Criteria::ASC)->findOne();
     $this->branch = BranchPeer::retrieveByPK($this->file->getBranchId());
     $this->forward404Unless($this->branch, "Branch not found");
     $this->repository = RepositoryPeer::retrieveByPK($this->branch->getRepositoryId());
     $this->forward404Unless($this->repository, "Repository not found");
     $options = array();
     if ($request->getParameter('s', false)) {
         $options['ignore-all-space'] = true;
     }
     $this->fileContentLines = $this->gitCommand->getShowFileFromBranch($this->repository->getGitDir(), $this->branch->getCommitReference(), $this->file->getLastChangeCommit(), $this->file->getFilename(), $options);
     $fileLineCommentsModel = CommentQuery::create()->filterByFileId($this->file->getId())->filterByCommit($this->file->getLastChangeCommit())->filterByType(CommentPeer::TYPE_LINE)->find();
     $this->userId = $this->getUser()->getId();
     $this->fileLineComments = array();
     foreach ($fileLineCommentsModel as $fileLineCommentModel) {
         $this->fileLineComments[$fileLineCommentModel->getPosition()][] = $fileLineCommentModel;
     }
 }
예제 #5
0
 /**
  * Selects a collection of CollectionFile objects pre-filled with all related objects except Collection.
  *
  * @param      Criteria  $criteria
  * @param      PropelPDO $con
  * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
  * @return     array Array of CollectionFile objects.
  * @throws     PropelException Any exceptions caught during processing will be
  *		 rethrown wrapped into a PropelException.
  */
 public static function doSelectJoinAllExceptCollection(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
 {
     $criteria = clone $criteria;
     // Set the correct dbName if it has not been overridden
     // $criteria->getDbName() will return the same object if not set to another value
     // so == check is okay and faster
     if ($criteria->getDbName() == Propel::getDefaultDB()) {
         $criteria->setDbName(self::DATABASE_NAME);
     }
     CollectionFilePeer::addSelectColumns($criteria);
     $startcol2 = CollectionFilePeer::NUM_COLUMNS - CollectionFilePeer::NUM_LAZY_LOAD_COLUMNS;
     FilePeer::addSelectColumns($criteria);
     $startcol3 = $startcol2 + (FilePeer::NUM_COLUMNS - FilePeer::NUM_LAZY_LOAD_COLUMNS);
     $criteria->addJoin(CollectionFilePeer::FILE_ID, FilePeer::ID, $join_behavior);
     // symfony_behaviors behavior
     foreach (sfMixer::getCallables(self::getMixerPreSelectHook(__FUNCTION__)) as $sf_hook) {
         call_user_func($sf_hook, 'BaseCollectionFilePeer', $criteria, $con);
     }
     $stmt = BasePeer::doSelect($criteria, $con);
     $results = array();
     while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
         $key1 = CollectionFilePeer::getPrimaryKeyHashFromRow($row, 0);
         if (null !== ($obj1 = CollectionFilePeer::getInstanceFromPool($key1))) {
             // We no longer rehydrate the object, since this can cause data loss.
             // See http://propel.phpdb.org/trac/ticket/509
             // $obj1->hydrate($row, 0, true); // rehydrate
         } else {
             $cls = CollectionFilePeer::getOMClass(false);
             $obj1 = new $cls();
             $obj1->hydrate($row);
             CollectionFilePeer::addInstanceToPool($obj1, $key1);
         }
         // if obj1 already loaded
         // Add objects for joined File rows
         $key2 = FilePeer::getPrimaryKeyHashFromRow($row, $startcol2);
         if ($key2 !== null) {
             $obj2 = FilePeer::getInstanceFromPool($key2);
             if (!$obj2) {
                 $cls = FilePeer::getOMClass(false);
                 $obj2 = new $cls();
                 $obj2->hydrate($row, $startcol2);
                 FilePeer::addInstanceToPool($obj2, $key2);
             }
             // if $obj2 already loaded
             // Add the $obj1 (CollectionFile) to the collection in $obj2 (File)
             $obj2->addCollectionFile($obj1);
         }
         // if joined row is not null
         $results[] = $obj1;
     }
     $stmt->closeCursor();
     return $results;
 }
예제 #6
0
 /**
  * Retrieve multiple objects by pkey.
  *
  * @param      array $pks List of primary keys
  * @param      PropelPDO $con the connection to use
  * @throws     PropelException Any exceptions caught during processing will be
  *		 rethrown wrapped into a PropelException.
  */
 public static function retrieveByPKs($pks, PropelPDO $con = null)
 {
     if ($con === null) {
         $con = Propel::getConnection(FilePeer::DATABASE_NAME, Propel::CONNECTION_READ);
     }
     $objs = null;
     if (empty($pks)) {
         $objs = array();
     } else {
         $criteria = new Criteria(FilePeer::DATABASE_NAME);
         $criteria->add(FilePeer::ID, $pks, Criteria::IN);
         $objs = FilePeer::doSelect($criteria, $con);
     }
     return $objs;
 }
예제 #7
0
파일: actions.class.php 프로젝트: EQ4/smint
 /** This is executed when searched for related tracks and metadata */
 public function executeRelatedtrack(sfWebRequest $request)
 {
     $this->getContext()->getConfiguration()->loadHelpers('Url');
     $empty_metadatafilteredquery = false;
     $distances = NULL;
     $files = NULL;
     // get request parameters
     $metadataquery = $request->getParameter('metadataquery');
     $tracknr = $request->getParameter('tracknr');
     $limit = $request->getParameter('limit', $this->getContext()->getConfiguration()->getSmintMaxQueryResults());
     $offset = $request->getParameter('offset', 0);
     $id_prefix = $request->getParameter('id_prefix', '') . smintTools::generateHtmlId($tracknr) . "_";
     $omit_empty_metadataquery = $request->getParameter('omit_empty_metadataquery', false);
     $distancetypeid = sfConfig::get('app_defaults_distancetypeid', 0);
     $featurevectortypeid = sfConfig::get('app_defaults_featurevectortypeid', 0);
     mysfLog::logRequest($this, $request);
     //get file via external key
     $file = FilePeer::getFileByExternalKey($tracknr);
     //only if the file was found in the smafestore db
     if ($file) {
         // run query
         $fileTrackId = $file->getTrackid();
         $relatedCriteria = $this->buildRelatedQuery($fileTrackId, $featurevectortypeid, $distancetypeid, $limit, $offset, $metadataquery);
         $related = FilePeer::doSelect($relatedCriteria);
         // if omit empty metadataquery is true
         if ($omit_empty_metadataquery) {
             if (count($related) > 0) {
                 // if the query returned results
                 $distances = DistancePeer::doSelect($relatedCriteria);
             } else {
                 // if the query returned no results -> retry without metadata
                 $empty_metadatafilteredquery = true;
                 $relatedCriteria = $this->buildRelatedQuery($fileTrackId, $featurevectortypeid, $distancetypeid, $limit, $offset);
                 $related = FilePeer::doSelect($relatedCriteria);
                 $distances = DistancePeer::doSelect($relatedCriteria);
             }
         } else {
             $distances = DistancePeer::doSelect($relatedCriteria);
         }
     }
     $files = FiledescPeer::doSelect($relatedCriteria);
     // add duration
     //		$fileDownloadURL = url_for("getAudioFile/download") . "?tracknr=" . rawurlencode($tracknr);
     $queryFileMetadata = FiledescPeer::retrieveByPk($tracknr);
     $fileInfoName = $queryFileMetadata->getTitle() . " - " . $queryFileMetadata->getPerformers();
     $uploadedFilePHPUrl_incomplete = url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($tracknr);
     $uploadedFileURL = smintUploadFileHelper::getDirectFileUrl($file->getUri());
     return $this->renderPartial('search/result', array('render' => 'related', 'uploadedFilePHPUrl_incomplete' => $uploadedFilePHPUrl_incomplete, 'uploadedFileURL' => $uploadedFileURL, 'seedLabel' => $fileInfoName, 'id_prefix' => $id_prefix, 'tracknr' => $tracknr, 'files' => $files, 'distances' => $distances, 'limit' => $limit, 'offset' => $offset, 'metadataquery' => $metadataquery, 'empty_metadatafilteredquery' => $empty_metadatafilteredquery, 'aSegmSearch' => $aSegmSearch));
 }
예제 #8
0
 /**
  * Selects a collection of StatusAction objects pre-filled with all related objects except Branch.
  *
  * @param      Criteria  $criteria
  * @param      PropelPDO $con
  * @param      String    $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN
  * @return     array Array of StatusAction objects.
  * @throws     PropelException Any exceptions caught during processing will be
  *		 rethrown wrapped into a PropelException.
  */
 public static function doSelectJoinAllExceptBranch(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN)
 {
     $criteria = clone $criteria;
     // Set the correct dbName if it has not been overridden
     // $criteria->getDbName() will return the same object if not set to another value
     // so == check is okay and faster
     if ($criteria->getDbName() == Propel::getDefaultDB()) {
         $criteria->setDbName(self::DATABASE_NAME);
     }
     StatusActionPeer::addSelectColumns($criteria);
     $startcol2 = StatusActionPeer::NUM_HYDRATE_COLUMNS;
     sfGuardUserPeer::addSelectColumns($criteria);
     $startcol3 = $startcol2 + sfGuardUserPeer::NUM_HYDRATE_COLUMNS;
     RepositoryPeer::addSelectColumns($criteria);
     $startcol4 = $startcol3 + RepositoryPeer::NUM_HYDRATE_COLUMNS;
     FilePeer::addSelectColumns($criteria);
     $startcol5 = $startcol4 + FilePeer::NUM_HYDRATE_COLUMNS;
     $criteria->addJoin(StatusActionPeer::USER_ID, sfGuardUserPeer::ID, $join_behavior);
     $criteria->addJoin(StatusActionPeer::REPOSITORY_ID, RepositoryPeer::ID, $join_behavior);
     $criteria->addJoin(StatusActionPeer::FILE_ID, FilePeer::ID, $join_behavior);
     // symfony_behaviors behavior
     foreach (sfMixer::getCallables(self::getMixerPreSelectHook(__FUNCTION__)) as $sf_hook) {
         call_user_func($sf_hook, 'BaseStatusActionPeer', $criteria, $con);
     }
     $stmt = BasePeer::doSelect($criteria, $con);
     $results = array();
     while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
         $key1 = StatusActionPeer::getPrimaryKeyHashFromRow($row, 0);
         if (null !== ($obj1 = StatusActionPeer::getInstanceFromPool($key1))) {
             // We no longer rehydrate the object, since this can cause data loss.
             // See http://www.propelorm.org/ticket/509
             // $obj1->hydrate($row, 0, true); // rehydrate
         } else {
             $cls = StatusActionPeer::getOMClass(false);
             $obj1 = new $cls();
             $obj1->hydrate($row);
             StatusActionPeer::addInstanceToPool($obj1, $key1);
         }
         // if obj1 already loaded
         // Add objects for joined sfGuardUser rows
         $key2 = sfGuardUserPeer::getPrimaryKeyHashFromRow($row, $startcol2);
         if ($key2 !== null) {
             $obj2 = sfGuardUserPeer::getInstanceFromPool($key2);
             if (!$obj2) {
                 $cls = sfGuardUserPeer::getOMClass(false);
                 $obj2 = new $cls();
                 $obj2->hydrate($row, $startcol2);
                 sfGuardUserPeer::addInstanceToPool($obj2, $key2);
             }
             // if $obj2 already loaded
             // Add the $obj1 (StatusAction) to the collection in $obj2 (sfGuardUser)
             $obj2->addStatusAction($obj1);
         }
         // if joined row is not null
         // Add objects for joined Repository rows
         $key3 = RepositoryPeer::getPrimaryKeyHashFromRow($row, $startcol3);
         if ($key3 !== null) {
             $obj3 = RepositoryPeer::getInstanceFromPool($key3);
             if (!$obj3) {
                 $cls = RepositoryPeer::getOMClass(false);
                 $obj3 = new $cls();
                 $obj3->hydrate($row, $startcol3);
                 RepositoryPeer::addInstanceToPool($obj3, $key3);
             }
             // if $obj3 already loaded
             // Add the $obj1 (StatusAction) to the collection in $obj3 (Repository)
             $obj3->addStatusAction($obj1);
         }
         // if joined row is not null
         // Add objects for joined File rows
         $key4 = FilePeer::getPrimaryKeyHashFromRow($row, $startcol4);
         if ($key4 !== null) {
             $obj4 = FilePeer::getInstanceFromPool($key4);
             if (!$obj4) {
                 $cls = FilePeer::getOMClass(false);
                 $obj4 = new $cls();
                 $obj4->hydrate($row, $startcol4);
                 FilePeer::addInstanceToPool($obj4, $key4);
             }
             // if $obj4 already loaded
             // Add the $obj1 (StatusAction) to the collection in $obj4 (File)
             $obj4->addStatusAction($obj1);
         }
         // if joined row is not null
         $results[] = $obj1;
     }
     $stmt->closeCursor();
     return $results;
 }
예제 #9
0
파일: BaseTrack.php 프로젝트: EQ4/smint
 /**
  * Returns the number of related File objects.
  *
  * @param      Criteria $criteria
  * @param      boolean $distinct
  * @param      PropelPDO $con
  * @return     int Count of related File objects.
  * @throws     PropelException
  */
 public function countFiles(Criteria $criteria = null, $distinct = false, PropelPDO $con = null)
 {
     if ($criteria === null) {
         $criteria = new Criteria(TrackPeer::DATABASE_NAME);
     } else {
         $criteria = clone $criteria;
     }
     if ($distinct) {
         $criteria->setDistinct();
     }
     $count = null;
     if ($this->collFiles === null) {
         if ($this->isNew()) {
             $count = 0;
         } else {
             $criteria->add(FilePeer::TRACK_ID, $this->id);
             $count = FilePeer::doCount($criteria, false, $con);
         }
     } else {
         // criteria has no effect for a new object
         if (!$this->isNew()) {
             // the following code is to determine if a new query is
             // called for.  If the criteria is the same as the last
             // one, just return count of the collection.
             $criteria->add(FilePeer::TRACK_ID, $this->id);
             if (!isset($this->lastFileCriteria) || !$this->lastFileCriteria->equals($criteria)) {
                 $count = FilePeer::doCount($criteria, false, $con);
             } else {
                 $count = count($this->collFiles);
             }
         } else {
             $count = count($this->collFiles);
         }
     }
     return $count;
 }
예제 #10
0
 /**
  * Find object by primary key using raw SQL to go fast.
  * Bypass doSelect() and the object formatter by using generated code.
  *
  * @param     mixed $key Primary key to use for the query
  * @param     PropelPDO $con A connection object
  *
  * @return    File A model object, or null if the key is not found
  */
 protected function findPkSimple($key, $con)
 {
     $sql = 'SELECT `ID`, `BRANCH_ID`, `STATE`, `FILENAME`, `IS_BINARY`, `COMMIT_REFERENCE`, `REVIEW_REQUEST`, `NB_ADDED_LINES`, `NB_DELETED_LINES`, `LAST_CHANGE_COMMIT`, `LAST_CHANGE_COMMIT_DESC`, `LAST_CHANGE_COMMIT_USER`, `STATUS`, `COMMIT_STATUS_CHANGED`, `USER_STATUS_CHANGED`, `DATE_STATUS_CHANGED` FROM `file` WHERE `ID` = :p0';
     try {
         $stmt = $con->prepare($sql);
         $stmt->bindValue(':p0', $key, PDO::PARAM_INT);
         $stmt->execute();
     } catch (Exception $e) {
         Propel::log($e->getMessage(), Propel::LOG_ERR);
         throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
     }
     $obj = null;
     if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
         $obj = new File();
         $obj->hydrate($row);
         FilePeer::addInstanceToPool($obj, (string) $row[0]);
     }
     $stmt->closeCursor();
     return $obj;
 }
예제 #11
0
파일: BaseFile.php 프로젝트: EQ4/smint
 /**
  * Populates the object using an array.
  *
  * This is particularly useful when populating an object from one of the
  * request arrays (e.g. $_POST).  This method goes through the column
  * names, checking to see whether a matching key exists in populated
  * array. If so the setByName() method is called for that column.
  *
  * You can specify the key type of the array by additionally passing one
  * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
  * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
  * The default key type is the column's phpname (e.g. 'AuthorId')
  *
  * @param      array  $arr     An array to populate the object from.
  * @param      string $keyType The type of keys the array uses.
  * @return     void
  */
 public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
 {
     $keys = FilePeer::getFieldNames($keyType);
     if (array_key_exists($keys[0], $arr)) {
         $this->setId($arr[$keys[0]]);
     }
     if (array_key_exists($keys[1], $arr)) {
         $this->setHash($arr[$keys[1]]);
     }
     if (array_key_exists($keys[2], $arr)) {
         $this->setTrackId($arr[$keys[2]]);
     }
     if (array_key_exists($keys[3], $arr)) {
         $this->setInserted($arr[$keys[3]]);
     }
     if (array_key_exists($keys[4], $arr)) {
         $this->setUpdated($arr[$keys[4]]);
     }
     if (array_key_exists($keys[5], $arr)) {
         $this->setInputFormat($arr[$keys[5]]);
     }
     if (array_key_exists($keys[6], $arr)) {
         $this->setUri($arr[$keys[6]]);
     }
     if (array_key_exists($keys[7], $arr)) {
         $this->setSamplef($arr[$keys[7]]);
     }
     if (array_key_exists($keys[8], $arr)) {
         $this->setBitrate($arr[$keys[8]]);
     }
     if (array_key_exists($keys[9], $arr)) {
         $this->setChannels($arr[$keys[9]]);
     }
     if (array_key_exists($keys[10], $arr)) {
         $this->setEncoding($arr[$keys[10]]);
     }
     if (array_key_exists($keys[11], $arr)) {
         $this->setSamplebit($arr[$keys[11]]);
     }
     if (array_key_exists($keys[12], $arr)) {
         $this->setExternalKey($arr[$keys[12]]);
     }
     if (array_key_exists($keys[13], $arr)) {
         $this->setGuid($arr[$keys[13]]);
     }
 }
예제 #12
0
 /**
  * This is a method for emulating ON DELETE CASCADE for DBs that don't support this
  * feature (like MySQL or SQLite).
  *
  * This method is not very speedy because it must perform a query first to get
  * the implicated records and then perform the deletes by calling those Peer classes.
  *
  * This method should be used within a transaction if possible.
  *
  * @param      Criteria $criteria
  * @param      PropelPDO $con
  * @return     int The number of affected rows (if supported by underlying database driver).
  */
 protected static function doOnDeleteCascade(Criteria $criteria, PropelPDO $con)
 {
     // initialize var to track total num of affected rows
     $affectedRows = 0;
     // first find the objects that are implicated by the $criteria
     $objects = BranchPeer::doSelect($criteria, $con);
     foreach ($objects as $obj) {
         // delete related Comment objects
         $criteria = new Criteria(CommentPeer::DATABASE_NAME);
         $criteria->add(CommentPeer::BRANCH_ID, $obj->getId());
         $affectedRows += CommentPeer::doDelete($criteria, $con);
         // delete related File objects
         $criteria = new Criteria(FilePeer::DATABASE_NAME);
         $criteria->add(FilePeer::BRANCH_ID, $obj->getId());
         $affectedRows += FilePeer::doDelete($criteria, $con);
         // delete related StatusAction objects
         $criteria = new Criteria(StatusActionPeer::DATABASE_NAME);
         $criteria->add(StatusActionPeer::BRANCH_ID, $obj->getId());
         $affectedRows += StatusActionPeer::doDelete($criteria, $con);
     }
     return $affectedRows;
 }
예제 #13
0
 /**
  * Get the associated File object
  *
  * @param      PropelPDO Optional Connection object.
  * @return     File The associated File object.
  * @throws     PropelException
  */
 public function getFile(PropelPDO $con = null)
 {
     if ($this->aFile === null && $this->file_id !== null) {
         $this->aFile = FilePeer::retrieveByPk($this->file_id);
         /* The following can be used additionally to
         		   guarantee the related object contains a reference
         		   to this object.  This level of coupling may, however, be
         		   undesirable since it could result in an only partially populated collection
         		   in the referenced object.
         		   $this->aFile->addCollectionFiles($this);
         		 */
     }
     return $this->aFile;
 }
예제 #14
0
파일: actions.class.php 프로젝트: EQ4/smint
 /** provides the file as download/streaming
  * Request params:
  * - tracknr
  * - fileid
  * - uploaded
  * 		( either tracknr or fileid or uploaded is required)
  * - format		optional. One of: mp3, ogg. If format is given, the file is converted to the given format, using command line invocations that are configured in app.yml
  *
  *
  */
 public function executeDownload(sfWebRequest $request)
 {
     // write session, so it won't lock other requests
     session_write_close();
     $reqparamUploaded = $this->getRequestParameter('uploaded');
     if ($reqparamUploaded) {
         $filename = smintUploadFileHelper::getUploadPath() . $reqparamUploaded;
     } else {
         $tracknr = $this->getRequestParameter('tracknr');
         if ($tracknr) {
             $file = FilePeer::getFileByExternalKey($tracknr);
             $filekey = $tracknr;
         } else {
             # check if file.id is given
             $fileid = $this->getRequestParameter('fileid');
             $file = FilePeer::retrieveByPK($fileid);
             $filekey = $fileid;
         }
         //check if a file was found matching tracknr, else exit with 404
         if ($file) {
             $filename = $file->getUri();
         } else {
             $this->forward404("file not found in database.");
         }
     }
     //check if a tracknr is given, otherwise exit with 404
     if (!$filename) {
         $this->forward404("Invalid query! Provide tracknr, fileid or uploaded to get a file.");
     }
     if (file_exists($filename)) {
         //check if file is inside the folder configured in smint/config/app.yml
         // or inside the upload folder
         $mp3Path = dirname(sfConfig::get('app_files_mp3path') . "/file");
         if (strpos($filename, $mp3Path) === false && strpos($filename, smintUploadFileHelper::getUploadPath()) === false) {
             $this->forward404("file: {$filename} is outside of the configured path (app.yml): {$mp3Path}. Accessing files outside the path is not allowed. Check app.yml and URI in file table.");
         }
         // -----------------------------------------------
         // -------------- check for format --------------
         // if no format is given,
         $reqparamFormat = $this->getRequestParameter('format');
         if ($reqparamFormat) {
             if (substr($filename, -3) === $reqparamFormat) {
                 mysfLog::log($this, "INFO: format parameter equals original audio file suffix. No conversion.");
                 if ($reqparamFormat === "mp3") {
                     $contenttype = "audio/mpeg";
                 } else {
                     $contenttype = "audio/{$reqparamFormat}";
                 }
             } else {
                 // conversion
                 if ($reqparamFormat === "ogg") {
                     $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat);
                     $contenttype = "audio/ogg";
                 } else {
                     if ($reqparamFormat === "mp3") {
                         $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat);
                         $contenttype = "audio/mpeg";
                     } else {
                         if ($reqparamFormat === "waveform") {
                             $filename = smintFileserverHelper::doFileConversion($filename, $reqparamFormat);
                             $contenttype = "application/txt";
                         } else {
                             if ($reqparamFormat === "png") {
                                 $waveformfilename = smintFileserverHelper::doFileConversion($filename, "waveform");
                                 $wfdata = split(", ", file_get_contents($waveformfilename));
                                 //mysfLog::log($this, print_r($wfdata, true));
                                 // how much detail we want. Larger number means less detail
                                 // (basically, how many bytes/frames to skip processing)
                                 // the lower the number means longer processing time
                                 // EP: in SMINT we do not chagne this. To change the detail, edit your waveform_resolution
                                 // config param in app.yml!
                                 define("DETAIL", 1);
                                 // get user vars from form
                                 $width = $this->getRequestParameter('width') ? rawurldecode($this->getRequestParameter('width')) : 640;
                                 $height = $this->getRequestParameter('height') ? rawurldecode($this->getRequestParameter('height')) : 100;
                                 $foreground = $this->getRequestParameter('fg') ? rawurldecode($this->getRequestParameter('fg')) : "#4D4D4D";
                                 $background = $this->getRequestParameter('bg') ? rawurldecode($this->getRequestParameter('bg')) : "#ffffff";
                                 $maxval = 0;
                                 $factor = sfConfig::get('app_defaults_waveform_factor', 0.8);
                                 // create original image width based on amount of detail
                                 $img = imagecreatetruecolor(sizeof($wfdata) / DETAIL, $height);
                                 // apply factor to the data
                                 //$wfdata_factor = array_map("this->pow_func", $wfdata);
                                 for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) {
                                     $wfdata[$i] = pow(abs($wfdata[$i]), $factor);
                                 }
                                 $datamaxval = max(array_map("abs", $wfdata));
                                 $normconstant = doubleval($height) / doubleval($datamaxval);
                                 for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) {
                                     $wfdata[$i] = $wfdata[$i] * $normconstant;
                                 }
                                 /*
                                 						for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) {
                                 
                                 							if (abs($wfdata[$i]) > $maxval) {
                                 								$maxval = $wfdata[$i];
                                 							}
                                 						}
                                 						if ($maxval < 40) {
                                 							for ($i = 0; $i < sizeof($wfdata); $i += DETAIL) {
                                 								$wfdata[$i] = pow(abs($wfdata[$i]), 1.4);
                                 							}
                                 						}
                                  * */
                                 // fill background of image
                                 if ($background == "") {
                                     imagesavealpha($img, true);
                                     $transparentColor = imagecolorallocatealpha($img, 0, 0, 0, 127);
                                     imagefill($img, 0, 0, $transparentColor);
                                 } else {
                                     list($r, $g, $b) = smintTools::html2rgb($background);
                                     imagefilledrectangle($img, 0, 0, sizeof($wfdata) / DETAIL, $height, imagecolorallocate($img, $r, $g, $b));
                                 }
                                 // generate foreground color
                                 list($r, $g, $b) = smintTools::html2rgb($foreground);
                                 // loop through frames/bytes of wav data as genearted above
                                 for ($d = 0; $d < sizeof($wfdata); $d += DETAIL) {
                                     // relative value based on height of image being generated
                                     // data values can range between -127 and 128
                                     $v = $wfdata[$d];
                                     //$v = pow($v, sfConfig::get('app_defaults_waveform_factor', 0.8));
                                     // draw the line on the image using the $v value and centering it vertically on the canvas
                                     imageline($img, $d / DETAIL, ($height - $v) / 2, $d / DETAIL, ($height + $v) / 2, imagecolorallocate($img, $r, $g, $b));
                                 }
                                 // want it resized?
                                 if ($width != imagesx($img)) {
                                     // resample the image to the proportions defined in the form
                                     $rimg = imagecreatetruecolor($width, $height);
                                     // save alpha from original image
                                     imagesavealpha($rimg, true);
                                     imagealphablending($rimg, false);
                                     // copy to resized
                                     imagecopyresampled($rimg, $img, 0, 0, 0, 0, $width, $height, sizeof($wfdata) / DETAIL, $height);
                                     $img = $rimg;
                                 }
                                 $contenttype = "image/png";
                                 header("Content-type: {$contenttype}");
                                 imagepng($img);
                                 imagedestroy($img);
                                 // dont render view
                                 return sfView::NONE;
                             } else {
                                 $error_message = "ERROR: Format {$reqparamFormat} not valid";
                                 mysfLog::log($this, $error_message);
                                 throw new Exception($error_message);
                             }
                         }
                     }
                 }
             }
         } else {
             mysfLog::log($this, "INFO: format parameter not given, sending the original file ");
             // assuming file ending as content type. Just an approximation
             $contenttype = "audio/" . substr($filename, -3);
         }
         // do a redirect to file to have apache handle it
         $this->redirect(smintUploadFileHelper::getDirectFileUrl_for_uploads($filename));
         /* alternate version of redirect (not using symf framework)
         			 * does not work better :-(
         			 *
         			 $url = smintUploadFileHelper::getDirectFileUrl_for_uploads($filename);
         			 $statusCode = 302;
         			 // redirect
         			 $response = $this->context->getResponse();
         			 $response->clearHttpHeaders();
         			 $response->setStatusCode($statusCode);
         			 $response->setHttpHeader('Location', $url);
         			 $response->send();
         
         			 throw new sfStopException();
         			 // we do not reach this part b/o the redirect!
         			 *
         			 */
         // ------------ delegate to helper for download
         // serves file, obeying the range header
         smintFileserverHelper::serve_file_resumable($this->getResponse(), $filename, $contenttype);
         // dont render view
         return sfView::NONE;
         //return sfView::HEADER_ONLY;
     } else {
         $missingfile = $filename ? $filename : "No filename found!";
         $this->forward404("file for tracknr:  not found: " . $missingfile);
     }
 }
예제 #15
0
파일: BaseFile.php 프로젝트: ratibus/Crew
 /**
  * Populates the object using an array.
  *
  * This is particularly useful when populating an object from one of the
  * request arrays (e.g. $_POST).  This method goes through the column
  * names, checking to see whether a matching key exists in populated
  * array. If so the setByName() method is called for that column.
  *
  * You can specify the key type of the array by additionally passing one
  * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
  * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
  * The default key type is the column's phpname (e.g. 'AuthorId')
  *
  * @param      array  $arr     An array to populate the object from.
  * @param      string $keyType The type of keys the array uses.
  * @return     void
  */
 public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
 {
     $keys = FilePeer::getFieldNames($keyType);
     if (array_key_exists($keys[0], $arr)) {
         $this->setId($arr[$keys[0]]);
     }
     if (array_key_exists($keys[1], $arr)) {
         $this->setBranchId($arr[$keys[1]]);
     }
     if (array_key_exists($keys[2], $arr)) {
         $this->setState($arr[$keys[2]]);
     }
     if (array_key_exists($keys[3], $arr)) {
         $this->setFilename($arr[$keys[3]]);
     }
     if (array_key_exists($keys[4], $arr)) {
         $this->setIsBinary($arr[$keys[4]]);
     }
     if (array_key_exists($keys[5], $arr)) {
         $this->setCommitReference($arr[$keys[5]]);
     }
     if (array_key_exists($keys[6], $arr)) {
         $this->setReviewRequest($arr[$keys[6]]);
     }
     if (array_key_exists($keys[7], $arr)) {
         $this->setNbAddedLines($arr[$keys[7]]);
     }
     if (array_key_exists($keys[8], $arr)) {
         $this->setNbDeletedLines($arr[$keys[8]]);
     }
     if (array_key_exists($keys[9], $arr)) {
         $this->setLastChangeCommit($arr[$keys[9]]);
     }
     if (array_key_exists($keys[10], $arr)) {
         $this->setLastChangeCommitDesc($arr[$keys[10]]);
     }
     if (array_key_exists($keys[11], $arr)) {
         $this->setLastChangeCommitUser($arr[$keys[11]]);
     }
     if (array_key_exists($keys[12], $arr)) {
         $this->setStatus($arr[$keys[12]]);
     }
     if (array_key_exists($keys[13], $arr)) {
         $this->setCommitStatusChanged($arr[$keys[13]]);
     }
     if (array_key_exists($keys[14], $arr)) {
         $this->setUserStatusChanged($arr[$keys[14]]);
     }
     if (array_key_exists($keys[15], $arr)) {
         $this->setDateStatusChanged($arr[$keys[15]]);
     }
 }
예제 #16
0
파일: mp3Handler.php 프로젝트: EQ4/smint
 /** Returns appropriate JS code for mp3 player config.
  * @param $files Array of Filedesc instances
  * @param $aSegmSearch Array with segmentation information
  *
  */
 public static function getMp3PlayerConfig($files = array(), $aSegmSearch = array())
 {
     //needed for javascript_tag
     use_helper('JavascriptBase');
     $player = sfConfig::get('app_mp3player_defaultplayer', 'worldpress');
     switch ($player) {
         case 'flash-mp3-player':
             return '';
             break;
         case 'worldpress':
             $playerConfig = sfConfig::get('app_mp3player_worldpress');
             $autostart = isset($playerConfig['autostart']) ? $playerConfig['autostart'] : 'yes';
             $width = isset($playerConfig['width']) ? $playerConfig['width'] : '200';
             $skin = $playerConfig['skin'];
             return javascript_tag("AudioPlayer.setup('" . public_path('audio-player/player.swf') . "', \n                  {\n                    width: '{$width}', \n                    autostart: '{$autostart}', \n                    animation: 'no', \n                    {$skin},\n                  });");
             break;
         case 'smintplayer':
         default:
             // get configuration
             $playerConfig = sfConfig::get('app_mp3player_smintplayer');
             // build options array of array. First dimension is list of files, second is assoc array with values for the player
             $options = array();
             if (!isset($aSegmSearch['enabled'])) {
                 $aSegmSearch['enabled'] = false;
             }
             foreach ($files as $i => $filedesc) {
                 $filerec = FilePeer::getFileByExternalKey($filedesc->getTracknr());
                 if (!isset($filerec)) {
                     // no recrod returned - maybe no metadata in the db?
                     $tmparray = array('text' => "(No metadata available)", 'audiofile_mp3' => url_for("getAudioFile/download", true) . "?fileid=" . rawurlencode($filedesc->getTracknr()) . "&format=mp3", 'audiofile_ogg' => url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($filedesc->getTracknr()) . "&format=ogg", 'waveformfile' => url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($filedesc->getTracknr()) . "&format=waveform", 'duration' => isset($iDurationMs) ? $iDurationMs : 0, 'segments' => $aSegmSearch['enabled'] ? $aSegmSearch['resultsegments'][$i] : array(), 'searchsimilarfunc' => 'smint_' . smintTools::generateHtmlId($filedesc->getTracknr()) . '()', 'backlinktext' => "License track from gettyimages music", 'backlinkurl' => url_for("search/redirect") . "?url=" . rawurlencode("http://www.gettyimages.at/music/download-songs/" . $filedesc->getTracknr() . "?ref=spec"));
                 } else {
                     $iBitrate = $filerec->getBitrate();
                     $sUri = $filerec->getUri();
                     // estimate duration
                     if (file_exists($sUri)) {
                         $iSize = filesize($sUri);
                         if ($iSize) {
                             // file size divided by bytes per second, times 1000 to get ms.
                             // bitrate is k bits per second, so multiply by 1024 to get bits, and divide by 8 to get bytes
                             $iDurationMs = intval($iSize / ($iBitrate * 1024 / 8) * 1000);
                         } else {
                             mysfLog::log($this, "DEBUG Could not read file size: {$sUri}");
                             $iDurationMs = 0;
                         }
                     } else {
                         mysfLog::log($this, "WARNING File does not exist: {$sUri}");
                         $iDurationMs = 0;
                     }
                     $tmparray = array('text' => $filedesc->getTitle() . ' | ' . $filedesc->getPerformers() . ' | ' . $filedesc->getGenre(), 'audiofile_mp3' => smintUploadFileHelper::getDirectFileUrl($filerec->getUri()), 'audiofile_ogg' => url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($filedesc->getTracknr()) . "&format=ogg", 'waveformfile' => url_for("getAudioFile/download", true) . "?tracknr=" . rawurlencode($filedesc->getTracknr()) . "&format=waveform", 'duration' => isset($iDurationMs) ? $iDurationMs : 0, 'segments' => $aSegmSearch['enabled'] ? $aSegmSearch['resultsegments'][$i] : array(), 'searchsimilarfunc' => 'smint_' . smintTools::generateHtmlId($filedesc->getTracknr()) . '()', 'backlinktext' => "License track from gettyimages music", 'backlinkurl' => url_for("search/redirect") . "?url=" . rawurlencode("http://www.gettyimages.at/music/download-songs/" . $filedesc->getTracknr() . "?ref=spec"));
                 }
                 $options[] = $tmparray;
             }
             // we cannot put all these fields into one array since the output format must be like
             // , A: XXXX, B: XXX
             // and not
             //, {A: XXXX, B: XXX}
             return ", playlist: " . smintTools::my_options_for_javascript($options) . ", waveform_resolution: " . intval(sfConfig::get('app_defaults_waveform_resolution')) . ', waveform_factor: ' . doubleval(sfConfig::get('app_defaults_waveform_factor'));
             break;
     }
 }