/** * gets a file pointer from a specified file * @param string $filename * @param array $options * @return mixed $res file pointer | true | false */ public static function getFPFromFile($filename, $options = array()) { if (isset($options)) { self::$options = $options; } if (!file_exists($filename)) { self::$errors[] = lang::translate('File does not exists') . ' : ' . $options['filename']; return false; } if (isset($options['maxsize'])) { $size = filesize($options['filename']); // check the file is less than the maximum file size if ($size > $options['maxsize']) { $error = lang::translate('File is too large.'); $error .= lang::translate('Max size is ') . bytes::bytesToGreek($options['maxsize']); error_log($error); self::$errors[] = $error; return false; } } // check for right content if (isset($options['allow_mime'])) { $type = file::getMime($options['filename']); if (!in_array($type, $options['allow_mime'])) { self::$errors[] = lang::translate('This Content type is not allowed') . MENU_SUB_SEPARATOR_SEC . $type; return false; } } $fp = fopen($filename, 'rb'); return $fp; }
/** * Sets a controller and a action */ private function setControllerAction() { // Parse url. 2 cases: // a) Default controller // b) Module controller // Get all modules $mod_path = conf::pathBase() . "/" . $this->modules; $mods = file::getDirsGlob($mod_path, array('basename' => true)); $base = direct::fragment(0); if (!in_array($base, $mods)) { // Could not find a controller / module $this->controller = $this->default; $action = direct::fragment(0); if ($action) { $this->action = $action; } } else { // Found a controller / module $this->controller = $base; $action = direct::fragment(1); if ($action) { $this->action = $action; } } }
public static function assets($options = null) { $path = conf::pathBase() . "/htdocs/files/default/cached_assets"; if (file_exists($path)) { file::rrmdir($path); } return 1; }
/** * wrapper function for loading a profile */ function load_profile($options) { $pro = new profile(); $profiles = file::getFileList('profiles', array('dir_only' => true)); if (!in_array($options['profile'], $profiles)) { common::abort('No such profile'); } if (isset($options['config_only'])) { $pro->loadConfigIni($options['profile']); } else { $pro->loadProfile($options['profile']); } }
function multi_shared_exec_command($options = null) { $path = conf::pathBase() . "/config/multi/*"; if (!isset($options['command'])) { common::abort('Specify a command'); return 1; } $command = $options['command']; $dirs = file::getDirsGlob($path, array('basename' => 1)); foreach ($dirs as $domain) { $exec_command = "./coscli.sh --domain={$domain} {$command}"; common::echoMessage("Executing command: {$exec_command}"); passthru($exec_command, $return_var); } }
/** * executes a shell command on all coscms systems install in parent dir (../) from * current dir * @param string $command * @return int $ret */ function multi_exec_shell_command($options = array()) { $path = conf::pathBase() . "/../"; if (!isset($options['command'])) { common::abort('Specify a command'); return 1; } $command = $options['command']; $dirs = file::getDirsGlob($path, array('basename' => 1)); foreach ($dirs as $domain) { if (!file_exists("../{$domain}/config/config.ini")) { continue; } $exec_command = "cd ../{$domain} && {$command}"; multi_passthru($exec_command); } }
/** * function for checking if your are denying people * from e.g. admin areas of your module. */ function dev_test_access($options = null) { $files = file::getFileListRecursive(conf::pathModules(), "*module.php"); foreach ($files as $val) { $class_path = "modules" . str_replace(conf::pathModules(), '', $val); $class_path = str_replace('.php', '', $class_path); $class = str_replace('/', "\\", $class_path); $ary = get_class_methods($class); if (!is_array($ary)) { continue; } $call_paths = dev_get_actions($ary, $class_path); foreach ($call_paths as $path) { $url = conf::getSchemeWithServerName() . "{$path}"; $curl = new mycurl($url); $curl->createCurl(); echo $curl->getHttpStatus(); common::echoMessage(" Status code recieved on: {$url}"); } } }
/** * Loads all base modules * Base modules are placed in vendor/diversen/simple-php-classes */ public static function loadBaseModules() { $command_path = __DIR__ . "/../shell"; $base_list = file::getFileList($command_path, array('search' => '.php')); foreach ($base_list as $val) { include_once $command_path . "/{$val}"; } }
/** * method for getting all templates located in conf::pathHtdocs()/template * used for settings current templates in profiles/profile/profile.inc file */ public function getTemplates() { $dir = conf::pathHtdocs() . "/templates"; $templates = file::getFileList($dir, array('dir_only' => true)); $ary = array(); foreach ($templates as $val) { $info = $this->getTemplateInfo($val); if (empty($info)) { continue; } $ary[] = $info; } return $ary; }
/** * returns a array of all templates found in template_dir * @return array $templates */ public static function getAllTemplates() { return file::getFileList(conf::pathHtdocs() . "/templates", array('dir_only' => true)); }
$path = ".."; include '../vendor/autoload.php'; } conf::setMainIni('base_path', $path); // Set real path $real = realpath($path); // PAth to current request $info = parse_url($_SERVER['REQUEST_URI']); // Does htdocs dir exists if (file_exists($real . "/htdocs")) { $real .= "/htdocs" . "/{$info['path']}"; } // Get full requst path if (file_exists($real) && $info['path'] != '/') { //echo $real; die; $mime = file::getMime($real); //die; if ($mime) { if ($mime == 'text/x-php') { return false; } http::cacheHeaders(); header("Content-Type: {$mime}"); readfile($real); } die; //return false; } else { $boot = new boot(); $boot->run(); return true;
/** * Get type of extension * @param type $url * @return type */ protected function getType($url) { $type = file::getExtension($url); return strtolower($type); }
/** * Checks broken media * @param type $url * @return boolean */ protected function checkMedia($url) { $type = file::getExtension($url); if ($type == 'mp4' && self::$type == 'mp4') { return false; } return $url; }
/** * Run the system */ public function run() { // Register an autoloader for loading modules from mopdules dir $m = new modules(); $m->autoloadRegister(); // define HTML constants common::defineConstants(); // define global constants - based on base path conf::defineCommon(); // set include paths conf::setIncludePath(); // load config file conf::load(); if (conf::getMainIni('debug')) { log::enableDebug(); } // set public file folder in file class file::$basePath = conf::getFullFilesPath(); // utf-8 ini_set('default_charset', 'UTF-8'); // load config/config.ini // check if there exists a shared ini file // shared ini is used if we want to enable settings between hosts // which share same code base. // e.g. when updating all sites, it is a good idea to set the following flag // site_update = 1 // this flag will send correct 503 headers, when we are updating our site. // if site is being updaing we send temporarily headers // and display an error message if (conf::getMainIni('site_update')) { http::temporarilyUnavailable(); } // set a unified server_name if not set in config file. $server_name = conf::getMainIni('server_name'); if (!$server_name) { conf::setMainIni('server_name', $_SERVER['SERVER_NAME']); } // redirect to uniform server name is set in config.ini // e.g. www.testsite.com => testsite.com $server_redirect = conf::getMainIni('server_redirect'); if (isset($server_redirect)) { http::redirectHeaders($server_redirect); } // redirect to https is set in config.ini // force anything into ssl mode $server_force_ssl = conf::getMainIni('server_force_ssl'); if (isset($server_force_ssl)) { http::sslHeaders(); } // catch all output ob_start(); // Create a db connection $db_conn = array('url' => conf::getMainIni('url'), 'username' => conf::getMainIni('username'), 'password' => conf::getMainIni('password'), 'db_init' => conf::getMainIni('db_init')); // Other options // db_dont_persist = 0 // dont_die = 0 // Set to one and the connection don't die because of // e.g. no database etc. This will return NO_DB_CONN as string //$url = conf::getMainIni('url'); connect::connect($db_conn); // init module loader. $ml = new moduleloader(); // initiate uri uri::getInstance(); // runlevel 1: merge db config $ml->runLevel(1); // select all db settings and merge them with ini file settings $db_Settings = []; if (moduleloader::moduleExists('settings')) { $db_settings = q::select('settings')->filter('id =', 1)->fetchSingle(); } // merge db settings with config/config.ini settings // db settings override ini file settings conf::$vars['coscms_main'] = array_merge(conf::$vars['coscms_main'], $db_settings); // run level 2: set locales $ml->runLevel(2); // set locales intl::setLocale(); // set default timezone intl::setTimezone(); // runlevel 3 - init session $ml->runLevel(3); // start session session::initSession(); // Se if user is logged in with SESSION if (!session::isUser()) { // If not logged in check system cookie // This will start the session, if an appropiate cookie exists session::checkSystemCookie(); } // Check account $res = session::checkAccount(); if (!$res) { // Redirect to main page if user is not allowed // With current SESSION or COOKIE http::locationHeader('/'); } // set account timezone if enabled - can only be done after session // as user needs to be logged in intl::setAccountTimezone(); // run level 4 - load language $ml->runLevel(4); // load all language files $l = new lang(); $base = conf::pathBase(); $htdocs = conf::pathHtdocs(); $l->setDirsInsideDir("{$base}/modules/"); $l->setDirsInsideDir("{$htdocs}/templates/"); $l->setSingleDir("{$base}/vendor/diversen/simple-php-classes"); $l->setSingleDir("{$base}/vendor/diversen/simple-pager"); $l->loadLanguage(conf::getMainIni('lang')); // runlevel 5 $ml->runLevel(5); // load routes if any dispatch::setDbRoutes(); // check db routes or load defaults $db_route = dispatch::getMatchRoutes(); if (!$db_route) { $ml->setModuleInfo(); $ml->initModule(); } else { dispatch::includeModule($db_route['method']); } // After module has been loaded. // You can e.g. override module ini settings $ml->runLevel(6); // Init layout. Sets template name // load correct CSS. St menus if any. Etc. $layout = new layout(); // we first load menus here so we can se what happened when we // init our module. In case of a 404 not found error we don't want // to load module menus $layout->loadMenus(); // init blocks $layout->initBlocks(); // if any matching route was found we check for a method or function if ($db_route) { $str = dispatch::call($db_route['method']); } else { // or we use default module parsing $str = $ml->getParsedModule(); } // set view vars $vars['content'] = $str; // run level 7 $ml->runLevel(7); // echo module content echo $str = \mainTemplate::view($vars); conf::$vars['final_output'] = ob_get_contents(); ob_end_clean(); // Last divine intervention // e.g. Dom or Tidy $ml->runLevel(8); echo conf::$vars['final_output']; }
protected function uploadImage($url) { // Array ( [name] => Angus_cattle_18.jpg [type] => image/jpeg [tmp_name] => /tmp/php5lPQZT [error] => 0 [size] => 52162 ) $ary = []; $name = file::getFilename($url) . "." . file::getExtension($url); $ary['name'] = $name; $ary['abstract'] = file::getFilename($url); $ary['type'] = file::getMime($url); $ary['tmp_name'] = $url; $ary['error'] = 0; $ary['size'] = 0; $i = new \modules\image\uploadBlob(); $res = $i->insertFileDirect($ary, $this->reference, $this->parentId, $this->userId); if ($res) { $id = q::lastInsertId(); $row = $i->getSingleFileInfo($id); return $i->getFullWebPath($row); } else { log::error("Could not upload image: {$name}"); return false; } }
protected function saveImage($url) { $id = direct::fragment(2, $url); $title = direct::fragment(3, $url); $path = "/images/{$id}/{$title}"; $save_path = conf::getFullFilesPath($path); $web_path = conf::getWebFilesPath($path); $image_url = conf::getSchemeWithServerName() . $url; $code = headers::getReturnCode($image_url); if ($code != 200) { log::error("Could not get file content (image). Got: {$code} " . $image_url); return ''; } else { $file = file_get_contents($image_url); } // make dir $dir = dirname($path); file::mkdir($dir); file_put_contents($save_path, $file); return $web_path; }
protected function saveMedia($url) { $type = file::getExtension($url); if ($type == 'mp4') { return $this->saveMp4($url); } else { return $this->saveImage($url); } }
/** * function for getting latest timestamp for dumps * * default to backup/sql but you can specify a dir. * * @param string $dir * @return int $timestamp */ function get_latest_db_dump($dir = null, $num_files = null) { if (!$dir) { $dir = conf::pathBase() . "/backup/sql"; } $list = file::getFileList($dir); $time_stamp = 0; foreach ($list as $val) { $file = explode('.', $val); if (is_numeric($file[0])) { if ($file[0] > $time_stamp) { $time_stamp = $file[0]; } } } return $time_stamp; }
/** * Updates a PHP string with extracted translation * Updating means that any changes to the values of * e.g. $LANG['My sentence'] will not be changed * @param string $dir * @return string $translation_str */ public function updateLangStrForPath($dir) { $file_list = file::getFileListRecursive($dir); asort($file_list); // compose a php file $translation_str = "<?php\n\n"; $translation_str .= "\$" . $this->translateAryName . " = array();\n"; // if lang file does not exists $lang_file = $this->getLanguageFileFromDir($dir); if (!file_exists($lang_file)) { return $this->createLangStrForPath($dir); } include $lang_file; $original_ary = ${$this->translateAryName}; if (empty($original_ary)) { return $this->createLangStrForPath($dir); } foreach ($file_list as $file) { if (!$this->isText($file)) { continue; } $file_str = file_get_contents($file); $strings = $this->search($file_str); // no strings we continue if (empty($strings)) { continue; } $translation_str .= "\n// Translation of file {$file}\n\n"; // and we add all strings foreach ($strings as $trans) { if (!isset($original_ary[$trans])) { // new value $translation_str .= $this->setCorrectQuotes($trans); } else { // keep old value $old_value = $original_ary[$trans]; $translation_str .= $this->setCorrectQuotes($trans, $old_value); } } } return $translation_str; }
/** * function for doing a prompt install from shell mode * is a wrapper around other shell functions. */ function prompt_install() { common::echoMessage('Pick a version to install:', 'y'); $tags = git::getTagsInstallLatest() . PHP_EOL; $tags .= "master"; common::echoMessage($tags); $tag = common::readSingleline("Enter tag (version) to use:"); common::execCommand("git checkout {$tag}"); // Which profile to install $profiles = file::getFileList('profiles', array('dir_only' => true)); if (count($profiles) == 1) { $profile = array_pop($profiles); } else { common::echoMessage("List of profiles: "); foreach ($profiles as $val) { common::echoMessage("\t" . $val); } // select profile and load it $profile = common::readSingleline('Enter profile, and hit return: '); } common::echoMessage("Loading the profile '{$profile}'", 'y'); load_profile(array('profile' => $profile, 'config_only' => true)); common::echoMessage("Main configuration (placed in config/config.ini) for '{$profile}' is loaded", 'y'); // Keep base path. Ortherwise we will lose it when loading profile $base_path = conf::pathBase(); // Load the default config.ini settings as a skeleton conf::$vars['coscms_main'] = conf::getIniFileArray($base_path . '/config/config.ini', true); // Reset base path conf::setMainIni('base_path', $base_path); conf::defineCommon(); common::echoMessage("Enter MySQL credentials", 'y'); // Get configuration info $host = common::readSingleline('Enter your MySQL host: '); $database = common::readSingleline('Enter database name: '); $username = common::readSingleline('Enter database user: '******'Enter database users password: '******'Enter server host name: '); common::echoMessage("Writing database connection info to main configuration"); // Assemble configuration info conf::$vars['coscms_main']['url'] = "mysql:dbname={$database};host={$host};charset=utf8"; conf::$vars['coscms_main']['username'] = $username; conf::$vars['coscms_main']['password'] = $password; conf::$vars['coscms_main']['server_name'] = $server_name; // Write it to ini file $content = conf::arrayToIniFile(conf::$vars['coscms_main'], false); $path = conf::pathBase() . "/config/config.ini"; file_put_contents($path, $content); common::echoMessage("Your can also always change the config/config.ini file manually"); $options = array(); $options['profile'] = $profile; if ($tag == 'master') { $options['master'] = true; } common::echoMessage("Will now clone and install all modules", 'y'); cos_install($options); common::echoMessage("Create a super user", 'y'); useradd_add(); $login = "******"; common::echoMessage("If there was no errors you will be able to login at {$login}"); common::echoMessage("Remember to change file permissions. This will require super user"); common::echoMessage("E.g. like this:"); common::echoMessage("sudo ./coscli.sh file --chmod-files"); }
protected function saveImage($url) { $id = direct::fragment(2, $url); $ext = file::getExtension($url); $title = md5(uniqid()) . ".{$ext}"; $i = new image(); $file = $i->getFile($id); if (empty($file)) { return ''; } $path = "/images/{$id}/{$title}"; $save_path = conf::getFullFilesPath($path); $web_path = conf::getWebFilesPath($path); $dir = dirname($path); file::mkdir($dir); file_put_contents($save_path, $file['file']); return $web_path; }
/** * Get a SQL file list from module, and action * @param string $module * @param string $action (up or down) * @return array $ary array with file list */ public function getSqlFileList($module, $action) { $sql_dir = conf::pathModules() . "/{$module}/mysql/{$action}"; $file_list = file::getFileList($sql_dir); if (is_array($file_list)) { return $file_list; } else { return array(); } }
/** * CLI command: function for getting latest timestamp from /backup/full dir * * @return int backup with most recent timestamp */ function backup_get_latest_backup($type = null) { if ($type == 'files') { $dir = conf::pathBase() . "/backup/files"; } else { $dir = conf::pathBase() . "/backup/full"; } $list = file::getFileList($dir); $time_stamp = 0; foreach ($list as $key => $val) { $file = explode('.', $val); if (is_numeric($file[0])) { if ($file[0] > $time_stamp) { $time_stamp = $file[0]; } } } return $time_stamp; }
$str = file_get_contents('tmp/.database.sql'); file_put_contents('.database.sql', $str); chmod('.database.sql', 0777); // And mount again Phar::mount('config/config.ini', '.config.ini'); Phar::mount('sqlite/database.sql', '.database.sql'); } if (php_sapi_name() == 'cli-server') { $info = parse_url($_SERVER['REQUEST_URI']); $file = $info['path']; if (file_exists("./{$info['path']}") && $info['path'] != '/') { $full = __DIR__ . "{$file}"; if (!file_exists($full) or is_dir($full)) { echo "Is dir. Or does not exists"; return false; } $mime = file::getMime($full); if ($mime) { if ($mime == 'text/x-php') { return false; } http::cacheHeaders(); header("Content-Type: {$mime}"); readfile($full); } } else { include "index.php"; } } __halt_compiler();
/** * Set 'inline' CSS. This will add CSS files from outside of public HTML * to be added to a template. * @param string $css file path of the css * @param int $order the loading order of css 0 is first > 0 is * later * @param array $options array ('no_cache' => 0) */ public static function setInlineCss($css, $order = null, $options = array()) { $str = file::getCachedFile($css); if (isset(self::$inlineCss[$order])) { self::setInlineCss($css, $order + 1); } else { self::$inlineCss[] = $str; } }
/** * method for checking allowed mime types * @param string $filename the filename to check * @return boolean $res */ public static function checkAllowedMime($file) { $type = file::getMime($file['tmp_name']); if (!in_array($type, self::$options['allow_mime'])) { $message = lang::translate('Mime type is not allowed. '); $message .= lang::translate('These mime types are allowed ') . MENU_SUB_SEPARATOR_SEC; $message .= self::getMimeAsString(self::$options['allow_mime']); self::$errors[] = $message; return false; } return true; }
/** * remove directory recursively * @param string $path */ public static function rrmdir($dir) { $fp = opendir($dir); if ($fp) { while ($f = readdir($fp)) { $file = $dir . "/" . $f; if ($f == "." || $f == "..") { continue; } else { if (is_dir($file) && !is_link($file)) { file::rrmdir($file); } else { unlink($file); } } } closedir($fp); rmdir($dir); } }