function formatPath($path) { $path = 'users' . DS . $_SESSION['nearos']['username'] . DS . normalizePath($path); $path = str_replace('/', DS, $path); $path = str_replace('\\', DS, $path); return $path; }
public function testNormalizePath() { $this->assertSame("/etc/foobar", normalizePath("/etc/foobar")); $this->assertSame("/etc/foobar", normalizePath("/etc/foobar/")); $this->assertSame("/etc/foobar", normalizePath("/etc/foobar/")); $this->assertSame("C:/etc/foobar", normalizePath("C:\\etc\\foobar\\")); }
/** * test that installation of a plugin responding "false" at beforeInstall stops * the entire process. * * @return void */ public function testInstallStops() { $this->post('/admin/system/plugins/install', ['path' => normalizePath(ROOT . '/plugins/source/NukedApp/'), 'activate' => 0, 'file_system' => 'Install from File System']); // message generated from plugin's event listener $this->assertResponseContains('This plugin cannot be installed as it is NUKED', 'failed when installing nuked plugin'); $this->assertResponseOk(); }
function __construct($dir = null) { if ($dir == null) { $this->workDirectory = normalizePath(__DIR__ . "/../modules/"); } else { $this->workDirectory = normalizePath($dir); } #Set another work directory ($dir) }
/** * Deletes a file for the given FileField instance. * * File name must be passes as `file` GET parameter. * * @param string $name EAV attribute name * @return void * @throws \Cake\Network\Exception\NotFoundException When invalid attribute name * is given */ public function delete($name) { $this->loadModel('Field.FieldInstances'); $instance = $this->_getInstance($name); if ($instance && !empty($this->request->query['file'])) { $file = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/{$this->request->query['file']}", DS); $file = new File($file); $file->delete(); } $response = ''; $this->viewBuilder()->layout('ajax'); $this->title(__d('field', 'Delete File')); $this->set(compact('response')); }
function boot($rootDir, $urlDepth = 0, callable $onStartUp = null) { $rootDir = normalizePath($rootDir); // Initialize some settings from environment variables $dotenv = new Dotenv("{$rootDir}/.env"); try { $dotenv->load(); } catch (ConfigException $e) { echo $e->getMessage(); return 1; } // Load the kernel's configuration. /** @var KernelSettings $kernelSettings */ $kernelSettings = $this->kernelSettings = $this->injector->share(KernelSettings::class, 'app')->make(KernelSettings::class); $kernelSettings->isWebBased = true; $kernelSettings->setApplicationRoot($rootDir, $urlDepth); // Setup debugging (must be done before instantiating the kernel, but after instantiating its settings). $this->setupDebugging($rootDir); // Boot up the framework's kernel. $this->injector->execute([KernelModule::class, 'register']); // Boot up the framework's subsytems and the application's modules. /** @var KernelInterface $kernel */ $kernel = $this->injector->make(KernelInterface::class); if ($onStartUp) { $onStartUp($kernel); } // Boot up all modules. try { $kernel->boot(); } catch (ConfigException $e) { $NL = "<br>\n"; echo $e->getMessage() . $NL . $NL; if ($e->getCode() == -1) { echo sprintf('Possile error causes:%2$s%2$s- the class name may be misspelled,%2$s- the class may no longer exist,%2$s- module %1$s may be missing or it may be corrupted.%2$s%2$s', str_match($e->getMessage(), '/from module (\\S+)/')[1], $NL); } $path = "{$kernelSettings->storagePath}/" . ModulesRegistry::REGISTRY_FILE; if (file_exists($path)) { echo "Tip: one possible solution is to remove the '{$path}' file and run 'workman' to rebuild the module registry."; } } // Finalize. if ($kernel->devEnv()) { $this->setDebugPathsMap($this->injector->make(ModulesRegistry::class)); } return $kernel->getExitCode(); }
/** * Loads and registers plugin's namespace and loads its event listeners classes. * * This is used to allow plugins being installed to respond to events before * they are integrated to the system. Events such as `beforeInstall`, * `afterInstall`, etc. * * @param string $plugin Name of the plugin for which attach listeners * @param string $path Path to plugin's root directory (which contains "src") * @throws \Cake\Error\FatalErrorException On illegal usage of this method */ protected function _attachListeners($plugin, $path) { $path = normalizePath("{$path}/"); $eventsPath = normalizePath("{$path}/src/Event/"); if (is_readable($eventsPath) && is_dir($eventsPath)) { $EventManager = EventManager::instance(); $eventsFolder = new Folder($eventsPath); Plugin::load($plugin, ['autoload' => true, 'bootstrap' => false, 'routes' => false, 'path' => $path, 'classBase' => 'src', 'ignoreMissing' => true]); foreach ($eventsFolder->read(false, false, true)[1] as $classPath) { $className = preg_replace('/\\.php$/i', '', basename($classPath)); $fullClassName = implode('\\', [$plugin, 'Event', $className]); if (class_exists($fullClassName)) { $handler = new $fullClassName(); $this->_listeners[] = $handler; $EventManager->on($handler); } } } }
/** * Uploads a ZIP package to the server. * * @return bool True on success */ public function upload() { if (!isset($this->_package['tmp_name']) || !is_readable($this->_package['tmp_name'])) { $this->_error(__d('installer', 'Invalid package.')); return false; } elseif (!isset($this->_package['name']) || !str_ends_with(strtolower($this->_package['name']), '.zip')) { $this->_error(__d('installer', 'Invalid package format, it is not a ZIP package.')); return false; } else { $dst = normalizePath(TMP . $this->_package['name']); if (is_readable($dst)) { $file = new File($dst); $file->delete(); } if (move_uploaded_file($this->_package['tmp_name'], $dst)) { $this->_dst = $dst; return true; } } $this->_error(__d('installer', 'Package could not be uploaded, please check write permissions on /tmp directory.')); return false; }
/** * Main function Prints out the list of shells. * * @return void */ public function main() { if (!defined('QUICKAPPS_CORE')) { return parent::main(); } if (empty($this->params['xml'])) { $this->out(__d('cms', '<info>Current Paths:</info>'), 2); $this->out(__d('cms', '* QuickApps Core: {0}', [normalizePath(QUICKAPPS_CORE)])); $this->out(__d('cms', '* CakePHP Core: {0}', [normalizePath(CORE_PATH)])); $this->out(__d('cms', '* Site Path: {0}', [normalizePath(ROOT)])); $this->out(''); $this->out(__d('cms', '<info>Available Shells:</info>'), 2); } $shellList = $this->Command->getShellList(); if (empty($shellList)) { return; } if (empty($this->params['xml'])) { $this->_asText($shellList); } else { $this->_asXml($shellList); } }
return; } $filter = $plugin->status; if ($plugin->isTheme) { $filter = $filter && in_array($plugin->name, [option('front_theme'), option('back_theme')]); } if (!$filter) { return; } if (!in_array("{$plugin->name}\\", array_keys($classLoader->getPrefixesPsr4()))) { $classLoader->addPsr4("{$plugin->name}\\", normalizePath("{$plugin->path}/src/"), true); } if (!in_array("{$plugin->name}\\Test\\", array_keys($classLoader->getPrefixesPsr4()))) { $classLoader->addPsr4("{$plugin->name}\\Test\\", normalizePath("{$plugin->path}/tests/"), true); } $info = ['autoload' => false, 'bootstrap' => true, 'routes' => true, 'path' => normalizePath("{$plugin->path}/"), 'classBase' => 'src', 'ignoreMissing' => true]; Plugin::load($plugin->name, $info); foreach ($plugin->eventListeners as $fullClassName) { if (class_exists($fullClassName)) { if (str_ends_with($fullClassName, 'Shortcode')) { EventDispatcher::instance('Shortcode')->eventManager()->on(new $fullClassName()); } else { EventDispatcher::instance()->eventManager()->on(new $fullClassName()); } } } $pluginsPath[] = $info['path']; }); if (empty($pluginsPath)) { die("Ops, something went wrong. Try to clear your site's snapshot and verify write permissions on /tmp directory."); }
function generateThumbnail($originalImagePathFromRoot) { $imageGalleryRelative = $this->getGalleryRelativeURLFromPath($originalImagePathFromRoot); $filename = pathinfoFilename($imageGalleryRelative); $fileExtension = pathinfoExtension($imageGalleryRelative); $directory = pathinfoDirname($imageGalleryRelative); if ($directory === ".") { $directory = ""; } $directory = normalizePath($directory); $targetCachedFileName = $this->photosPathFromRoot . 'cache' . DIRECTORY_SEPARATOR . $directory . $filename . '_' . $this->settings['thumbnail_size'] . '.' . $fileExtension; $createCachedFile = $this->fileSystemHelper->generateCacheDirectory($directory); //Load the original image switch ($fileExtension) { case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($originalImagePathFromRoot); $format = "jpeg"; break; case 'png': $image = imagecreatefrompng($originalImagePathFromRoot); $format = "png"; break; } //Resize it $width = imagesx($image); $height = imagesy($image); $new_size = $this->resizedSize($width, $height); $newImage = ImageCreateTrueColor($new_size[0], $new_size[1]); imagecopyresampled($newImage, $image, 0, 0, 0, 0, $new_size[0], $new_size[1], $width, $height); $this->cacheImage($newImage, $targetCachedFileName, $format); return true; }
if ($add_meta) { $text = $frontmatter . $text; } if (substr($output_path, -1) != '/') { $output_path = $output_path . '/'; } $directory = $output_path . $directory; // create directory if necessary if (!empty($directory)) { if (!file_exists($directory)) { mkdir($directory, 0777, true); } $directory = $directory . '/'; } // create file $file = fopen(normalizePath($directory . $filename . '.md'), 'w'); fwrite($file, $text); fclose($file); $count++; } // Rename and move files with the same name as directories if (!empty($directory_list) && !empty($arguments['indexes'])) { $directory_list = array_keys($directory_list); foreach ($directory_list as $directory_name) { if (file_exists($output_path . $directory_name . '.md')) { rename($output_path . $directory_name . '.md', $output_path . $directory_name . '/index.md'); } } } if ($count > 0) { echo "{$count} files converted" . PHP_EOL . PHP_EOL;
/** * Gets composer json information for this package. * * @param bool $full Whether to get full composer schema or not. Defaults to * false, only defined keys in JSON file will be fetched * @return array Package's "composer.json" file as an array, an empty array if * corrupt or not found */ public function composer($full = false) { $cacheKey = "composer({$this->_packageName}, {$full})"; if ($cache = static::cache($cacheKey)) { return $cache; } $jsonPath = normalizePath($this->path() . '/composer.json'); if (!is_readable($jsonPath)) { return []; } $json = json_decode(file_get_contents($jsonPath), true); if (empty($json)) { return []; } if ($full) { $json = Hash::merge(JsonSchema::$schema, $json); } return static::cache($cacheKey, $json); }
/** * @return relative URL path to Root URL with slash included if needed * It is calculated based on location of file relative to root_dir * If called not from a file within aMember root, root_surl will be * returned */ function smarty_function_root_url($params, &$smarty) { $rd = ROOT_DIR; $fn = normalizePath(dirname(array_shift(get_included_files()))); // filename of the script if (($c = strpos($fn, $rd)) === FALSE) { return amConfig('root_surl'); } $fn = substr($fn, $c + strlen($rd) + 1); if ($fn == '') { return ''; } $fnn = ''; foreach (explode('/', $fn) as $f) { $fnn .= '../'; } return $fnn; }
public function init_module($module = 'CI_core') { if ($module === 'CI_core') { $config = $this->_core_config; $config['migration_path'] == '' and $config['migration_path'] = APPPATH . 'migrations/'; } else { list($path, $file) = Modules::find('migration', $module, 'config/'); if ($path === FALSE) { return FALSE; } if (!($config = Modules::load_file($file, $path, 'config'))) { return FALSE; } !$config['migration_path'] and $config['migration_path'] = '../migrations'; $config['migration_path'] = normalizePath($path . $config['migration_path']); } foreach ($config as $key => $val) { $this->{'_' . $key} = $val; } if ($this->_migration_enabled !== TRUE) { return FALSE; } $this->_migration_path = rtrim($this->_migration_path, '/') . '/'; if (!file_exists($this->_migration_path)) { return FALSE; } $this->_current_module = $module; return TRUE; }
/** * {@inheritDoc} * * It will look for plugin's version in the following places: * * - Plugin's "composer.json" file. * - Plugin's "VERSION.txt" file (or any file matching "/version?(\.\w+)/i"). * - Composer's "installed.json" file. * * If not found `dev-master` is returned by default. If plugin is not registered * on QuickAppsCMS (not installed) an empty string will be returned instead. * * @return string Plugin's version, for instance `1.2.x-dev` */ public function version() { if (parent::version() !== null) { return parent::version(); } if (!Plugin::exists($this->name())) { $this->_version = ''; return $this->_version; } // from composer.json if (!empty($this->composer['version'])) { $this->_version = $this->composer['version']; return $this->_version; } // from version.txt $files = glob($this->path . '/*', GLOB_NOSORT); foreach ($files as $file) { $fileName = basename(strtolower($file)); if (preg_match('/version?(\\.\\w+)/i', $fileName)) { $versionFile = file($file); $version = trim(array_pop($versionFile)); $this->_version = $version; return $this->_version; } } // from installed.json $installedJson = normalizePath(VENDOR_INCLUDE_PATH . "composer/installed.json"); if (is_readable($installedJson)) { $json = (array) json_decode(file_get_contents($installedJson), true); foreach ($json as $pkg) { if (isset($pkg['version']) && strtolower($pkg['name']) === strtolower($this->_packageName)) { $this->_version = $pkg['version']; return $this->_version; } } } $this->_version = 'dev-master'; return $this->_version; }
/** * Export entire database to PHP fixtures. * * By default, all generated PHP files will be placed in `/tmp/fixture/` * directory, this can be changed using the `--destination` argument. * * @return bool */ public function main() { $options = (array) $this->params; $destination = normalizePath("{$options['destination']}/"); if (is_string($options['tables'])) { $options['tables'] = explode(',', $options['tables']); } if (is_string($options['no-data'])) { $options['no-data'] = explode(',', $options['no-data']); } if (file_exists($destination)) { $dst = new Folder($destination); $dst->delete(); $this->out(__d('system', 'Removing existing directory: {0}', $destination), 1, Shell::VERBOSE); } else { new Folder($destination, true); $this->out(__d('system', 'Creating directory: {0}', $destination), 1, Shell::VERBOSE); } $db = ConnectionManager::get('default'); $db->connect(); $schemaCollection = $db->schemaCollection(); $tables = $schemaCollection->listTables(); foreach ($tables as $table) { if (!empty($options['tables']) && !in_array($table, $options['tables'])) { $this->out(__d('system', 'Table "{0}" skipped', $table), 1, Shell::VERBOSE); continue; } $Table = TableRegistry::get($table); $Table->behaviors()->reset(); $fields = ['_constraints' => [], '_indexes' => [], '_options' => (array) $Table->schema()->options()]; $columns = $Table->schema()->columns(); $records = []; $primaryKeys = []; foreach ($Table->schema()->indexes() as $indexName) { $index = $Table->schema()->index($indexName); if (!empty($index['columns'])) { $fields['_indexes']["{$table}_{$indexName}_index"] = $index; } } foreach ($columns as $column) { $fields[$column] = $Table->schema()->column($column); } foreach ($Table->schema()->constraints() as $constraint) { $constraintName = in_array($constraint, $columns) ? Inflector::underscore("{$table}_{$constraint}") : $constraint; $fields['_constraints'][$constraintName] = $Table->schema()->constraint($constraint); if (isset($fields['_constraints']['primary']['columns'])) { $primaryKeys = $fields['_constraints']['primary']['columns']; } } foreach ($fields as $column => $info) { if (isset($info['length']) && in_array($column, $primaryKeys) && isset($info['autoIncrement']) && $info['autoIncrement'] === true) { unset($fields[$column]['length']); } } // FIX: We need RAW data for time instead of Time Objects $originalTypes = []; foreach ($Table->schema()->columns() as $column) { $type = $Table->schema()->columnType($column); $originalTypes[$column] = $type; if (in_array($type, ['date', 'datetime', 'time'])) { $Table->schema()->columnType($column, 'string'); } } if ($options['mode'] === 'full') { foreach ($Table->find('all') as $row) { $row = $row->toArray(); if ($this->params['no-id'] && isset($row['id'])) { unset($row['id']); } $records[] = $row; } } $className = Inflector::camelize($table) . 'Fixture'; if ($options['fixture'] && in_array($className, ['AcosFixture', 'UsersFixture'])) { $records = []; } // undo changes made by "FIX" foreach ($originalTypes as $column => $type) { $fields[$column]['type'] = $type; } if (empty($fields['_indexes'])) { unset($fields['_indexes']); } $fields = $this->_arrayToString($fields); $records = in_array($table, $options['no-data']) ? '[]' : $this->_arrayToString($records); $fixture = $this->_classFileHeader($className); $fixture .= "{\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table name.\n"; $fixture .= " *\n"; $fixture .= " * @var string\n"; $fixture .= " */\n"; $fixture .= " public \$table = '{$table}';\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table columns.\n"; $fixture .= " *\n"; $fixture .= " * @var array\n"; $fixture .= " */\n"; $fixture .= " public \$fields = {$fields};\n"; $fixture .= "\n"; $fixture .= " /**\n"; $fixture .= " * Table records.\n"; $fixture .= " *\n"; $fixture .= " * @var array\n"; $fixture .= " */\n"; $fixture .= " public \$records = {$records};\n"; $fixture .= "}\n"; $file = new File(normalizePath("{$destination}/{$className}.php"), true); $file->write($fixture, 'w', true); $this->out(__d('system', 'Table "{0}" exported!', $table), 1, Shell::VERBOSE); } $this->out(__d('system', 'Database exported to: {0}', $destination)); return true; }
/** * Creates a temporary directory. * * @param $dir * @param string $prefix * @param int $mode * * @return string */ function tempdir($dir, $prefix = '', $mode = 0700) { if (substr($dir, -1) != '/') { $dir .= '/'; } do { $path = $dir . $prefix . mt_rand(0, 9999999); } while (!mkdir($path, $mode)); return normalizePath($path); }
function defineMetaIAHWrite() { global $lang; $sucess = false; $xml = normalizePath("xml/" . $lang . "/bvs.xml"); $xsl = normalizePath("xsl/metaiah/define-metaiah.xsl", "SITE_PATH"); $define = normalizePath("xml/" . $lang . "/metaiah.xml"); //print "\n xsl=" . $xsl . " ini=" . $ini . "<br>"; $text = processTransformation($xml, $xsl); $text = str_replace("encoding=\"UTF-8\"", "encoding=\"ISO-8859-1\"", $text); if ($text == "") { print "warning:transformation error generated empty content"; } else { if (!putDoc($define, $text)) { print "putDoc error: " . $define . "<br/>\n"; } else { $sucess = true; } } return $sucess; }
function render($file, $data) { include normalizePath($file); //$data will be available to view }
/** * {@inheritDoc} * * - extra: Holds a list (array) of files and their in formation (mime-icon, * file name, etc). * * - value: Holds a text containing all file names separated by space. */ public function beforeSave(Field $field, $post) { // FIX Removes the "dummy" input from extra if exists, the "dummy" input is // used to force Field Handler to work when empty POST information is sent $extra = []; foreach ((array) $field->extra as $k => $v) { if (is_integer($k)) { $extra[] = $v; } } $field->set('extra', $extra); $files = (array) $post; if (!empty($files)) { $value = []; foreach ($files as $k => $file) { if (!is_integer($k)) { unset($files[$k]); continue; } else { $file = array_merge(['mime_icon' => '', 'file_name' => '', 'file_size' => '', 'description' => ''], (array) $file); } $value[] = trim("{$file['file_name']} {$file['description']}"); } $field->set('value', implode(' ', $value)); $field->set('extra', $files); } if ($field->metadata->value_id) { $newFileNames = Hash::extract($files, '{n}.file_name'); try { $prevFiles = (array) TableRegistry::get('Eav.EavValues')->get($field->metadata->value_id)->extra; } catch (\Exception $ex) { $prevFiles = []; } foreach ($prevFiles as $f) { if (!in_array($f['file_name'], $newFileNames)) { $file = normalizePath(WWW_ROOT . "/files/{$field->metadata->settings['upload_folder']}/{$f['file_name']}", DS); $file = new File($file); $file->delete(); } } } return true; }
/** * This method should never be used unless you know what are you doing. * * Populates the "acos" DB with information of every installed plugin, or * for the given plugin. It will automatically extracts plugin's controllers * and actions for creating a tree structure as follow: * * - PluginName * - Admin * - PrivateController * - index * - some_action * - ControllerName * - index * - another_action * * After tree is created you should be able to change permissions using * User's permissions section in backend. * * @param string $for Optional, build ACOs for the given plugin, or all plugins * if not given * @param bool $sync Whether to sync the tree or not. When syncing all invalid * ACO entries will be removed from the tree, also new ones will be added. When * syn is set to false only new ACO entries will be added, any invalid entry * will remain in the tree. Defaults to false * @return bool True on success, false otherwise */ public static function buildAcos($for = null, $sync = false) { if (function_exists('ini_set')) { ini_set('max_execution_time', 300); } elseif (function_exists('set_time_limit')) { set_time_limit(300); } if ($for === null) { $plugins = plugin()->toArray(); } else { try { $plugins = [plugin($for)]; } catch (\Exception $e) { return false; } } $added = []; foreach ($plugins as $plugin) { if (!Plugin::exists($plugin->name)) { continue; } $aco = new AcoManager($plugin->name); $controllerDir = normalizePath("{$plugin->path}/src/Controller/"); $folder = new Folder($controllerDir); $controllers = $folder->findRecursive('.*Controller\\.php'); foreach ($controllers as $controller) { $controller = str_replace([$controllerDir, '.php'], '', $controller); $className = $plugin->name . '\\' . 'Controller\\' . str_replace(DS, '\\', $controller); $methods = static::_controllerMethods($className); if (!empty($methods)) { $path = explode('Controller\\', $className)[1]; $path = str_replace_last('Controller', '', $path); $path = str_replace('\\', '/', $path); foreach ($methods as $method) { if ($aco->add("{$path}/{$method}")) { $added[] = "{$plugin->name}/{$path}/{$method}"; } } } } } if ($sync && isset($aco)) { $aco->Acos->recover(); $existingPaths = static::paths($for); foreach ($existingPaths as $exists) { if (!in_array($exists, $added)) { $aco->remove($exists); } } $validLeafs = $aco->Acos->find()->select(['id'])->where(['id NOT IN' => $aco->Acos->find()->select(['parent_id'])->where(['parent_id IS NOT' => null])]); $aco->Acos->Permissions->deleteAll(['aco_id NOT IN' => $validLeafs]); } return true; }
function tagInclude($Item) { $src = $this->attr("src"); $res = 0; $did = $this->attr("data-id"); $dad = $this->attr("data-add"); $header = $this->attr("data-header"); if ($header > "") { $Item["header"] = $header; } $footer = $this->attr("data-footer"); if ($footer > "") { $Item["footer"] = $footer; } $vars = $this->attr("vars"); if ($vars > "") { $Item = attrAddData($vars, $Item); } $json = $this->attr("json"); if ($json > "") { $Item = json_decode($json, true); } $dfs = $this->attr("data-formsave"); $class = $this->attr("data-class"); if ($src == "comments") { $src = "/engine/forms/comments/comments_widget.php"; $this->attr("data-role-hide", "true"); } if ($src == "modal") { $src = "/engine/forms/form_comModal.php"; $this->attr("data-role-hide", "true"); } if ($src == "imgviewer") { $src = "/engine/js/imgviewer.php"; $this->attr("data-role-hide", "true"); } if ($src == "uploader") { $src = "/engine/js/uploader.php"; $this->attr("data-role-hide", "true"); } if ($src == "editor") { $src = "/engine/js/editor.php"; $this->attr("data-role-hide", "true"); } $vars = $this->attr("vars"); if ($vars > "") { $Item = attrAddData($vars, $Item); } if ($src == "") { $src = $this->html(); $this_content = ki::fromString($src); } else { $tplpath = explode("/", $src); $tplpath = array_slice($tplpath, 0, -1); $tplpath = implode("/", $tplpath) . "/"; if (!isset($_SESSION["tplpath"]) or $_SESSION["tplpath"] == "") { $_SESSION["tplpath"] = normalizePath($tplpath); } $src = contentSetValuesStr($src, $Item); $file = $_SESSION["prj_path"] . $src; if (is_file($_SERVER["DOCUMENT_ROOT"] . $file)) { $src = $_SERVER["DOCUMENT_ROOT"] . $file; } else { if (substr($src, 0, 7) !== "http://") { if (substr($src, 0, 1) != "/") { $src = "/" . $src; } $src = "http://" . $_SERVER['HTTP_HOST'] . $src; } } $this_content = ki::fromFile($src); } if ($did > "") { $this_content->find(":first")->attr("id", $did); } if ($dad == "false") { $this_content->find("[data-formsave]")->attr("data-add", $dad); } if ($dfs > "") { $this_content->find("[data-formsave]")->attr("data-formsave", $dfs); } if ($dfs == "false") { $this_content->find("[data-formsave]")->remove(); } if ($class > "") { $this_content->find(":first")->addClass($class); } if (count($this->find("include")) > 0) { $this->append("<div id='___include___' style='display:none;'>{$this_content}</div>"); foreach ($this->find("include") as $inc) { $attr = array("html", "outer", "htmlOuter", "outerHtml", "innerHtml", "htmlInner", "text", "value"); foreach ($attr as $key => $attribute) { $find = $inc->attr($attribute); if ($attribute == "outer" or $attribute == "htmlOuter") { $attribute = "outerHtml"; } if ($attribute == "html" or $attribute == "innerHtml" or $attribute == "htmlInner") { $attribute = "html"; } if ($find > "") { foreach ($this->find("#___include___")->find($find) as $text) { $inc->after($text->{$attribute}()); } } } unset($attribute); $inc->remove(); } unset($inc); $this->find("#___include___")->remove(); } else { $this->append($this_content->outerHtml()); } $this->contentSetData($Item); }
/** * Add a New Box To The Collection * * @http_method POST * @resource box/ * * @param string $name query * @param string $os query * @param string $ip query * @param string $port query * @param string $login query * @param string $password query * @param optional string $userPath * @param optional string $steamPath * @param optional string $notes * * @return application/json * * @author Nikita Rousseau */ function postBox($name, $os, $ip, $port, $login, $password, $userPath = '', $steamPath = '', $notes = '') { $args = array('name' => $name, 'os' => $os, 'ip' => $ip, 'port' => $port, 'login' => $login, 'password' => $password, 'userPath' => $userPath, 'steamPath' => $steamPath, 'notes' => $notes); $errors = array(); // array to hold validation errors $data = array(); // array to pass back data $dbh = Core_DBH::getDBH(); // Get Database Handle // validate the variables ====================================================== $v = new Valitron\Validator($args); $rules = ['required' => [['name'], ['os'], ['ip'], ['port'], ['login'], ['password']], 'regex' => [['name', "/^([-a-z0-9_ -])+\$/i"]], 'integer' => [['os'], ['port']], 'ip' => [['ip']], 'alphaNum' => [['login']]]; $labels = array('name' => T_('Remote Machine Name'), 'os' => T_('Operating System'), 'ip' => T_('IP Address'), 'port' => T_('Port'), 'login' => T_('Login'), 'password' => T_('Password')); $v->rules($rules); $v->labels($labels); $v->validate(); $errors = $v->errors(); // validate the variables phase 2 ============================================== if (empty($errors)) { // Verify OS ID try { $sth = $dbh->prepare("\n\t\t\t\t\tSELECT operating_system\n\t\t\t\t\tFROM " . DB_PREFIX . "os\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tos_id = :os_id\n\t\t\t\t\t;"); $sth->bindParam(':os_id', $args['os']); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } if (empty($result[0])) { $errors['os'] = 'Bad Identifier'; } // Verify Communication $socket = @fsockopen($args['ip'], $args['port'], $errno, $errstr, 3); if ($socket === FALSE) { $errors['com'] = "Unable to connect to " . $args['ip'] . " on port " . $args['port'] . ". " . utf8_encode($errstr) . " ( {$errno} )"; unset($socket); } else { unset($socket); $ssh = new Net_SSH2($args['ip'], $args['port']); if (!$ssh->login($args['login'], $args['password'])) { $errors['com'] = 'Login failed'; } else { // Verify Remote Paths if (!empty($args['userPath'])) { if (boolval(trim($ssh->exec('test -d ' . escapeshellcmd($args['userPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['remoteUserHome'] = 'Invalid path. Must be an absolute or full path'; } } if (!empty($args['steamPath'])) { if (boolval(trim($ssh->exec('test -f ' . escapeshellcmd($args['steamPath']) . " && echo '1' || echo '0'"))) === FALSE) { $errors['steamcmd'] = 'SteamCMD not found. Must be an absolute or full path'; } } } $ssh->disconnect(); } } // Apply ======================================================================= if (empty($errors)) { // // Database update // // Vars Init if (empty($args['userPath'])) { $home = "~"; $args['userPath'] = $home; } else { $home = escapeshellcmd(normalizePath($args['userPath'])); $args['userPath'] = $home; } $config = parse_ini_file(CONF_SECRET_INI); // BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tos_id \t\t\t= :os,\n\t\t\t\t\t\tname \t\t\t= :name,\n\t\t\t\t\t\tsteam_lib_path \t= :steamcmd,\n\t\t\t\t\t\tnotes \t\t\t= :notes\n\t\t\t\t\t;"); $sth->bindParam(':os', $args['os']); $sth->bindParam(':name', $args['name']); $sth->bindParam(':steamcmd', $args['steamPath']); $sth->bindParam(':notes', $args['notes']); $sth->execute(); $box_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // IP try { $sth = $dbh->prepare("\n\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_ip\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_id = :box_id,\n\t\t\t\t\t\tip = :ip,\n\t\t\t\t\t\tis_default = 1\n\t\t\t\t\t;"); $sth->bindParam(':box_id', $box_id); $sth->bindParam(':ip', $args['ip']); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } // CREDENTIALS // Phase 1 // Connect to the remote host // Try to append our public key to authorized_keys $ssh = new Net_SSH2($args['ip'], $args['port']); $ssh->login($args['login'], $args['password']); $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); // Check if the public key already exists if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // Otherwise, append it $ssh->exec("echo '" . file_get_contents(RSA_PUBLIC_KEY_FILE) . "' >> " . $home . "/.ssh/authorized_keys"); } // Phase 2 // Verify that the public key is allowed on the remote host $isUsingSSHPubKey = TRUE; // By default, we use the SSH authentication keys method $remote_keys = $ssh->exec('cat ' . $home . '/.ssh/authorized_keys'); $ssh->disconnect(); if (strpos($remote_keys, file_get_contents(RSA_PUBLIC_KEY_FILE)) === FALSE) { // authorized_keys is not writable // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } else { // Phase 3 // Try to connect with our private key on the remote host $ssh = new Net_SSH2($args['ip'], $args['port']); $key = new Crypt_RSA(); $key->loadKey(file_get_contents(RSA_PRIVATE_KEY_FILE)); if (!$ssh->login($args['login'], $key)) { // Authentication failed // Use compatibility mode // Store the password in DB $isUsingSSHPubKey = FALSE; } $ssh->disconnect(); } // SSH CREDENTIALS $cipher = new Crypt_AES(CRYPT_AES_MODE_ECB); $cipher->setKeyLength(256); $cipher->setKey($config['APP_SSH_KEY']); if ($isUsingSSHPubKey) { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :com_port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $sth->bindParam(':login', $login); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } else { try { $sth = $dbh->prepare("\n\t\t\t\t\t\tINSERT INTO " . DB_PREFIX . "box_credential\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\tlogin = :login,\n\t\t\t\t\t\t\tpassword = :password,\n\t\t\t\t\t\t\tremote_user_home = :home,\n\t\t\t\t\t\t\tcom_protocol = 'ssh2',\n\t\t\t\t\t\t\tcom_port = :port\n\t\t\t\t\t\t;"); $login = $cipher->encrypt($args['login']); $password = $cipher->encrypt($args['password']); $sth->bindParam(':login', $login); $sth->bindParam(':password', $password); $sth->bindParam(':home', $args['userPath']); $sth->bindParam(':com_port', $args['port']); $sth->execute(); $credential_id = $dbh->lastInsertId(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // UPDATE BOX try { $sth = $dbh->prepare("\n\t\t\t\t\tUPDATE " . DB_PREFIX . "box\n\t\t\t\t\tSET\n\t\t\t\t\t\tbox_credential_id = :box_credential_id\n\t\t\t\t\tWHERE box_id = :box_id\n\t\t\t\t\t;"); $sth->bindParam(':box_credential_id', $credential_id); $sth->bindParam(':box_id', $box_id); $sth->execute(); } catch (PDOException $e) { echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine(); die; } } // return a response and log =================================================== $logger = self::getLogger(); $data['errors'] = $errors; if (!empty($data['errors'])) { $data['success'] = false; $logger->info('Failed to add box.'); } else { $data['success'] = true; $logger->info('Box added.'); } return array('response' => 'application/json', 'data' => json_encode($data)); }
/** * Tries to get package that represents a third party library. * * - Package must exists on `VENDOR_PATH/vendor-name/package-name/`. * - Its composer.json file must exists as well. * - Package must be registered on Composer's "installed.json" file. * * @param string $package Full package name * @return bool|\CMS\Core\Package\ThirdPartyPackage */ protected static function _getThirdParty($package) { list($vendor, $packageName) = packageSplit($package); $packageJson = normalizePath(VENDOR_INCLUDE_PATH . "/{$vendor}/{$packageName}/composer.json"); if (is_readable($packageJson)) { $installedJson = normalizePath(VENDOR_INCLUDE_PATH . "composer/installed.json"); if (is_readable($installedJson)) { $json = (array) json_decode(file_get_contents($installedJson), true); foreach ($json as $pkg) { if (strtolower($pkg['name']) === strtolower($package)) { return new ThirdPartyPackage($package, dirname($packageJson), $pkg['version']); } } } } return false; }
if (isset($xslSave)) { $xslSave = "../" . $checked['xslSave']; $sucessWriteXml = xmlWrite($xmlContent, $xslSave, $checked['xmlSave']); if ($sucessWriteXml != '' && $checked['page'] != 'users') { // generate html htmlWrite($sucessWriteXml); // generate ini iniWrite($sucessWriteXml); if ($checked['page'] == 'collection' || $checked['page'] == 'topic') { // generate metaiah define xml defineMetaIAHWrite(); } } if (isset($xmlT)) { if ($xmlT == "saved") { $xmlContent = BVSDocXml("root", $checked['xmlSave']); } } } $xslTransform = normalizePath($checked['xsl'], "SITE_PATH"); if ($debug == "XSL") { die($xslContent); } if (isset($xsl)) { print processTransformation($xmlContent, $xslTransform); } else { print $xmlContent; } ?>
/** * Extracts the current ZIP package. * * @param string $file Full path to the ZIP package * @return bool True on success */ protected function _unzip($file) { include_once Plugin::classPath('Installer') . 'Lib/pclzip.lib.php'; $File = new File($file); $to = normalizePath($File->folder()->pwd() . '/' . $File->name() . '_unzip/'); if (is_readable($to)) { $folder = new Folder($to); $folder->delete(); } else { $folder = new Folder($to, true); } $PclZip = new \PclZip($file); $PclZip->delete(PCLZIP_OPT_BY_EREG, '/__MACOSX/'); $PclZip->delete(PCLZIP_OPT_BY_EREG, '/\\.DS_Store$/'); if ($PclZip->extract(PCLZIP_OPT_PATH, $to)) { list($directories, $files) = $folder->read(false, false, true); if (count($directories) === 1 && empty($files)) { $container = new Folder($directories[0]); $container->move(['to' => $to]); } $this->_workingDir = $to; return true; } $this->err(__d('installer', 'Unzip error: {0}', [$PclZip->errorInfo(true)])); return false; }
static function getImageDescription($path) { $imageName = pathinfoFilename($path); $imageDirectory = normalizePath(pathinfoDirname($path)); $possibleDescriptionPath = $imageDirectory . $imageName . '.txt'; if (is_file($possibleDescriptionPath)) { return file_get_contents($possibleDescriptionPath); } return null; }
/** * Scan plugin directories and returns plugin names and their paths within file * system. We consider "plugin name" as the name of the container directory. * * Example output: * * ```php * [ * 'Users' => '/full/path/plugins/Users/', * 'ThemeManager' => '/full/path/plugins/ThemeManager/', * ... * 'MySuperPlugin' => '/full/path/plugins/MySuperPlugin/', * 'DarkGreenTheme' => '/full/path/plugins/DarkGreenTheme/', * ] * ``` * * If $ignoreThemes is set to true `DarkGreenTheme` will not be part of the * result. * * NOTE: All paths includes trailing slash. * * @param bool $ignoreThemes Whether include themes as well or not * @return array Associative array as `PluginName` => `/full/path/to/PluginName` */ public static function scan($ignoreThemes = false) { $cacheKey = "scan({$ignoreThemes})"; $cache = static::cache($cacheKey); if (!$cache) { $cache = []; $paths = App::path('Plugin'); $Folder = new Folder(); $Folder->sort = true; foreach ($paths as $path) { $Folder->cd($path); foreach ($Folder->read(true, true, true)[0] as $dir) { $name = basename($dir); $cache[$name] = normalizePath("{$dir}/"); } } // look for Cake plugins installed using Composer if (file_exists(VENDOR_INCLUDE_PATH . 'cakephp-plugins.php')) { $cakePlugins = (array) (include VENDOR_INCLUDE_PATH . 'cakephp-plugins.php'); if (!empty($cakePlugins['plugins'])) { $cache = Hash::merge($cakePlugins['plugins'], $cache); } } // filter, remove hidden folders and others foreach ($cache as $name => $path) { if (strpos($name, '.') === 0) { unset($cache[$name]); } elseif ($name == 'CMS') { unset($cache[$name]); } elseif ($ignoreThemes && str_ends_with($name, 'Theme')) { unset($cache[$name]); } } $cache = static::cache($cacheKey, $cache); } return $cache; }
/** * Delete image's thumbnails if exists. * * @param string $imagePath Full path to original image file * @return void */ public static function deleteThumbnails($imagePath) { $imagePath = normalizePath("{$imagePath}/"); $fileName = basename($imagePath); $tmbPath = normalizePath(dirname($imagePath) . '/.tmb/'); $folder = new Folder($tmbPath); $pattern = preg_quote(static::removeExt($fileName)); foreach ($folder->find(".*{$pattern}.*") as $tn) { $tn = new File($tmbPath . $tn); $tn->delete(); } }