public function run(Task $task) { \common_Logger::d('Running task ' . $task->getId()); $report = new \common_report_Report(\common_report_Report::TYPE_INFO, __('Running task %s', $task->getId())); $queue = $this->getServiceLocator()->get(Queue::CONFIG_ID); $queue->updateTaskStatus($task->getId(), Task::STATUS_RUNNING); try { $actionService = $this->getServiceLocator()->get(ActionService::SERVICE_ID); $invocable = $task->getInvocable(); if (is_string($invocable)) { $invocable = $actionService->resolve($task->getInvocable()); } else { if ($invocable instanceof ServiceLocatorAwareInterface) { $invocable->setServiceLocator($this->getServiceLocator()); } } $subReport = call_user_func($invocable, $task->getParameters()); $report->add($subReport); } catch (\Exception $e) { $message = 'Task ' . $task->getId() . ' failed. Error message: ' . $e->getMessage(); \common_Logger::e($message); $report = new \common_report_Report(\common_report_Report::TYPE_ERROR, $message); } $queue->updateTaskStatus($task->getId(), Task::STATUS_FINISHED, $report); return $report; }
public function testFileAppender() { $tfile = $this->createFile(); $dfile = $this->createFile(); $efile = $this->createFile(); common_log_Dispatcher::singleton()->init(array(array('class' => 'SingleFileAppender', 'threshold' => common_Logger::TRACE_LEVEL, 'file' => $tfile), array('class' => 'SingleFileAppender', 'mask' => 2, 'file' => $dfile), array('class' => 'SingleFileAppender', 'threshold' => common_Logger::ERROR_LEVEL, 'file' => $efile))); common_Logger::singleton()->enable(); common_Logger::t('message'); $this->assertEntriesInFile($tfile, 1); $this->assertEntriesInFile($dfile, 0); $this->assertEntriesInFile($efile, 0); common_Logger::d('message'); $this->assertEntriesInFile($tfile, 2); $this->assertEntriesInFile($dfile, 1); $this->assertEntriesInFile($efile, 0); common_Logger::e('message'); $this->assertEntriesInFile($tfile, 3); $this->assertEntriesInFile($dfile, 1); $this->assertEntriesInFile($efile, 1); common_Logger::singleton()->disable(); common_Logger::d('message'); $this->assertEntriesInFile($tfile, 3); $this->assertEntriesInFile($dfile, 1); $this->assertEntriesInFile($efile, 1); common_Logger::singleton()->restore(); common_Logger::d('message'); $this->assertEntriesInFile($tfile, 4); $this->assertEntriesInFile($dfile, 2); $this->assertEntriesInFile($efile, 1); common_Logger::singleton()->restore(); }
public static function outputFile($relPath, $filename = null) { $fullpath = self::getExportPath() . DIRECTORY_SEPARATOR . $relPath; if (tao_helpers_File::securityCheck($fullpath, true) && file_exists($fullpath)) { Context::getInstance()->getResponse()->setContentHeader(tao_helpers_File::getMimeType($fullpath)); $fileName = empty($filename) ? basename($fullpath) : $filename; header('Content-Disposition: attachment; fileName="' . $fileName . '"'); header("Content-Length: " . filesize($fullpath)); //Clean all levels of output buffering while (ob_get_level() > 0) { ob_end_clean(); } flush(); $fp = fopen($fullpath, "r"); if ($fp !== false) { while (!feof($fp)) { echo fread($fp, 65536); flush(); } fclose($fp); @unlink($fullpath); } else { common_Logger::e('Unable to open File to export' . $fullpath); } } else { common_Logger::e('Could not find File to export: ' . $fullpath); } }
public function scriptRunner($script, $extension) { $error = false; $errorStack = array(); if (isset($extension) && $extension != null) { $ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extension); } if ($script != null) { $parameters = array(); $options = array('argv' => array(0 => 'Script ' . $script), 'output_mode' => 'log_only'); try { $scriptName = $script; if (!class_exists($scriptName)) { throw new taoUpdate_models_classes_UpdateException('Could not find scriptName class ' . $script); } new $scriptName(array('parameters' => $parameters), $options); $error = false; } catch (Exception $e) { common_Logger::e('Error occurs during update ' . $e->getMessage()); $error = true; $errorStack[] = 'Error in script ' . $script . ' ' . $e->getMessage(); } if ($error) { echo json_encode(array('success' => 0, 'failed' => $errorStack)); } else { echo json_encode(array('success' => 1, 'failed' => array())); } } else { echo json_encode(array('success' => 0, 'failed' => array('not scriptname provided'))); } }
/** * Compile an item. * * @param core_kernel_file_File $destinationDirectory * @throws taoItems_models_classes_CompilationFailedException * @return tao_models_classes_service_ServiceCall */ public function compile() { $destinationDirectory = $this->spawnPublicDirectory(); $item = $this->getResource(); $itemUri = $item->getUri(); $report = new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Published %s', $item->getLabel())); if (!taoItems_models_classes_ItemsService::singleton()->isItemModelDefined($item)) { return $this->fail(__('Item \'%s\' has no model', $item->getLabel())); } $langs = $this->getContentUsedLanguages(); foreach ($langs as $compilationLanguage) { $compiledFolder = $this->getLanguageCompilationPath($destinationDirectory, $compilationLanguage); if (!is_dir($compiledFolder)) { if (!@mkdir($compiledFolder)) { common_Logger::e('Could not create directory ' . $compiledFolder, 'COMPILER'); return $this->fail(__('Could not create language specific directory for item \'%s\'', $item->getLabel())); } } $langReport = $this->deployItem($item, $compilationLanguage, $compiledFolder); $report->add($langReport); if ($langReport->getType() == common_report_Report::TYPE_ERROR) { $report->setType(common_report_Report::TYPE_ERROR); break; } } if ($report->getType() == common_report_Report::TYPE_SUCCESS) { $report->setData($this->createService($item, $destinationDirectory)); } else { $report->setMessage(__('Failed to publish %s', $item->getLabel())); } return $report; }
public function getPublicAccessUrl() { if (is_null($this->accessProvider)) { common_Logger::e('accessss'); throw new common_Exception('Tried obtaining access to private directory with ID ' . $this->id); } return $this->accessProvider->getAccessUrl($this->relPath); }
/** * Returns a URL that allows you to access the files in a directory * preserving the relative paths * * @return string * @throws common_Exception */ public function getPublicAccessUrl() { if (is_null($this->accessProvider)) { common_Logger::e('accessss'); throw new common_Exception('Tried obtaining access to private directory with ID ' . $this->getId()); } return $this->accessProvider->getAccessUrl($this->prefix . DIRECTORY_SEPARATOR); }
public function backup() { if (count($this->error) > 0) { common_Logger::e('Fail to dump database'); return false; } return $this->dump; }
/** * authenticate a user * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param string login * @param string password * @return boolean * @deprecated */ public function loginUser($login, $password) { $returnValue = (bool) false; try { $returnValue = LoginService::login($login, $password); } catch (core_kernel_users_Exception $ue) { common_Logger::e("A fatal error occured at user login time: " . $ue->getMessage()); } return (bool) $returnValue; }
/** * Converts a duration to a time * @param string $duration the ISO duration * @return string time hh:mm:ss.micros */ public static function durationToTime($duration) { $time = null; try { $interval = preg_match('/(\\.[0-9]{1,6}S)$/', $duration) ? new DateIntervalMS($duration) : new DateInterval($duration); $time = self::intervalToTime($interval); } catch (Exception $e) { common_Logger::e($e->getMessage()); } return $time; }
/** * Converts a duration to a time * @param string $duration the ISO duration * @return string time hh:mm:ss */ public static function durationToTime($duration) { $time = null; try { $interval = new DateInterval($duration); $time = self::intervalToTime($interval); } catch (Exception $e) { common_Logger::e($e->getMessage()); } return $time; }
/** * @author "Lionel Lecaque, <*****@*****.**>" * @param array $params * @throws tao_install_utils_Exception */ public function __construct($params) { try { $this->connection = $this->buildDbalConnection($params); $this->dbConfiguration = $params; $this->buildSchema(); } catch (Exception $e) { $this->connection = null; common_Logger::e($e->getMessage() . $e->getTraceAsString(), 'INSTALL'); throw new tao_install_utils_Exception('Unable to connect to the database ' . $params['dbname'] . ' with the provided credentials: ' . $e->getMessage()); } }
/** * * @access public * @author "Lionel Lecaque, <*****@*****.**>" */ public static function isDesignModeEnabled() { $returnValue = true; $optimizableClasses = tao_helpers_Optimization::getOptimizableClasses(); foreach ($optimizableClasses as $class) { if (isset($class['status'])) { $returnValue &= $class['status'] == tao_helpers_Optimization::DECOMPILED; } else { common_Logger::e('Problem occcurs when checking if design mode enable'); return false; } } return $returnValue; }
/** * @param Event $event */ public static function logEvent(Event $event) { $action = 'cli' === php_sapi_name() ? $_SERVER['PHP_SELF'] : Context::getInstance()->getRequest()->getRequestURI(); /** @var common_session_Session $session */ $session = common_session_SessionManager::getSession(); /** @var common_user_User $currentUser */ $currentUser = $session->getUser(); $data = is_subclass_of($event, JsonSerializable::class) ? $event : []; try { static::getStorage()->log($event->getName(), $action, $currentUser->getIdentifier(), join(',', $currentUser->getPropertyValues(PROPERTY_USER_ROLES)), (new DateTime('now', new \DateTimeZone('UTC')))->format(DateTime::ISO8601), json_encode($data)); } catch (\Exception $e) { \common_Logger::e('Error logging to DB ' . $e->getMessage()); } }
/** * * @access public * @author "Lionel Lecaque, <*****@*****.**>" */ public static function isDesignModeEnabled() { $returnValue = true; $extensions = common_ext_ExtensionsManager::singleton()->getInstalledExtensions(); if (!isset($extensions['generisHard'])) { return false; } $optimizableClasses = Optimization::getOptimizableClasses(); foreach ($optimizableClasses as $class) { if (isset($class['status'])) { $returnValue &= $class['status'] == Optimization::DECOMPILED; } else { common_Logger::e('Problem occcurs when checking if design mode enable'); return false; } } return $returnValue; }
/** * * @access * @author "Lionel Lecaque, <*****@*****.**>" * @return boolean */ public function shieldExtensions() { $extmanger = common_ext_ExtensionsManager::singleton(); $extlists = $extmanger->getInstalledExtensions(); $returnvalue = true; try { foreach (array_keys($extlists) as $ext) { $returnvalue &= $this->shield($ext, taoUpdate_models_classes_Service::DEPLOY_FOLDER); } } catch (taoUpdate_models_classes_UpdateException $e) { common_Logger::e('Error during shield, revert all extensions'); foreach (array_keys($extlists) as $ext) { $this->unShield($ext); } throw $e; } return $returnvalue; }
/** * Main action to launch export * * @param string $uri * @return File */ public function export($uri) { $this->assessmentUri = $uri; $items = \taoQtiTest_models_classes_QtiTestService::singleton()->getItems($this->getResource($uri)); $data = []; /** @var \core_kernel_classes_Resource $item */ foreach ($items as $item) { try { $itemData = $this->getItemExporter()->getDataByItem($item); foreach ($itemData as &$column) { $column = array_merge($column, $this->getAdditionalData($item)); } $data[] = $itemData; } catch (ExtractorException $e) { \common_Logger::e('ERROR on item ' . $item->getUri() . ' : ' . $e->getMessage()); } } $headers = array_merge($this->getItemExporter()->getHeaders(), $this->getHeaders()); return $this->getItemExporter()->save($headers, $data, true); }
/** * Short description of method createInstance * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param Class clazz * @param string label * @param string comment * @param string uri * @return core_kernel_classes_Resource */ public static function createInstance(core_kernel_classes_Class $clazz, $label = '', $comment = '', $uri = '') { $returnValue = null; $newUri = !empty($uri) ? self::checkProvidedUri($uri) : common_Utils::getNewUri(); $newResource = new core_kernel_classes_Class($newUri); $propertiesValues = array(RDF_TYPE => $clazz->getUri()); if (!empty($label)) { $propertiesValues[RDFS_LABEL] = $label; } if (!empty($comment)) { $propertiesValues[RDFS_COMMENT] = $comment; } $check = $newResource->setPropertiesValues($propertiesValues); if ($check) { $returnValue = $newResource; } else { $msg = "Failed to create an instance of class '" . $clazz->getUri() . "'."; throw new common_Exception($msg); common_Logger::e($msg); } return $returnValue; }
public static function createAdapters() { $adapters = array(); $config = common_ext_ExtensionsManager::singleton()->getExtensionById('generis')->getConfig('auth'); if (is_array($config)) { foreach ($config as $key => $adapterConf) { if (isset($adapterConf['driver'])) { $className = $adapterConf['driver']; unset($adapterConf['driver']); if (class_exists($className) && in_array(__NAMESPACE__ . '\\LoginAdapter', class_implements($className))) { $adapter = new $className(); $adapter->setOptions($adapterConf); $adapters[] = $adapter; } else { \common_Logger::e($className . ' is not a valid LoginAdapter'); } } else { \common_Logger::e('No driver for auth adapter ' . $key); } } } return $adapters; }
/** * * @param unknown $xhtml * @param unknown $destination * @return common_report_Report */ public static function retrieveExternalResources($xhtml, $destination) { if (!file_exists($destination)) { if (!mkdir($destination)) { common_Logger::e('Folder ' . $destination . ' could not be created'); return new common_report_Report(common_report_Report::TYPE_ERROR, __('Unable to create deployement directory'), $xhtml); } } $authorizedMedia = self::$defaultMedia; $mediaList = array(); $expr = "/http[s]?:(\\\\)?\\/(\\\\)?\\/[^<'\"&?]+\\.(" . implode('|', $authorizedMedia) . ")/mi"; //take into account json encoded url preg_match_all($expr, $xhtml, $mediaList, PREG_PATTERN_ORDER); $uniqueMediaList = array_unique($mediaList[0]); $report = new common_report_Report(common_report_Report::TYPE_SUCCESS, __('Retrieving external resources')); foreach ($uniqueMediaList as $mediaUrl) { // This is a file that has to be stored in the item compilation folder itself... // I do not get why they are all copied. They are all there they were copied from the item module... // But I agree that remote resources (somewhere on the Internet) should be copied via curl. // So if the URL does not matches a place where the TAO server is, we curl the resource and store it. // FileManager files should be considered as remote resources to avoid 404 issues. Indeed, a backoffice // user might delete an image in the filemanager during a delivery campain. This is dangerous. $decodedMediaUrl = str_replace('\\/', '/', $mediaUrl); $mediaPath = self::retrieveFile($decodedMediaUrl, $destination); if (!empty($mediaPath) && $mediaPath !== false) { $xhtml = str_replace($mediaUrl, basename($mediaPath), $xhtml, $replaced); //replace only when copyFile is successful } else { $report->add(new common_report_Report(common_report_Report::TYPE_ERROR, __('Failed retrieving %s', $decodedMediaUrl))); $report->setType(common_report_Report::TYPE_ERROR); } } if ($report->getType() == common_report_Report::TYPE_SUCCESS) { $report->setData($xhtml); } return $report; }
/** * Compile the RubricBlocRefs' contents into a separate rubric block PHP template. * * @param AssessmentTest $assessmentTest The AssessmentTest object you want to compile the rubrickBlocks. */ protected function compileRubricBlocks(AssessmentTest $assessmentTest) { $rubricBlockRefs = $assessmentTest->getComponentsByClassName('rubricBlockRef'); $testService = taoQtiTest_models_classes_QtiTestService::singleton(); $sourceDir = $testService->getQtiTestDir($this->getResource()); foreach ($rubricBlockRefs as $rubricRef) { $rubricRefHref = $rubricRef->getHref(); $cssScoper = $this->getCssScoper(); $renderingEngine = $this->getRenderingEngine(); $markupPostRenderer = $this->getMarkupPostRenderer(); $publicCompiledDocDir = $this->getPublicDirectory(); $privateCompiledDocDir = $this->getPrivateDirectory(); // -- loading... common_Logger::t("Loading rubricBlock '" . $rubricRefHref . "'..."); $rubricDoc = new XmlDocument(); $rubricDoc->loadFromString($this->getPrivateDirectory()->read($rubricRefHref)); common_Logger::t("rubricBlock '" . $rubricRefHref . "' successfully loaded."); // -- rendering... common_Logger::t("Rendering rubricBlock '" . $rubricRefHref . "'..."); $pathinfo = pathinfo($rubricRefHref); $renderingFile = $pathinfo['filename'] . '.php'; $rubric = $rubricDoc->getDocumentComponent(); $rubricStylesheets = $rubric->getStylesheets(); $stylesheets = new StylesheetCollection(); // In any case, include the base QTI Stylesheet. $stylesheets->merge($rubricStylesheets); $rubric->setStylesheets($stylesheets); // -- If the rubricBlock has no id, give it a auto-generated one in order // to be sure that CSS rescoping procedure works fine (it needs at least an id // to target its scoping). if ($rubric->hasId() === false) { // Prepend 'tao' to the generated id because the CSS // ident token must begin by -|[a-zA-Z] $rubric->setId('tao' . uniqid()); } // -- Copy eventual remote resources of the rubricBlock. $this->copyRemoteResources($rubric); $domRendering = $renderingEngine->render($rubric); $mainStringRendering = $markupPostRenderer->render($domRendering); // Prepend stylesheets rendering to the main rendering. $styleRendering = $renderingEngine->getStylesheets(); $mainStringRendering = $styleRendering->ownerDocument->saveXML($styleRendering) . $mainStringRendering; foreach ($stylesheets as $rubricStylesheet) { $relPath = trim($this->getExtraPath(), '/'); $relPath = (empty($relPath) ? '' : $relPath . DIRECTORY_SEPARATOR) . $rubricStylesheet->getHref(); $sourceFile = $sourceDir->getFile($relPath); if (!$publicCompiledDocDir->has($relPath)) { try { $data = $sourceFile->read(); $tmpDir = \tao_helpers_File::createTempDir(); $tmpFile = $tmpDir . 'tmp.css'; file_put_contents($tmpFile, $data); $scopedCss = $cssScoper->render($tmpFile, $rubric->getId()); unlink($tmpFile); rmdir($tmpDir); $publicCompiledDocDir->write($relPath, $scopedCss); } catch (\InvalidArgumentException $e) { common_Logger::e('Unable to copy file into public directory: ' . $relPath); } } } // -- Replace the artificial 'tao://qti-directory' base path with a runtime call to the delivery time base path. $mainStringRendering = str_replace(TAOQTITEST_PLACEHOLDER_BASE_URI, '<?php echo $' . TAOQTITEST_BASE_PATH_NAME . '; ?>', $mainStringRendering); if (!$privateCompiledDocDir->has($renderingFile)) { try { $privateCompiledDocDir->write($renderingFile, $mainStringRendering); common_Logger::t("rubricBlockRef '" . $rubricRefHref . "' successfully rendered."); } catch (\InvalidArgumentException $e) { common_Logger::e('Unable to copy file into public directory: ' . $renderingFile); } } // -- Clean up old rubric block and reference the new rubric block template. $privateCompiledDocDir->delete($rubricRefHref); $rubricRef->setHref('./' . $pathinfo['filename'] . '.php'); } }
<?php /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2013-2014 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * */ $testClass = taoQtiTest_models_classes_QtiTestService::singleton()->getRootClass(); $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'qtiv2p1Examples.zip'; try { $report = taoQtiTest_models_classes_QtiTestService::singleton()->importMultipleTests(new core_kernel_classes_Class(TAO_TEST_CLASS), $file); } catch (Exception $e) { common_Logger::e('An error occured while importing QTI Test Example. The system reported the following error: ' . $e->getMessage()); throw $e; }
/** * Return all directory parsers from configuration * * @return PortableElementDirectoryParser[] */ protected function getDirectoryParsers() { $parsers = array(); $models = $this->getPortableFactory()->getModels(); foreach ($models as $key => $model) { if ($model->getDirectoryParser() instanceof PortableElementDirectoryParser) { $parsers[] = $model->getDirectoryParser(); } else { \common_Logger::e('Invalid DirectoryParser for model ' . $key); } } return $parsers; }
/** * Populate the document using the JSON parameter. * * @param string $json a valid json object (one that comes from the toJson method). * * @throws taoQtiTest_models_classes_QtiTestConverterException */ public function fromJson($json) { try { $data = json_decode($json, true); if (is_array($data)) { $this->arrayToComponent($data); } } catch (ReflectionException $re) { common_Logger::e($re->getMessage()); common_Logger::d($re->getTraceAsString()); throw new taoQtiTest_models_classes_QtiTestConverterException('Unable to create the QTI Test from json: ' . $re->getMessage()); } }
/** * Sent email message * * @access public * @author Bertrand Chevrier, <*****@*****.**> * @param Message $message * @return boolean whether message was sent */ public function send(Message $message) { $mailer = $this->getMailer(); $mailer->SetFrom($this->getFrom($message)); $mailer->AddReplyTo($this->getFrom($message)); $mailer->Subject = $message->getTitle(); $mailer->AltBody = strip_tags(preg_replace("/<br.*>/i", "\n", $message->getBody())); $mailer->MsgHTML($message->getBody()); $mailer->AddAddress($this->getUserMail($message->getTo())); $result = false; try { if ($mailer->Send()) { $message->setStatus(\oat\tao\model\messaging\Message::STATUS_SENT); $result = true; } if ($mailer->IsError()) { $message->setStatus(\oat\tao\model\messaging\Message::STATUS_ERROR); } } catch (phpmailerException $pe) { \common_Logger::e($pe->getMessage()); } $mailer->ClearReplyTos(); $mailer->ClearAllRecipients(); $mailer->SmtpClose(); return $result; }
/** * Get the mime-type of a file. If the mime-type cannot be found, * is returned. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param string fileName The path to the file. * @return string */ public static function getMimeType($fileName) { if (empty($fileName)) { common_Logger::e('getMimeType called without filename'); } $mime_types = array('txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'wmv' => 'video/x-ms-wmv', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'ogv' => 'video/ogg', 'oga' => 'audio/ogg', 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'srt' => 'application/x-subrip'); if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $fileName); finfo_close($finfo); } else { if (function_exists('mime_content_type')) { $mimetype = mime_content_type($fileName); } } if (!empty($mimetype)) { if (preg_match("/; charset/", $mimetype)) { $mimetypeInfos = explode(';', $mimetype); $mimetype = $mimetypeInfos[0]; } if (!preg_match("/^application/", $mimetype)) { return $mimetype; } } $explosion = explode('.', $fileName); $ext = strtolower(array_pop($explosion)); if (array_key_exists($ext, $mime_types)) { return $mime_types[$ext]; } else { return empty($mimetype) ? 'application/octet-stream' : $mimetype; } }
/** * Loop all items and call extract function * * @param array $items * @return array * @throws ExtractorException */ public function getDataByItems(array $items) { $output = []; foreach ($items as $item) { try { $output[] = $this->getDataByItem($item); } catch (ExtractorException $e) { \common_Logger::e('ERROR on item ' . $item->getUri() . ' : ' . $e->getMessage()); } } if (empty($output)) { throw new ExtractorException('No data item to export.'); } return $output; }
/** * returns a module by ID * * @access public * @author firstname and lastname of author, <*****@*****.**> * @param string $id * @return Module */ public function getModule($id) { $returnValue = null; $className = $this->getId() . '_actions_' . $id; if (class_exists($className)) { $returnValue = new $className(); } else { common_Logger::e('could not load ' . $className); } return $returnValue; }
/** * install an extension * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @return void */ public function install() { common_Logger::i('Installing extension ' . $this->extension->getId(), 'INSTALL'); if ($this->extension->getId() == 'generis') { throw new common_ext_ForbiddenActionException('Tried to install generis using the ExtensionInstaller', $this->extension->getId()); } try { // not yet installed? if (common_ext_ExtensionsManager::singleton()->isInstalled($this->extension->getId())) { throw new common_ext_AlreadyInstalledException('Problem installing extension ' . $this->extension->getId() . ' : Already installed', $this->extension->getId()); } else { // we purge the whole cache. $cache = common_cache_FileCache::singleton(); $cache->purge(); //check dependances if (!$this->checkRequiredExtensions()) { // unreachable code } // deprecated, but might still be used $this->installLoadDefaultConfig(); $this->installOntology(); $this->installRegisterExt(); $this->installLoadConstants(); $this->installExtensionModel(); common_Logger::d('Installing custom script for extension ' . $this->extension->getId()); $this->installCustomScript(); common_Logger::d('Done installing custom script for extension ' . $this->extension->getId()); if ($this->getLocalData() == true) { common_Logger::d('Installing local data for extension ' . $this->extension->getId()); $this->installLocalData(); common_Logger::d('Done installing local data for extension ' . $this->extension->getId()); } common_Logger::d('Extended install for extension ' . $this->extension->getId()); // Method to be overriden by subclasses // to extend the installation mechanism. $this->extendedInstall(); common_Logger::d('Done extended install for extension ' . $this->extension->getId()); } } catch (common_ext_ExtensionException $e) { // Rethrow common_Logger::e('Exception raised ' . $e->getMessage()); throw $e; } }
/** * Short description of method createTransitionRule * * @access private * @author Joel Bout, <*****@*****.**> * @param Resource connector * @param Expression expression * @return core_kernel_classes_Resource */ private function createTransitionRule(core_kernel_classes_Resource $connector, core_kernel_rules_Expression $expression) { $returnValue = null; $transitionRule = $connector->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_CONNECTORS_TRANSITIONRULE)); if (empty($transitionRule) || $transitionRule == null) { //create an instance of transition rule: $transitionRuleClass = new core_kernel_classes_Class(CLASS_TRANSITIONRULES); $transitionRule = $transitionRuleClass->createInstance(); //Associate the newly created transition rule to the connector: $connector->editPropertyValues(new core_kernel_classes_Property(PROPERTY_CONNECTORS_TRANSITIONRULE), $transitionRule->getUri()); } if (empty($expression)) { common_Logger::e('condition is not an instance of ressource : ' . $expression); } else { //delete old condition: $oldCondition = $transitionRule->getOnePropertyValue(new core_kernel_classes_Property(PROPERTY_RULE_IF)); if (!is_null($oldCondition)) { $this->deleteCondition($oldCondition); } $transitionRule->editPropertyValues(new core_kernel_classes_Property(PROPERTY_RULE_IF), $expression); } $returnValue = $transitionRule; return $returnValue; }