/** * Short description of method init * * @access public * @author Sam * @param array configuration * @return boolean */ public function init($configuration) { parent::init($configuration); $this->data = array(); $this->archivers = array(); if (isset($configuration['local_server_comment'])) { $this->comment = strval($configuration['local_server_comment']); } foreach ($configuration['archivers'] as $archiverConfig) { if (isset($archiverConfig['class'])) { $classname = $archiverConfig['class']; if (!class_exists($classname)) { $classname = 'common_profiler_archiver_' . $classname; } if (class_exists($classname)) { $archiver = new $classname(); try { if ($archiver instanceof common_profiler_archiver_Archiver && !is_null($archiver) && $archiver->init($archiverConfig)) { $this->archivers[] = $archiver; } } catch (InvalidArgumentException $e) { common_Logger::w('archiver configuration issue: ' . $e->getMessage()); } } } } return true; }
public function getStrings($values) { $contentStrings = array(); $xmlTokenizer = new taoItems_models_classes_search_XmlItemContentTokenizer(); foreach ($values as $valueUri) { $file = new core_kernel_file_File($valueUri); try { $content = file_get_contents($file->getAbsolutePath()); if ($content === false) { common_Logger::w('File ' . $file->getAbsolutePath() . ' not found for item'); } else { // Try to make it a DOM Document... $dom = new DOMDocument('1.0', 'UTF-8'); if (@$dom->loadXML($content) === true) { $contentStrings = array_merge($contentStrings, $xmlTokenizer->getStrings($dom)); unset($dom); } else { common_Logger::d('Skipped non XML content for ' . $file->getUri()); } } } catch (common_Exception $exc) { common_Logger::w('Invalid file ' . $valueUri . ' for ItemContentTokenizer: ' . $exc->getMessage()); } } return $contentStrings; }
/** * * @param array callOptions an array of parameters sent to the results storage configuration * @param mixed $resultServer * @param string uri or resource */ public function __construct($resultServer, $additionalStorages = array()) { $this->implementations = array(); if (is_object($resultServer) and get_class($resultServer) == 'core_kernel_classes_Resource') { $this->resultServer = $resultServer; } else { if (common_Utils::isUri($resultServer)) { $this->resultServer = new core_kernel_classes_Resource($resultServer); } } // the static storages if ($this->resultServer->getUri() != TAO_VOID_RESULT_SERVER) { $resultServerModels = $this->resultServer->getPropertyValues(new core_kernel_classes_Property(TAO_RESULTSERVER_MODEL_PROP)); if (!isset($resultServerModels) or count($resultServerModels) == 0) { throw new common_Exception("The result server is not correctly configured (Resource definition)"); } foreach ($resultServerModels as $resultServerModelUri) { $resultServerModel = new core_kernel_classes_Resource($resultServerModelUri); $this->addImplementation($resultServerModel->getUniquePropertyValue(new core_kernel_classes_Property(TAO_RESULTSERVER_MODEL_IMPL_PROP))->literal); } } if (!is_null($additionalStorages)) { // the dynamic storages foreach ($additionalStorages as $additionalStorage) { $this->addImplementation($additionalStorage["implementation"], $additionalStorage["parameters"]); } } common_Logger::i("Result Server Initialized using defintion:" . $this->resultServer->getUri()); // sets the details required depending on the type of storage }
public function setUp() { TaoPhpUnitTestRunner::initTest(); $this->disableCache(); // creates a user using remote script from joel $testUserData = array(PROPERTY_USER_LOGIN => 'tjdoe', PROPERTY_USER_PASSWORD => 'test123', PROPERTY_USER_LASTNAME => 'Doe', PROPERTY_USER_FIRSTNAME => 'John', PROPERTY_USER_MAIL => '*****@*****.**', PROPERTY_USER_DEFLG => \tao_models_classes_LanguageService::singleton()->getLanguageByCode(DEFAULT_LANG)->getUri(), PROPERTY_USER_UILG => \tao_models_classes_LanguageService::singleton()->getLanguageByCode(DEFAULT_LANG)->getUri(), PROPERTY_USER_ROLES => array(INSTANCE_ROLE_GLOBALMANAGER)); $testUserData[PROPERTY_USER_PASSWORD] = 'test' . rand(); $data = $testUserData; $data[PROPERTY_USER_PASSWORD] = \core_kernel_users_Service::getPasswordHash()->encrypt($data[PROPERTY_USER_PASSWORD]); $tmclass = new \core_kernel_classes_Class(CLASS_TAO_USER); $user = $tmclass->createInstanceWithProperties($data); \common_Logger::i('Created user ' . $user->getUri()); // prepare a lookup table of languages and values $usage = new \core_kernel_classes_Resource(INSTANCE_LANGUAGE_USAGE_GUI); $propValue = new \core_kernel_classes_Property(RDF_VALUE); $langService = \tao_models_classes_LanguageService::singleton(); $lookup = array(); foreach ($langService->getAvailableLanguagesByUsage($usage) as $lang) { $lookup[$lang->getUri()] = (string) $lang->getUniquePropertyValue($propValue); } $data = array('rootUrl' => ROOT_URL, 'userUri' => $user->getUri(), 'userData' => $testUserData, 'lang' => $lookup); $this->login = $data['userData'][PROPERTY_USER_LOGIN]; $this->password = $data['userData'][PROPERTY_USER_PASSWORD]; $this->userUri = $data['userUri']; }
/** * Create a formatted failure report and log a warning * * @param $userMessage * @param null $model * @return Report */ private function createFailure($userMessage, $model = null) { $typeIdentifier = is_null($model) ? 'unknown type' : $model->getTypeIdentifier(); $message = 'The portable element cannot be registered "' . $typeIdentifier . '", reason: ' . $userMessage; \common_Logger::w($message); return Report::createFailure($message); }
/** * (non-PHPdoc) * @see \oat\tao\model\media\MediaBrowser::getDirectory */ public function getDirectory($parentLink = '/', $acceptableMime = array(), $depth = 1) { $sysPath = $this->getSysPath($parentLink); $label = substr($parentLink, strrpos($parentLink, '/') + 1); if (!$label) { $label = 'local'; } $data = array('path' => $parentLink, 'label' => $label); if ($depth > 0) { $children = array(); if (is_dir($sysPath)) { foreach (new DirectoryIterator($sysPath) as $fileinfo) { if (!$fileinfo->isDot()) { $subPath = rtrim($parentLink, '/') . '/' . $fileinfo->getFilename(); if ($fileinfo->isDir()) { $children[] = $this->getDirectory($subPath, $acceptableMime, $depth - 1); } else { $file = $this->getFileInfo($subPath, $acceptableMime); if (!is_null($file) && (count($acceptableMime) == 0 || in_array($file['mime'], $acceptableMime))) { $children[] = $file; } } } } } else { common_Logger::w('"' . $sysPath . '" is not a directory'); } $data['children'] = $children; } else { $data['url'] = _url('files', 'ItemContent', 'taoItems', array('uri' => $this->item->getUri(), 'lang' => $this->lang, 'path' => $parentLink)); } return $data; }
/** * Load the extension. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param array $extraConstants * @return mixed */ public function load($extraConstants = array()) { if (!empty($extraConstants)) { throw new common_exception_Error('Loading extra constants in ' . __CLASS__ . ' nolonger supported'); } common_Logger::t('Loading extension ' . $this->getExtension()->getId() . ' constants'); // load the constants from the manifest if ($this->extension->getId() != "generis") { foreach ($this->extension->getConstants() as $key => $value) { if (!defined($key) && !is_array($value)) { define($key, $value); } } } $constantFile = $this->getExtension()->getDir() . 'includes' . DIRECTORY_SEPARATOR . 'constants.php'; if (file_exists($constantFile)) { //include the constant file include_once $constantFile; //this variable comes from the constant file and contain the const definition if (isset($todefine)) { foreach ($todefine as $constName => $constValue) { if (!defined($constName)) { define($constName, $constValue); //constants are defined there! } else { common_Logger::d('Constant ' . $constName . ' in ' . $this->getExtension()->getId() . ' has already been defined'); } } unset($todefine); } } }
public function send(Message $message) { $messageFile = $this->getFilePath($message->getTo()); \common_Logger::d('Wrote message to ' . $messageFile); $written = file_put_contents($messageFile, $message->getBody()); return $written !== false; }
/** * @author "Lionel Lecaque, <*****@*****.**>" * @param string $namespace * @param string $data xml content */ public function createModel($namespace, $data) { $modelId = $this->getModelId($namespace); if ($modelId === false) { common_Logger::d('modelId not found, need to add namespace ' . $namespace); $this->addNewModel($namespace); //TODO bad way, need to find better $modelId = $this->getModelId($namespace); } $modelDefinition = new EasyRdf_Graph($namespace); if (is_file($data)) { $modelDefinition->parseFile($data); } else { $modelDefinition->parse($data); } $graph = $modelDefinition->toRdfPhp(); $resources = $modelDefinition->resources(); $format = EasyRdf_Format::getFormat('php'); $data = $modelDefinition->serialise($format); foreach ($data as $subjectUri => $propertiesValues) { foreach ($propertiesValues as $prop => $values) { foreach ($values as $k => $v) { $this->addStatement($modelId, $subjectUri, $prop, $v['value'], isset($v['lang']) ? $v['lang'] : null); } } } return true; }
public function initElements() { $class = $this->data['class']; if (!$class instanceof \core_kernel_classes_Class) { throw new \common_Exception('missing class in simple delivery creation form'); } $classUriElt = \tao_helpers_form_FormFactory::getElement('classUri', 'Hidden'); $classUriElt->setValue($class->getUri()); $this->form->addElement($classUriElt); //create the element to select the import format $formatElt = \tao_helpers_form_FormFactory::getElement('test', 'Combobox'); $formatElt->setDescription(__('Select the test you want to publish to the test-takers')); $testClass = new \core_kernel_classes_Class(TAO_TEST_CLASS); $options = array(); $testService = \taoTests_models_classes_TestsService::singleton(); foreach ($testClass->getInstances(true) as $test) { try { $testItems = $testService->getTestItems($test); //Filter tests which has no items if (!empty($testItems)) { $options[$test->getUri()] = $test->getLabel(); } } catch (\Exception $e) { \common_Logger::w('Unable to load items for test ' . $test->getUri()); } } if (empty($options)) { throw new NoTestsException(); } $formatElt->setOptions($options); $formatElt->addValidator(\tao_helpers_form_FormFactory::getValidator('NotEmpty')); $this->form->addElement($formatElt); }
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); } }
private function getUncached($property) { $value = array(); switch ($property) { case PROPERTY_USER_DEFLG: case PROPERTY_USER_UILG: $resource = $this->getUserResource()->getOnePropertyValue(new \core_kernel_classes_Property($property)); if (!is_null($resource)) { if ($resource instanceof \core_kernel_classes_Resource) { return array($resource->getUniquePropertyValue(new \core_kernel_classes_Property(RDF_VALUE))); } else { common_Logger::w('Language ' . $resource . ' is not a resource'); return array(DEFAULT_LANG); } } else { return array(DEFAULT_LANG); } break; case PROPERTY_USER_ROLES: return array("http://www.tao.lu/Ontologies/TAOItem.rdf#TestAuthor", "http://www.tao.lu/Ontologies/TAOItem.rdf#ItemAuthor"); case "http://www.tao.lu/Ontologies/TAO.rdf#FirstTimeInTao": return array("http://www.tao.lu/Ontologies/generis.rdf#False"); case "http://www.tao.lu/Ontologies/TAO.rdf#LastExtensionUsed": return array("tao/Main/index?structure=items&ext=taoItems"); default: return $this->getUserResource()->getPropertyValues(new \core_kernel_classes_Property($property)); } }
/** * Returns a json encoded array describign a directory * * @throws common_exception_MissingParameter * @return string */ public function files() { if (!$this->hasRequestParameter('uri')) { throw new common_exception_MissingParameter('uri', __METHOD__); } $testUri = $this->getRequestParameter('uri'); $test = new core_kernel_classes_Resource($testUri); if (!$this->hasRequestParameter('lang')) { throw new common_exception_MissingParameter('lang', __METHOD__); } $testLang = $this->getRequestParameter('lang'); $subPath = $this->hasRequestParameter('path') ? $this->getRequestParameter('path') : '/'; $depth = $this->hasRequestParameter('depth') ? $this->getRequestParameter('depth') : 1; //build filters $filters = array(); if ($this->hasRequestParameter('filters')) { $filterParameter = $this->getRequestParameter('filters'); if (!empty($filterParameter)) { if (preg_match('/\\/\\*/', $filterParameter)) { common_Logger::w('Stars mime type are not yet supported, filter "' . $filterParameter . '" will fail'); } $filters = array_map('trim', explode(',', $filterParameter)); } } $data = taoQtiTest_helpers_ResourceManager::buildDirectory($test, $testLang, $subPath, $depth, $filters); echo json_encode($data); }
/** * Creates a new delivery * * @param core_kernel_classes_Class $deliveryClass * @param core_kernel_classes_Resource $test * @param array $properties Array of properties of delivery * @return common_report_Report */ public static function create(\core_kernel_classes_Class $deliveryClass, \core_kernel_classes_Resource $test, $properties = array()) { \common_Logger::i('Creating delivery with ' . $test->getLabel() . ' under ' . $deliveryClass->getLabel()); $storage = new TrackedStorage(); $testCompilerClass = \taoTests_models_classes_TestsService::singleton()->getCompilerClass($test); $compiler = new $testCompilerClass($test, $storage); $report = $compiler->compile(); if ($report->getType() == \common_report_Report::TYPE_SUCCESS) { //$tz = new \DateTimeZone(\common_session_SessionManager::getSession()->getTimeZone()); $tz = new \DateTimeZone('UTC'); if (!empty($properties[TAO_DELIVERY_START_PROP])) { $dt = new \DateTime($properties[TAO_DELIVERY_START_PROP], $tz); $properties[TAO_DELIVERY_START_PROP] = (string) $dt->getTimestamp(); } if (!empty($properties[TAO_DELIVERY_END_PROP])) { $dt = new \DateTime($properties[TAO_DELIVERY_END_PROP], $tz); $properties[TAO_DELIVERY_END_PROP] = (string) $dt->getTimestamp(); } $serviceCall = $report->getData(); $properties[PROPERTY_COMPILEDDELIVERY_DIRECTORY] = $storage->getSpawnedDirectoryIds(); $compilationInstance = DeliveryAssemblyService::singleton()->createAssemblyFromServiceCall($deliveryClass, $serviceCall, $properties); $report->setData($compilationInstance); } return $report; }
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'))); } }
/** * * @param string $currentVersion * @return string $versionUpdatedTo */ public function update($initialVersion) { $currentVersion = $initialVersion; //migrate from 2.6 to 2.6.1 if ($currentVersion == '2.6') { //data upgrade OntologyUpdater::syncModels(); $currentVersion = '2.6.1'; } if ($currentVersion == '2.6.1') { $ext = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoDelivery'); $className = $ext->getConfig(\taoDelivery_models_classes_execution_ServiceProxy::CONFIG_KEY); if (is_string($className)) { $impl = null; switch ($className) { case 'taoDelivery_models_classes_execution_OntologyService': $impl = new \taoDelivery_models_classes_execution_OntologyService(); break; case 'taoDelivery_models_classes_execution_KeyValueService': $impl = new \taoDelivery_models_classes_execution_KeyValueService(array(\taoDelivery_models_classes_execution_KeyValueService::OPTION_PERSISTENCE => 'deliveryExecution')); break; default: \common_Logger::w('Unable to migrate custom execution service'); } if (!is_null($impl)) { $proxy = \taoDelivery_models_classes_execution_ServiceProxy::singleton(); $proxy->setImplementation($impl); $currentVersion = '2.6.2'; } } } return $currentVersion; }
/** * @param array $conditions * @param string $conditionService * @return bool */ protected function complies(array $conditions, $conditionService) { $clientName = $conditionService::singleton()->getClientName(); $clientVersion = $conditionService::singleton()->getClientVersion(); $clientNameResource = $conditionService::singleton()->getClientNameResource(); \common_Logger::i("Detected client: {$clientName} @ {$clientVersion}"); $result = false; /** @var \core_kernel_classes_Property $browser */ foreach ($conditions as $condition) { if ($condition->exists() === true) { /** @var \core_kernel_classes_Resource $requiredName */ $requiredName = $condition->getOnePropertyValue(new \core_kernel_classes_Property($conditionService::PROPERTY_NAME)); if ($clientNameResource && !$clientNameResource->equals($requiredName)) { \common_Logger::i("Client rejected. Required name is {$requiredName} but current name is {$clientName}."); continue; } elseif ($clientNameResource === null) { \common_Logger::i("Client rejected. Unknown client."); continue; } $requiredVersion = $condition->getOnePropertyValue(new \core_kernel_classes_Property($conditionService::PROPERTY_VERSION)); if (-1 !== version_compare($conditionService::singleton()->getClientVersion(), $requiredVersion)) { $result = true; break; } } } return $result; }
/** * Short description of method authenticate * * @access public * @author Joel Bout, <*****@*****.**> * @param Repository vcs * @param string login * @param string password * @return boolean */ public function authenticate(core_kernel_versioning_Repository $vcs, $login, $password) { $returnValue = (bool) false; common_Logger::i(__FUNCTION__ . ' called on local directory', 'LOCALVCS'); $returnValue = is_dir($vcs->getPath()); return (bool) $returnValue; }
public static function buildDirectory(core_kernel_classes_Resource $test, $lang, $relPath = '/', $depth = 1, $filters = array()) { $baseDir = self::getBaseDir($test); $path = $baseDir . ltrim($relPath, '/'); $data = array('path' => $relPath); if ($depth > 0) { $children = array(); if (is_dir($path)) { foreach (new DirectoryIterator($path) as $fileinfo) { if (!$fileinfo->isDot()) { $subPath = rtrim($relPath, '/') . '/' . $fileinfo->getFilename(); if ($fileinfo->isDir()) { $children[] = self::buildDirectory($test, $lang, $subPath, $depth - 1, $filters); } else { $file = self::buildFile($test, $lang, $subPath, $filters); if (!is_null($file)) { $children[] = $file; } } } } } else { common_Logger::w('"' . $path . '" is not a directory'); } $data['children'] = $children; } else { $data['url'] = _url('files', 'TestContent', 'taoQtiTest', array('uri' => $test->getUri(), 'lang' => $lang, 'path' => $relPath)); } return $data; }
public function __invoke($params) { $persistenceId = count($params) > 0 ? reset($params) : 'default'; $persistence = $this->getServiceLocator()->get(\common_persistence_Manager::SERVICE_KEY)->getPersistenceById($persistenceId); $schemaManager = $persistence->getDriver()->getSchemaManager(); $schema = $schemaManager->createSchema(); $fromSchema = clone $schema; try { $revisionTable = $schema->createtable(Storage::REVISION_TABLE_NAME); $revisionTable->addOption('engine', 'MyISAM'); $revisionTable->addColumn(Storage::REVISION_RESOURCE, "string", array("notnull" => false, "length" => 255)); $revisionTable->addColumn(Storage::REVISION_VERSION, "string", array("notnull" => false, "length" => 50)); $revisionTable->addColumn(Storage::REVISION_USER, "string", array("notnull" => true, "length" => 255)); $revisionTable->addColumn(Storage::REVISION_CREATED, "string", array("notnull" => true)); $revisionTable->addColumn(Storage::REVISION_MESSAGE, "string", array("notnull" => true, "length" => 4000)); $revisionTable->setPrimaryKey(array(Storage::REVISION_RESOURCE, Storage::REVISION_VERSION)); $dataTable = $schema->createtable(Storage::DATA_TABLE_NAME); $dataTable->addOption('engine', 'MyISAM'); $dataTable->addColumn(Storage::DATA_RESOURCE, "string", array("notnull" => false, "length" => 255)); $dataTable->addColumn(Storage::DATA_VERSION, "string", array("notnull" => false, "length" => 50)); $dataTable->addColumn(Storage::DATA_SUBJECT, "string", array("notnull" => true, "length" => 255)); $dataTable->addColumn(Storage::DATA_PREDICATE, "string", array("length" => 255)); // not compatible with oracle $dataTable->addColumn(Storage::DATA_OBJECT, "text", array("default" => null, "notnull" => false)); $dataTable->addColumn(Storage::DATA_LANGUAGE, "string", array("length" => 50)); $dataTable->addForeignKeyConstraint($revisionTable, array(Storage::REVISION_RESOURCE, Storage::REVISION_VERSION), array(Storage::REVISION_RESOURCE, Storage::REVISION_VERSION)); } catch (SchemaException $e) { \common_Logger::i('Database Schema already up to date.'); } $queries = $persistence->getPlatform()->getMigrateSchemaSql($fromSchema, $schema); foreach ($queries as $query) { $persistence->exec($query); } }
public function __invoke($params) { if (!isset($params[0])) { return new \common_report_Report(\common_report_Report::TYPE_ERROR, __('Usage: InitRdsQueue PERSISTENCE_ID')); } $persistenceId = $params[0]; $serviceManager = ServiceManager::getServiceManager(); $persistence = \common_persistence_Manager::getPersistence($persistenceId); $schemaManager = $persistence->getDriver()->getSchemaManager(); $schema = $schemaManager->createSchema(); $fromSchema = clone $schema; try { $queueTable = $schema->createtable(RdsQueue::QUEUE_TABLE_NAME); $queueTable->addOption('engine', 'MyISAM'); $queueTable->addColumn(RdsQueue::QUEUE_ID, "integer", array("notnull" => true, "autoincrement" => true)); $queueTable->addColumn(RdsQueue::QUEUE_STATUS, "string", array("notnull" => true, "length" => 50)); $queueTable->addColumn(RdsQueue::QUEUE_ADDED, "string", array("notnull" => true)); $queueTable->addColumn(RdsQueue::QUEUE_UPDATED, "string", array("notnull" => true)); $queueTable->addColumn(RdsQueue::QUEUE_OWNER, "string", array("notnull" => false, "length" => 255)); $queueTable->addColumn(RdsQueue::QUEUE_TASK, "string", array("notnull" => true, "length" => 4000)); $queueTable->setPrimaryKey(array(RdsQueue::QUEUE_ID)); $queries = $persistence->getPlatform()->getMigrateSchemaSql($fromSchema, $schema); foreach ($queries as $query) { $persistence->exec($query); } } catch (SchemaException $e) { \common_Logger::i('Database Schema already up to date.'); } $queue = new RdsQueue(array(RdsQueue::OPTION_PERSISTENCE => $persistenceId)); $serviceManager->register(Queue::CONFIG_ID, $queue); return new \common_report_Report(\common_report_Report::TYPE_SUCCESS, __('Setup rds queue successfully')); }
/** * Update all the item files found within the $itemRootPath * @param boolean $changeItemContent - tells if the item files will be written with the updated content or not * @return array of modified item instances */ public function update($changeItemContent = false) { $returnValue = array(); $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->itemPath), RecursiveIteratorIterator::SELF_FIRST); $i = 0; $fixed = 0; foreach ($objects as $itemFile => $cursor) { if (is_file($itemFile)) { $this->checkedFiles[$itemFile] = false; if (basename($itemFile) === 'qti.xml') { $i++; $xml = new \DOMDocument(); $xml->load($itemFile); $parser = new ParserFactory($xml); $item = $parser->load(); \common_Logger::i('checking item #' . $i . ' id:' . $item->attr('identifier') . ' file:' . $itemFile); if ($this->updateItem($item, $itemFile)) { $this->checkedFiles[$itemFile] = true; $returnValue[$itemFile] = $item; \common_Logger::i('fixed required for #' . $i . ' id:' . $item->attr('identifier') . ' file:' . $itemFile); if ($changeItemContent) { $fixed++; \common_Logger::i('item fixed #' . $i . ' id:' . $item->attr('identifier') . ' file:' . $itemFile); file_put_contents($itemFile, $item->toXML()); } } } } } \common_Logger::i('total item fixed : ' . $fixed); return $returnValue; }
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; }
/** * Maps a fuly qualified or abbreviated lti role * to an existing tao role * * @param string $role * @throws common_Exception * @throws common_exception_Error * @return core_kernel_classes_Resource the tao role or null */ public static function mapLTIRole2TaoRole($role) { $taoRole = null; if (filter_var($role, FILTER_VALIDATE_URL)) { // url found $taoRole = new core_kernel_classes_Resource($role); } else { // if not fully qualified prepend LIS context role NS if (strtolower(substr($role, 0, 4)) !== 'urn:') { $role = self::LIS_CONTEXT_ROLE_NAMESPACE . $role; } list($prefix, $nid, $nss) = explode(':', $role, 3); if ($nid != 'lti') { common_Logger::w('Non LTI URN ' . $role . ' passed via LTI'); } $urn = 'urn:' . strtolower($nid) . ':' . $nss; // search for fitting role $class = new core_kernel_classes_Class(CLASS_LTI_ROLES); $cand = $class->searchInstances(array(PROPERTY_LTI_ROLES_URN => $urn)); if (count($cand) > 1) { throw new common_exception_Error('Multiple instances share the URN ' . $urn); } if (count($cand) == 1) { $taoRole = current($cand); } else { common_Logger::w('Unknown LTI role with urn: ' . $urn); } } if (!is_null($taoRole) && $taoRole->exists()) { return $taoRole->getUri(); } else { return null; } }
/** * 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; }
/** * Log in a user into Generis that has one of the provided $allowedRoles. * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @param string login The login of the user. * @param string password the md5 hash of the password. * @param allowedRoles A Role or an array of Roles that are allowed to be logged in. If the user has a Role that matches one or more Roles in this array, the login request will be accepted. * @return boolean */ public function login(common_user_auth_Adapter $adapter, $allowedRoles = array()) { $returnValue = (bool) false; try { $user = $adapter->authenticate(); if (!empty($allowedRoles)) { // Role can be either a scalar value or a collection. $allowedRoles = is_array($allowedRoles) ? $allowedRoles : array($allowedRoles); $roles = array(); foreach ($allowedRoles as $r) { $roles[] = $r instanceof core_kernel_classes_Resource ? $r->getUri() : $r; } unset($allowedRoles); $intersect = array_intersect($roles, $user->getRoles()); if (empty($intersect)) { common_Logger::w('User ' . $user->getIdentifier() . ' does not have the nescessary role'); return false; } } $returnValue = $this->startSession($user); } catch (common_user_auth_AuthFailedException $exception) { // failed return false; } return (bool) $returnValue; }
/** * * @return \Psr\Log\LoggerInterface */ public function getLogger() { if (is_null($this->logger)) { $this->logger = new \common_log_Logger2Psr(\common_Logger::singleton()); } return $this->logger; }
/** * Entrypoint of every tool */ public function launch() { try { taoLti_models_classes_LtiService::singleton()->startLtiSession(common_http_Request::currentRequest()); // check if cookie has been set if (tao_models_classes_accessControl_AclProxy::hasAccess('verifyCookie', 'CookieUtils', 'taoLti')) { $this->redirect(_url('verifyCookie', 'CookieUtils', 'taoLti', array('session' => session_id(), 'redirect' => _url('run', null, null, $_GET)))); } else { $this->returnError(__('You are not authorized to use this system')); } } catch (common_user_auth_AuthFailedException $e) { common_Logger::i($e->getMessage()); $this->returnError(__('The LTI connection could not be established'), false); } catch (taoLti_models_classes_LtiException $e) { // In regard of the IMS LTI standard, we have to show a back button that refer to the // launch_presentation_return_url url param. So we have to retrieve this parameter before trying to start // the session $params = common_http_Request::currentRequest()->getParams(); if (isset($params[taoLti_models_classes_LtiLaunchData::TOOL_CONSUMER_INSTANCE_NAME])) { $this->setData('consumerLabel', $params[taoLti_models_classes_LtiLaunchData::TOOL_CONSUMER_INSTANCE_NAME]); } elseif (isset($params[taoLti_models_classes_LtiLaunchData::TOOL_CONSUMER_INSTANCE_DESCRIPTION])) { $this->setData('consumerLabel', $params[taoLti_models_classes_LtiLaunchData::TOOL_CONSUMER_INSTANCE_DESCRIPTION]); } if (isset($params[taoLti_models_classes_LtiLaunchData::LAUNCH_PRESENTATION_RETURN_URL])) { $this->setData('returnUrl', $params[taoLti_models_classes_LtiLaunchData::LAUNCH_PRESENTATION_RETURN_URL]); } common_Logger::i($e->getMessage()); $this->returnError(__('The LTI connection could not be established'), false); } catch (tao_models_classes_oauth_Exception $e) { common_Logger::i($e->getMessage()); $this->returnError(__('The LTI connection could not be established'), false); } }
/** * uninstall an extension * * @access public * @author Jerome Bogaerts, <*****@*****.**> * @return boolean */ public function uninstall() { common_Logger::i('Uninstalling ' . $this->extension->getId(), 'UNINSTALL'); // uninstall possible if (is_null($this->extension->getManifest()->getUninstallData())) { throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Uninstall not supported'); } // installed? if (!common_ext_ExtensionsManager::singleton()->isInstalled($this->extension->getId())) { throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Not installed'); } // check dependcies if (helpers_ExtensionHelper::isRequired($this->extension)) { throw new common_Exception('Problem uninstalling extension ' . $this->extension->getId() . ' : Still required'); } common_Logger::d('uninstall script for ' . $this->extension->getId()); $this->uninstallScripts(); // hook $this->extendedUninstall(); common_Logger::d('unregister extension ' . $this->extension->getId()); $this->unregister(); // we purge the whole cache. $cache = common_cache_FileCache::singleton(); $cache->purge(); common_Logger::i('Uninstalled ' . $this->extension->getId()); return true; }
public function importDelivery(core_kernel_classes_Class $deliveryClass, $archiveFile) { $folder = tao_helpers_File::createTempDir(); $zip = new ZipArchive(); if ($zip->open($archiveFile) !== true) { return common_report_Report::createFailure(__('Unable to export Archive')); } $zip->extractTo($folder); $zip->close(); $manifestPath = $folder . self::MANIFEST_FILE; if (!file_exists($manifestPath)) { return common_report_Report::createFailure(__('Manifest not found in assembly')); } $manifest = json_decode(file_get_contents($manifestPath), true); try { $this->importDeliveryFiles($deliveryClass, $manifest, $folder); $delivery = $this->importDeliveryResource($deliveryClass, $manifest); $report = common_report_Report::createSuccess(__('Delivery "%s" successfully imported', $delivery->getUri()), $delivery); } catch (Exception $e) { common_Logger::w($e->getMessage()); if (isset($delivery) && $delivery instanceof core_kernel_classes_Resource) { $delivery->delete(); } $report = common_report_Report::createFailure(__('Unkown error during impoort')); } return $report; }