public function testShouldSaveResource() { $sResource = self::RESOURCE_PATH . DIRECTORY_SEPARATOR . self::RESOURCE_FILE; $sThumbsPath = self::THUMBNAIL_FOLDER . DIRECTORY_SEPARATOR . self::PATH_PREFIX; //THEN $this->oStandardMock->expects($this->once())->method('is_file')->with($this->equalTo($sResource))->will($this->returnValue(true)); $this->oStandardMock->expects($this->once())->method('mkdir')->with($this->equalTo($sThumbsPath), $this->equalTo(octdec(self::THUMBNAIL_DIR_CHMOD)))->will($this->returnValue(true)); $this->oStandardMock->expects($this->once())->method('copy')->with($this->equalTo($sResource), $this->equalTo($sThumbsPath . DIRECTORY_SEPARATOR . self::RESOURCE_FILE))->will($this->returnValue(true)); $this->oStandardMock->expects($this->once())->method('chmod')->with($this->equalTo($sThumbsPath . DIRECTORY_SEPARATOR . self::RESOURCE_FILE), $this->equalTo(octdec(self::THUMBNAIL_FILE_CHMOD)))->will($this->returnValue(true)); //WHEN $this->oStorage->addResource(self::RESOURCE_PATH . DIRECTORY_SEPARATOR . self::RESOURCE_FILE); $this->oStorage->save(); }
/** * @return AM_Tools_Standard */ public static function getInstance() { if (is_null(self::$_oInstance)) { self::$_oInstance = new self(); } return self::$_oInstance; }
/** * Save package to the local storage * * @return AM_Handler_Export_Storage_Local * @throws AM_Handler_Export_Storage_Exception */ public function savePackage() { if (is_null($this->_oPackage)) { throw new AM_Handler_Export_Storage_Exception('Package is empty'); } $this->_oPackage->savePackage(); $sPathTmp = $this->_oPackage->getPackagePath(); //Check that package exists if (!AM_Tools_Standard::getInstance()->file_exists($sPathTmp)) { throw new AM_Handler_Export_Storage_Exception(sprintf('File "%s" doesn\'t exist', $sPathTmp)); } //Prepare path on the local storage $sPackageFileName = pathinfo($sPathTmp, PATHINFO_BASENAME); $sPathToSave = $this->_buildPackagePath(); if (!AM_Tools_Standard::getInstance()->is_dir($sPathToSave)) { if (!AM_Tools_Standard::getInstance()->mkdir($sPathToSave, 0777, true)) { throw new AM_Handler_Export_Storage_Exception(sprintf('I/O error while create dir "%s"', $sPathToSave)); } } $sPathToSave .= DIRECTORY_SEPARATOR . $sPackageFileName; //Copy file to the local storage if (!AM_Tools_Standard::getInstance()->copy($sPathTmp, $sPathToSave)) { throw new AM_Handler_Export_Storage_Exception(sprintf('I/O error while copy files from "%s" to "%s"', $sPathTmp, $sPathToSave)); } AM_Tools_Standard::getInstance()->chmod($sPathToSave, 0666); $this->getHandler()->getLogger()->debug(sprintf('Package "%s" saved to "%s"', $sPathTmp, $sPathToSave)); return $this; }
/** * Set path to image file * @param string $sSourceFilePath path to image file * @return AM_Resource_Abstract * @throws AM_Resource_Exception */ protected function _setSourceFile($sSourceFilePath) { if (!AM_Tools_Standard::getInstance()->is_file($sSourceFilePath)) { throw new AM_Resource_Exception(sprintf('File \'%s\' not exists or has wrong type', $sSourceFilePath), 501); } $this->_sSourceFile = $sSourceFilePath; $aInfo = pathinfo($this->_sSourceFile); $this->_sSourceFileExtension = strtolower($aInfo['extension']); $this->_sSourceFileName = $aInfo['filename']; $this->_sSourceFileDir = $aInfo['dirname']; return $this; }
/** * Create mapper object * @param AM_Model_Db_Abstract $oModel * @param string $sProvider * @param array $aOptions * @return AM_Mapper_Abstract */ public static final function factory(AM_Model_Db_Abstract $oModel, $sProvider, $aOptions = array()) { $sModelTableName = $oModel->getTableName(); $sProvider = ucfirst(Zend_Filter::filterStatic($sProvider, 'Word_UnderscoreToCamelCase')); $sModelTableName = ucfirst(Zend_Filter::filterStatic($sModelTableName, 'Word_UnderscoreToCamelCase')); $sMapperClassName = 'AM_Mapper_' . $sProvider . "_" . $sModelTableName; $sFile = str_replace('_', DIRECTORY_SEPARATOR, $sMapperClassName) . '.php'; if (!AM_Tools_Standard::isReadable($sFile)) { throw new AM_Mapper_Exception(sprintf('Mapper class "%s" not found', $sMapperClassName), 503); } $oMapper = new $sMapperClassName($oModel, $aOptions); return $oMapper; }
/** * Removes resources * @param string $sResourceType * @param int $iId * @param string $sFileName */ public function clearResources($sFileName = null) { $sPath = $this->_getSavePath() . DIRECTORY_SEPARATOR . $this->getPathPrefix(); if (!empty($sFileName)) { $aFiles = glob($sPath . DIRECTORY_SEPARATOR . $sFileName); if ($aFiles) { foreach ($aFiles as $sFile) { AM_Tools_Standard::getInstance()->unlink($sFile); } } return; } AM_Tools_Standard::getInstance()->clearDir($sPath); }
/** * Defined by Zend_Application_Resource_Resource * * @return AM_Handler_Thumbnail_Storage_Abstract */ public function init() { $this->getBootstrap()->bootstrap('handlermanager'); $aOptions = $this->getOptions(); $sAdapter = $aOptions['adapter']; $sAdapterClassName = self::CLASS_PREFIX . '_' . ucfirst($sAdapter); $sFile = str_replace('_', DIRECTORY_SEPARATOR, $sAdapterClassName) . '.php'; if (!AM_Tools_Standard::getInstance()->isReadable($sFile)) { throw new AM_Exception(sprintf('Adapter class \'%s\' not found', $sAdapterClassName), 502); } $oThumbnailHandler = AM_Handler_Locator::getInstance()->getHandler('thumbnail'); $oStorage = new $sAdapterClassName($oThumbnailHandler, new Zend_Config($aOptions['options'])); if (!$oStorage instanceof AM_Handler_Thumbnail_Storage_Abstract) { throw new AM_Exception(sprintf('Wrong resource storage given', 501)); } return $oStorage; }
/** * Creates resource instance by file extension * @param string $sResourceFilePath path to the resource's file * @return AM_Resource_Abstract * @throws AM_Resource_Exception */ public static function create($sResourceFilePath) { if (!AM_Tools_Standard::getInstance()->is_file($sResourceFilePath)) { throw new AM_Resource_Factory_Exception(sprintf('File \'%s\' not exists', $sResourceFilePath), 501); } $sFileExtension = pathinfo($sResourceFilePath, PATHINFO_EXTENSION); $oFilter = new Zend_Filter(); $oFilter->addFilter(new Zend_Filter_StringToLower(array('encoding' => 'UTF-8'))); $sClassPostfix = ucfirst($oFilter->filter($sFileExtension)); $sResourceClassName = AM_Resource_Abstract::RESOURCE_CONCRETE_CLASS_PREFIX . $sClassPostfix; $sFile = str_replace('_', DIRECTORY_SEPARATOR, $sResourceClassName) . '.php'; if (!AM_Tools_Standard::getInstance()->isReadable($sFile)) { throw new AM_Resource_Factory_Exception(sprintf('Class \'%s\' not found', $sResourceClassName), 502); } /* @var $oResource AM_Resource_Abstract */ $oResource = new $sResourceClassName($sResourceFilePath); return $oResource; }
/** * Upload resource file * @return AM_Model_Db_StaticPdf_Data_Resource * @throws AM_Model_Db_StaticPdf_Data_Exception */ public function upload() { if (!AM_Tools_Standard::getInstance()->is_dir($this->_sResourceDir)) { if (!AM_Tools_Standard::getInstance()->mkdir($this->_sResourceDir, 0777, true)) { throw new AM_Model_Db_StaticPdf_Data_Exception(sprintf('I/O error while create dir "%s"', $this->_sResourceDir)); } } $oUploadHandler = $this->getUploader(); if (!$oUploadHandler->isUploaded(self::INPUT_FILE_NAME)) { throw new AM_Model_Db_StaticPdf_Data_Exception('File with variable name "pdf-file" not found'); } //Validate uploaded file $oUploadHandler->addValidator('Size', true, array('min' => 20, 'max' => 209715200))->addValidator('Count', true, 1)->addValidator('Extension', true, self::$_aAllowedExtensions); if (!$oUploadHandler->isValid()) { throw new AM_Model_Db_StaticPdf_Data_Exception($oUploadHandler->getMessagesAsString()); } $aFiles = $oUploadHandler->getFileInfo(); $sFileExtension = strtolower(pathinfo($aFiles[self::INPUT_FILE_NAME]['name'], PATHINFO_EXTENSION)); $sDestination = $this->_sResourceDir . DIRECTORY_SEPARATOR . $this->_sResourceName . '.' . $sFileExtension; //Rename file and receive it $oUploadHandler->addFilter('Rename', array('target' => $sDestination, 'overwrite' => true)); if (!$oUploadHandler->receive(self::INPUT_FILE_NAME)) { throw new AM_Model_Db_StaticPdf_Data_Exception($oUploadHandler->getMessagesAsString()); } $this->_sResourceDbBaseName = $aFiles[self::INPUT_FILE_NAME]['name']; $this->_postUpload($sDestination); return $this; }
/** * Check the pid file: * if file exists, get the pid from file and find the process with this pid * @return boolean * @throws AM_Task_Manager_Exception */ protected function _isDemonized() { $sPidFilePath = $this->_getPidFilePath(); if (AM_Tools_Standard::getInstance()->is_file($sPidFilePath)) { $iPid = intval(file_get_contents($sPidFilePath)); //checking for the presence of the process if (posix_kill($iPid, 0)) { //the daemon already run return true; } else { //pid file exists, but there isn't process $this->_removePidFile(); } } return false; }
/** * Run export task * @param AM_Model_Db_Revision $oRevision * @return AM_Handler_Export * @throws AM_Handler_Export_Exception */ public function initExportProcess(AM_Model_Db_Revision $oRevision) { $sCommand = sprintf('nohup %s/padcms export --revision=%d > /dev/null 2>&1 &', APPLICATION_PATH . DIRECTORY_SEPARATOR . '..', $oRevision->id); AM_Tools_Standard::getInstance()->exec($sCommand); return $this; }
/** * Add resource to the stack * @param string $sResourcePath * @return AM_Handler_Thumbnail_Storage_Abstract * @throws AM_Handler_Thumbnail_Storage_Exception */ public function addResource($sResourcePath) { if (!AM_Tools_Standard::getInstance()->is_file($sResourcePath)) { throw new AM_Handler_Thumbnail_Storage_Exception(sprintf('Can\'t read resource \\"%s\\"', $sResourcePath)); } $this->_aResources[] = $sResourcePath; return $this; }
/** * Get information from pdf * @return string Information about PDF in JSON {'widht', 'height', 'zones' => [{'uri','top','left','width','height'}] * @throws AM_Resource_Exception */ public function getPdfInfo() { $sPdfDrawBin = $this->_getPadcmsdrawPath(); $sCmd = sprintf('nice -n 15 %s -j %s 2>/dev/null', $sPdfDrawBin, $this->_sSourceFile); AM_Tools_Standard::getInstance()->exec($sCmd, $aCommandOutput); if (!$aCommandOutput || count($aCommandOutput) == 0) { throw new AM_Resource_Exception('Unable to get info from file ' . $this->_sSourceFile); } $aPageInfo = json_encode(Zend_Json_Decoder::decode(implode('', $aCommandOutput))); return $aPageInfo; }
/** * Connects to Apple Push Notification service server. * * @throws ApnsPHP_Exception if is unable to connect. * @return @type boolean True if successful connected. */ protected function _connect() { $sURL = $this->_aServiceURLs[$this->_nEnvironment]; unset($aURLs); $this->getLogger()->info("Trying {$sURL}..."); /** * @see http://php.net/manual/en/context.ssl.php */ $streamContext = AM_Tools_Standard::getInstance()->stream_context_create(array('ssl' => array('local_cert' => $this->_sProviderCertificateFile))); $this->_hSocket = AM_Tools_Standard::getInstance()->stream_socket_client($sURL, $nError, $sError, $this->_nConnectTimeout, STREAM_CLIENT_CONNECT, $streamContext); if (!$this->_hSocket) { throw new ApnsPHP_Exception("Unable to connect to '{$sURL}': {$sError} ({$nError})"); } AM_Tools_Standard::getInstance()->stream_set_blocking($this->_hSocket, 0); AM_Tools_Standard::getInstance()->stream_set_write_buffer($this->_hSocket, 0); $this->getLogger()->info("Connected to {$sURL}."); return true; }
/** * Establish connection and create DB * * @return Zend_Db_Adapter_Pdo_Sqlite * @throws AM_Handler_Export_Sqlite_Exception */ public function getAdapter() { if (is_null($this->_oAdapter)) { $this->_oAdapter = Zend_Db::factory('PDO_SQLITE', array('dbname' => $this->_getDbFile())); $sSchema = @file_get_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Sqlite' . DIRECTORY_SEPARATOR . 'schema.sqlite.sql'); if (empty($sSchema)) { throw new AM_Handler_Export_Sqlite_Exception('Schema file is empty'); } $this->_oAdapter->getConnection()->exec($sSchema); AM_Tools_Standard::getInstance()->chmod($this->_getDbFile(), 0666); } return $this->_oAdapter; }
/** * Optimize png image with optipng tool * @param string $sFilePath */ public static function optimizePng($sFilePath) { $sOptipngPath = Zend_Registry::get('config')->bin->optipng; $sCmd = sprintf('nice -n 15 %s -zc9 -zm8 -zs0 -f5 %s > /dev/null 2>&1', $sOptipngPath, $sFilePath); AM_Tools_Standard::getInstance()->passthru($sCmd); }
/** * Returns archive path * @return null|string */ public function getArchive() { $sZipFileName = sprintf('static-pdf-%s-%s.zip', $this->getIssue()->id, strtotime($this->getIssue()->updated)); $sZipFileDir = $this->getConfig()->temp->base . DIRECTORY_SEPARATOR . 'static-pdf'; $sZipFile = $sZipFileDir . DIRECTORY_SEPARATOR . $sZipFileName; if (!AM_Tools_Standard::getInstance()->is_file($sZipFile)) { $sTmpZipFile = AM_Handler_Temp::getInstance()->getFile($sZipFileName); $oZip = new ZipArchive(); $oZip->open($sTmpZipFile, ZIPARCHIVE::CREATE); $aFiles = $this->getFiles(); if (empty($aFiles)) { return null; } foreach ($aFiles as $sFile) { $oZip->addFile($sFile, pathinfo($sFile, PATHINFO_BASENAME)); } $oZip->close(); if (!AM_Tools_Standard::getInstance()->is_dir($sZipFileDir)) { AM_Tools_Standard::getInstance()->mkdir($sZipFileDir, 0777); } AM_Tools_Standard::getInstance()->copy($sTmpZipFile, $sZipFile); } return $sZipFile; }
/** * Upload resource * @param string $sResourceKey resource name * @return AM_Model_Db_Term_Data_Resource * @throws AM_Model_Db_Term_Data_Exception */ public function upload($sResourceKey) { $oUploadHandler = $this->getUploader(); if (!$oUploadHandler->isUploaded($sResourceKey)) { throw new AM_Model_Db_Term_Data_Exception(sprintf('File with variable name "%s" not found', $sResourceKey)); } //Validate uploaded file $oUploadHandler->addValidator('Size', true, array('min' => 20, 'max' => 209715200))->addValidator('Count', true, 1)->addValidator('Extension', true, self::getAllowedFileExtensions($sResourceKey)); if (!$oUploadHandler->isValid()) { throw new AM_Model_Db_Term_Data_Exception($oUploadHandler->getMessagesAsString()); } $sDataPath = $this->_getResourceDir(); if (!AM_Tools_Standard::getInstance()->is_dir($sDataPath)) { if (!AM_Tools_Standard::getInstance()->mkdir($sDataPath, 0777, true)) { throw new AM_Model_Db_Term_Data_Exception(sprintf('I/O error while create dir "%s"', $sDataPath)); } } $aFiles = $oUploadHandler->getFileInfo(); $sGivenFile = $aFiles[$sResourceKey]['name']; $aFileInfo = pathinfo($sGivenFile); $sFileName = $aFileInfo["filename"]; $sFileExtension = $aFileInfo["extension"]; $sFileNameNew = $sResourceKey . "." . $sFileExtension; //Copy resource $sDestination = $sDataPath . DIRECTORY_SEPARATOR . $sFileNameNew; //Rename file and receive it $oUploadHandler->addFilter('Rename', array('target' => $sDestination, 'overwrite' => true)); $this->clearResources($sResourceKey); if (!$oUploadHandler->receive($sResourceKey)) { throw new AM_Model_Db_Term_Data_Exception($oUploadHandler->getMessagesAsString()); } $sField = 'thumb_' . $sResourceKey; $this->getTerm()->{$sField} = $sFileName . '.' . $sFileExtension; $this->getTerm()->updated = new Zend_Db_Expr('NOW()'); $this->getTerm()->save(); $this->_postUpload($sDestination); return $this; }
/** * Removes content files * * @todo Refactor and move to the separate helper * @param string $sType The type of resource (element, toc, static-pdf, etc.) * @param int $iId * @param string $sFileName * @return void */ public static function clearContent($sType = null, $iId = null, $sFileName = null) { $sBasePath = Zend_Registry::get('config')->content->base; $sSplittedIdPath = is_null($iId) ? null : trim(AM_Tools_String::generatePathFromId($iId), DIRECTORY_SEPARATOR); if (!empty($sType)) { $sBasePath .= DIRECTORY_SEPARATOR . $sType; } if (!is_null($sSplittedIdPath)) { $sBasePath .= DIRECTORY_SEPARATOR . $sSplittedIdPath; } if (!empty($sFileName)) { $aFiles = glob($sBasePath . '/' . $sFileName); if ($aFiles) { foreach ($aFiles as $sFile) { AM_Tools_Standard::getInstance()->unlink($sFile); } } return; } if (!AM_Tools_Standard::getInstance()->is_dir($sBasePath)) { return; } AM_Tools_Standard::getInstance()->clearDir($sBasePath); }
/** * Reads an error message (if present) from the main stream. * If the error message is present and valid the error message is returned, * otherwhise null is returned. * * @return @type array|null Return the error message array. */ protected function _readErrorMessage() { $sErrorResponse = AM_Tools_Standard::getInstance()->fread($this->_hSocket, self::ERROR_RESPONSE_SIZE); if ($sErrorResponse === false || strlen($sErrorResponse) != self::ERROR_RESPONSE_SIZE) { return; } $aErrorResponse = $this->_parseErrorMessage($sErrorResponse); if (!is_array($aErrorResponse) || empty($aErrorResponse)) { return; } if (!isset($aErrorResponse['command'], $aErrorResponse['statusCode'], $aErrorResponse['identifier'])) { return; } if ($aErrorResponse['command'] != self::ERROR_RESPONSE_COMMAND) { return; } $aErrorResponse['time'] = time(); $aErrorResponse['statusMessage'] = $this->_getErrorMessageByCode($aErrorResponse['statusCode']); return $aErrorResponse; }
/** * Remove all files and dirs created during session * @return AM_Handler_Temp */ public function end() { if (empty($this->_sDirectory)) { return $this; } AM_Tools_Standard::getInstance()->clearDir($this->_sDirectory); AM_Tools_Standard::getInstance()->rmdir($this->_sDirectory); $this->_sDirectory = null; return $this; }
/** * Add file resource to the package * * @see AM_Handler_Export_Package_Interface::addFile() * @param string $sPathReal * @param string $sPathInPackage * @return AM_Handler_Export_Package_Abstract * @throws AM_Handler_Export_Package_Exception */ public function addFile($sPathReal, $sPathInPackage) { if (!AM_Tools_Standard::getInstance()->file_exists($sPathReal)) { throw new AM_Handler_Export_Package_Exception(sprintf('File "%s" doesn\'t exist', $sPathReal)); } if (empty($sPathInPackage)) { throw new AM_Handler_Export_Package_Exception('File path in package have to be not empty'); } $this->_aFiles[$sPathReal] = $sPathInPackage; return $this; }
/** * Upload resource * @param string $sResourceKey resource name * @return AM_Model_Db_Element_Data_Resource * @throws AM_Model_Db_Element_Data_Exception */ public function upload($sResourceKey = self::DATA_KEY_RESOURCE) { $oUploader = $this->getUploader(); if (!$oUploader->isUploaded($sResourceKey)) { throw new AM_Model_Db_Element_Data_Exception(sprintf('File with variable name "%s" not found', $sResourceKey)); } //Validate uploaded file $oUploader->addValidator('Size', true, array('min' => 20, 'max' => 209715200))->addValidator('Count', true, 1)->addValidator('Extension', true, self::getAllowedFileExtensions($sResourceKey)); if (!$oUploader->isValid()) { throw new AM_Model_Db_Element_Data_Exception($oUploader->getMessagesAsString()); } $sDataPath = $this->_getResourceDir(); if (!AM_Tools_Standard::getInstance()->is_dir($sDataPath)) { if (!AM_Tools_Standard::getInstance()->mkdir($sDataPath, 0777, true)) { throw new AM_Model_Db_Element_Data_Exception(sprintf('I/O error while create dir "%s"', $sDataPath)); } } $aFiles = $oUploader->getFileInfo(); $sGivenFileName = $aFiles[$sResourceKey]['name']; $aFileInfo = pathinfo($sGivenFileName); $sFileExtension = $aFileInfo['extension']; $sFileNameNew = $sResourceKey . "." . $sFileExtension; //Copy resource $sDestination = $sDataPath . DIRECTORY_SEPARATOR . $sFileNameNew; //Rename file and receive it $oUploader->addFilter('Rename', array('target' => $sDestination, 'overwrite' => true)); $this->clearResources($sResourceKey); if (!$oUploader->receive($sResourceKey)) { throw new AM_Model_Db_Element_Data_Exception($oUploader->getMessagesAsString()); } $this->addKeyValue($sResourceKey, $sGivenFileName); $this->addKeyValue(self::DATA_KEY_IMAGE_TYPE, $this->getImageType()); $this->_postUpload($sDestination, $sResourceKey); return $this; }
/** * Set temp path for uploaded files * @param string $sTempPath * @return AM_Model_Db_Element_Data_Abstract */ public function setTempPath($sTempPath) { if (!AM_Tools_Standard::getInstance()->is_dir($sTempPath)) { throw new AM_Model_Db_Element_Data_Exception("Wrong temp path given"); } $this->_sTempPath = $sTempPath; return $this; }
/** * Remove all xml suite files */ protected function _removeAllXmlSuites() { AM_Tools_Standard::getInstance()->clearDir($this->_sPathToXml); }