/** * build source package with more simple form of install. * @param array $options */ function cos_build_simple($options = null) { $dir = getcwd(); $name = basename($dir); if (file_exists("./build/{$name}")) { common::execCommand("sudo rm -rf ./build/{$name}*"); } common::execCommand("mkdir ./build/{$name}"); $htdocs = "cp -rf htdocs/* ./build/{$name}"; common::execCommand($htdocs); $domain = conf::getMainIni('domain'); if (!$domain) { $domain = 'default'; } $files_rm = "sudo rm -rf ./build/{$name}/files/{$domain}/*"; common::execCommand($files_rm); $config = "mkdir ./build/{$name}/config"; common::execCommand($config); $tmp_dir = "mkdir ./build/{$name}/tmp"; common::execCommand($tmp_dir); $profiles = "cp -rf profiles ./build/{$name}"; common::execCommand($profiles); $sql_scripts = "cp -rf scripts ./build/{$name}"; common::execCommand($sql_scripts); $cli = "cp -rf coscli.sh ./build/{$name}"; common::execCommand($cli); $composer = "cp -rf composer.json ./build/{$name}"; common::execCommand($composer); // reset database password $ary = conf::getIniFileArray("./config/config.ini"); $profile = new profile(); $ary = $profile->iniArrayPrepare($ary); // clean ini settings for secrets $ini_settings = conf::arrayToIniFile($ary); // add ini dist file file_put_contents("./build/{$name}/config/config.ini-dist", $ini_settings); $index = "cp -rf htdocs/index.php ./build/{$name}/index.php"; common::execCommand($index); $phar_cli = "cp -rf phar-cli.php ./build/{$name}/"; common::execCommand($phar_cli); $phar_web = "cp -rf phar-web.php ./build/{$name}/"; common::execCommand($phar_web); $module_dir = conf::pathModules(); $modules = "cp -rf {$module_dir} ./build/{$name}"; common::execCommand($modules); $vendor = "cp -rf vendor ./build/{$name}"; common::execCommand($vendor); $rm_git = "rm `find ./build/{$name} -name '.git'` -rf"; common::execCommand($rm_git); $rm_ignore = "rm `find ./build/{$name} -name '.gitignore'` -rf"; common::execCommand($rm_ignore); $rm_doc = "rm -rf ./build/vendor/doc"; common::execCommand($rm_doc); $output = array(); exec('git tag -l', $output); $version = array_pop($output); $command = "cd ./build && tar -Pczf {$name}-{$version}.tar.gz {$name} "; common::execCommand($command); }
/** * highlight a text using geshi. * in your text you will need, e.g. for PHP, * <code>[hl:php]<?php echo "hello world";?>[/hl:php]</code> * @param string $text string to filter. * @return string $text the filtered text */ public function filter($article) { if (conf::getMainIni('filters_allow_files')) { $article = self::filterGeshiFile($article); } $article = self::filterGeshiInline($article); return $article; }
/** * set default timezone (date_default_timezone) */ public static function setTimezone() { // if no user timezone if (!conf::getMainIni('date_default_timezone')) { conf::setMainIni('date_default_timezone', 'Europe/Copenhagen'); } date_default_timezone_set(conf::getMainIni('date_default_timezone')); }
/** * set SSL for mysql */ public static function setSsl() { $attr = conf::getMainIni('mysql_attr'); if (isset($attr['mysql_attr'])) { self::$dbh->setAttribute(PDO::MYSQL_ATTR_SSL_KEY, $attr['ssl_key']); self::$dbh->setAttribute(PDO::MYSQL_ATTR_SSL_CERT, $attr['ssl_cert']); self::$dbh->setAttribute(PDO::MYSQL_ATTR_SSL_CA, $attr['ssl_ca']); } }
/** * function for opening a connection to the database specified in config.ini * opens up the MySQL command line tool * @return int the executed commands shell status 0 on success. */ function connect_db() { $db = admin::getDbInfo(); if (!$db) { return db_no_url(); } $command = "mysql --default-character-set=utf8 -u" . conf::getMainIni('username') . " -p" . conf::getMainIni('password') . " -h" . $db['host'] . " {$db['dbname']}"; $ret = array(); proc_close(proc_open($command, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes)); }
/** * function for inserting user * @param array $values * @return boolean $res */ function useradd_db_insert($values) { $database = admin::getDbInfo(conf::getMainIni('url')); if (!$database) { return db_no_url(); } $db = new db(); $res = $db->insert('account', $values); return $res; }
/** * calculate a video ratio * @param int $default * @return int $ratio the ratio */ public static function videoRatio($default = 600) { $width = conf::getMainIni('media_width'); if ($width) { return $ratio = $width / $default; } else { // default ration is 1 return 1; } }
/** * returns favicon html * @return string $html */ public static function getFaviconHTML() { $favicon = conf::getMainIni('favicon'); $domain = conf::getDomain(); $rel_path = "/files/{$domain}/favicon/{$favicon}"; $full_path = conf::pathHtdocs() . "/{$rel_path}"; if (!is_file($full_path)) { $rel_path = '/favicon.ico'; } $str = "<link rel=\"shortcut icon\" href=\"{$rel_path}\" type=\"image/x-icon\" />\n"; return $str; }
/** * Connect to existing database handle with RedBeans */ public static function connectExisting() { static $connected = null; if (!$connected) { R::setup(connect::$dbh); $connected = true; } $freeze = conf::getMainIni('rb_freeze'); if ($freeze == 1) { R::freeze(true); } }
/** * function for installing coscms from a profile */ function cos_install($options = false) { // we need a profile specified if (!isset($options['profile'])) { common::abort('You need to specifiy a profile'); } // create files - logs/ - files/ cos_create_files(); // drop database drop_db_default($ary = array('silence' => 1)); // create database create_db(); // load default base sql. load_db_default(); // Set up profile to install $pro = new profile(); $pro->setProfileInfo($options['profile']); // install all the profile modules foreach ($pro->profileModules as $key => $val) { // check if master is specified. Else use profile version if (conf::getMainIni('git_use_master')) { $tag = 'master'; } else { $tag = $val['module_version']; } $options['repo'] = $val['public_clone_url']; $options['version'] = $tag; //$val['module_version']; $options['module'] = $val['module_name']; // check out and install cos_git_install($options, 'module'); } // install templates foreach ($pro->profileTemplates as $key => $val) { if (conf::getMainIni('git_use_master')) { $tag = 'master'; } else { $tag = $val['module_version']; } $options['repo'] = $val['public_clone_url']; $options['version'] = $tag; //$val['module_version']; $options['template'] = $val['module_name']; // check out and install cos_git_install($options, 'template'); } // load all profile ini files $pro->loadProfileFiles($options['profile']); // set template $pro->setProfileTemplate(); }
/** * Get HTML template for email * NOTE: Email needs to be set in config/config.ini when using CLI * @param string $path path to template * @return string $html */ public function getHtmlTemplate($path = null) { // Default path if (!$path) { $template = conf::getMainIni('template'); $path = conf::getTemplatePath($template) . '/mail/template.html'; } if (!file_exists($path)) { log::error('mailer/markdown: path does not exists: ' . $path); die; } $email = file_get_contents($path); return $email; }
/** * Set a log level based on env and debug */ public static function setLogLevel() { $env = conf::getEnv(); if ($env == 'development') { error_reporting(E_ALL); } // check if we are in debug mode and display errors if (conf::getMainIni('debug')) { ini_set('display_errors', 1); } if (conf::isCli()) { self::setErrorLog(); } }
function google_translate_path($options) { if (!isset($options['path'])) { common::abort('You need to specify path to translate'); } if (!isset($options['target'])) { common::abort('You need to specify target language to translate into'); } $e = new google(); $key = conf::getMainIni('google_translate_key'); $e->key = $key; $e->setSingleDir($options['path']); $e->updateLang(); }
/** * function for upgrading a module * * @param array options the module to be upgraded */ function cos_menu_uninstall_menu($options) { // check if module exists in modules dir $module_path = conf::pathModules() . '/' . $options['module']; if (!file_exists($module_path)) { common::echoMessage("module {$options['module']} does not exists in modules dir. "); } $menu = new moduleinstaller($options); $res = $menu->deleteMenuItem($options['module']); if ($res) { if (conf::getMainIni('verbose')) { common::echoMessage("Main menu item for '{$options['module']}' deleted"); } } }
/** * best guess for getting locales * If locale is set directly in configuration (or db override) we will * use this locale. * @return string */ public static function getLocale() { // Check in main config setting 'locale' $locale = conf::getMainIni('locale'); if ($locale) { return $locale; } // If locale is not set we use language .utf8 $language = conf::getMainIni('language'); if ($language) { return $language . ".utf8"; } // System locale return self::getSystemLocale(); }
/** * setup a Redbean instance from CosCMS */ public static function connect() { static $connected = null; if (!$connected) { $url = conf::getMainIni('url'); $username = conf::getMainIni('username'); $password = conf::getMainIni('password'); R::setup($url, $username, $password); $freeze = conf::getMainIni('rb_freeze'); if ($freeze == 1) { R::freeze(true); } $connected = true; } }
/** * dump single table structure * @param array $options */ function cos_structure_dump_table($options) { $ary = admin::getDbInfo(); if (!$ary) { return db_no_url(); } $user = conf::getMainIni('username'); $password = conf::getMainIni('password'); $dump_dir = "backup/sql/{$options['table']}"; if (!file_exists($dump_dir)) { mkdir($dump_dir); } $dump_name = "backup/sql/{$options['table']}/" . time() . ".sql"; $command = "mysqldump -d -h {$ary['host']} -u {$user} -p{$password} {$ary['dbname']} {$options['table']} > {$dump_name}"; common::execCommand($command); }
/** * gets database info from cinfuguration * @return array|false $ary false if no url is given. Array with db url info */ public static function getDbInfo($url = null) { if (!$url) { $url = conf::getMainIni('url'); } if (empty($url)) { return false; } $url = parse_url($url); $ary = explode(';', $url['path']); foreach ($ary as $val) { $a = explode("=", $val); if (isset($a[0], $a[1])) { $url[$a[0]] = $a[1]; } } return $url; }
/** * method for getting html for front page. If no logo has been * uploaded. You will get logo as html * @param type $options options to give to html::createHrefImage * @return string $str the html compsoing the logo or main title */ public static function getLogoHTML($options = array()) { $logo = conf::getMainIni('logo'); if (!$logo) { $title = $_SERVER['HTTP_HOST']; $link = html::createLink('/', $title); return $str = "<div id=\"logo_title\">{$link}</div>"; } else { $file = "/logo/" . conf::getMainIni('logo'); $src = conf::getWebFilesPath($file); if (!isset($options['alt'])) { $options['alt'] = $_SERVER['HTTP_HOST']; } $href = html::createHrefImage('/', $src, $options); $str = '<div id="logo_img">' . $href . '</div>' . "\n"; //die($str); return $str; } }
function db_to_sqlite($options = array()) { $check = "which sequel"; if (common::execCommand($check)) { common::echoMessage('You need sequel. Install it like this, e.g.:'); common::echoMessage('sudo aptitude install ruby-sequel libsqlite3-ruby libmysql-ruby'); common::abort(); } else { common::echoStatus('OK', 'g', 'Sequel is installed'); } $ok = false; $info = admin::getDbInfo(); if (!$info) { return db_no_url(); } if ($info['scheme'] == 'mysql') { $ok = true; } if ($info['scheme'] == 'mysqli') { $ok = true; } if (!$ok) { common::echoStatus('ERROR', 'r', 'Driver needs to be mysql or mysqli'); } $fs = new Filesystem(); $fs->remove('sqlite/database.sql'); $username = conf::getMainIni('username'); $password = conf::getMainIni('password'); $command = "sequel "; $command .= "{$info['scheme']}://{$username}:{$password}@{$info['host']}/{$info['dbname']} "; $command .= "-C "; $command .= "sqlite://sqlite/database.sql"; $ret = common::systemCommand($command); $base = conf::pathBase(); if (!$ret) { $fs->chmod('sqlite/database.sql', 0777, 00, true); common::echoMessage('Sqlite database created. Edit config.ini and add:'); common::echoMessage("sqlite:/{$base}/sqlite/database.sql"); } }
mkdir config touch config/config.ini Put your credentials into config/config.ini Something like this: url = "mysql:dbname=demo;host=localhost;charset=utf8" db_init = "SET NAMES utf8" username = "******" password = "******" EOF; echo $str; exit(1); } $db_conn = array('url' => conf::getMainIni('url'), 'username' => conf::getMainIni('username'), 'password' => conf::getMainIni('password'), 'db_init' => conf::getMainIni('db_init')); connect::connect($db_conn); function get_tables_db() { $db = new db(); $rows = $db->selectQuery('show tables'); $tables = array(); foreach ($rows as $table) { $tables[] = array_pop($table); } return $tables; } function get_table_create($table) { $db = new db(); $sql = "DESCRIBE `{$table}`";
/** * 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']; }
public function deleteAll() { $connect = array('host' => conf::getMainIni('imap_host'), 'port' => conf::getMainIni('imap_port'), 'user' => conf::getMainIni('imap_user'), 'password' => conf::getMainIni('imap_password'), 'ssl' => conf::getMainIni('imap_ssl')); $i = new imap(); $i->connect($connect); $c = $i->countMessages(); log::error("Parse bounces. Num messages: {$c}\n"); $i->mail->noop(); // reverse - we start with latest message = $c for ($x = $c; $x >= 1; $x--) { log::error("Pasing num: {$x}"); $i->mail->noop(); // keep alive $i->mail->removeMessage($x); $i->mail->noop(); // keep alive sleep(1); } }
/** * function for loading a database file into db specified in config.ini * * @param array options. You can specifiy a file to load in options. * e.g. <code>$options = array('File' => 'backup/sql/latest.sql')</code> * @return int the executed commands shell status 0 on success. */ function cos_db_load_table($options) { if (!isset($options['table'])) { common::abort('Specify a table to load with a backup'); } $dump_dir = "backup/sql/{$options['table']}"; if (!file_exists($dump_dir)) { common::abort('Yet no backups'); } $search = conf::pathBase() . "/backup/sql/{$options['table']}"; $latest = get_latest_db_dump($search); if ($latest == 0) { common::abort('Yet no database dumps'); } $latest = "backup/sql/{$options['table']}/" . $latest . ".sql"; $db = admin::getDbInfo(conf::getMainIni('url')); if (!$db) { return db_no_url(); } $command = "mysql --default-character-set=utf8 -u" . conf::$vars['coscms_main']['username'] . " -p" . conf::$vars['coscms_main']['password'] . " {$db['dbname']} < {$latest}"; return $ret = common::execCommand($command); }
/** * Returns a locale date string from mysql timestamp. * @param type $date same format as mysql timestamp * @param string $format ini settings format e.g. date_format_long * @return string $format */ public static function getDateString($date, $format = 'date_format_long') { $unix_stamp = strtotime($date); $date_formatted = strftime(conf::getMainIni($format), $unix_stamp); return $date_formatted; }
function clone_db($options = array()) { if (!isset($options['File'])) { common::abort('Specify new database name'); } $db = admin::getDbInfo(conf::getMainIni('url')); $old = $db['dbname']; $new_name = $options['File']; admin::cloneDB($old, $new_name); }
/** * function that checks for files dir, * and also checks is it is writable */ function cos_check_files_dir() { clearstatcache(); $files_dir = conf::pathFilesBase() . "/files"; $domain = conf::getMainIni('domain'); $files_dir .= "/{$domain}"; if (!is_writable($files_dir)) { echo "dir: {$files_dir} is not writeable<br />\n"; $user = getenv('APACHE_RUN_USER'); echo "server user is: {$user}<br />\n"; echo "On unix solution will be to:<br />\n"; echo "sudo chown -R www-data:www-data ./files"; die; } else { echo "We can write to files dir.OK<br>"; } }
/** * inits a template * set template name and load init settings * @param string $template name of the template to init. */ public static function init($template) { self::$templateName = $template; if (!isset(conf::$vars['template'])) { conf::$vars['template'] = array(); } moduleloader::setModuleIniSettings($template, 'template'); $css = conf::getMainIni('css'); if ($css) { assets::setTemplateCssIni($template, $css); } }
/** * init blocks and parse blocks. * blocks which should be inited are set in main config/config.ini * and looks like this: * * blocks_all = 'blocks,blocks_sec,blocks_top' * * Above ini setting means that we use three block sections called: * blocks, blocks_sec and blocks_top. * These names we then can use in our template, and display the blocks * using these names. */ public static function initBlocks() { $blocks = conf::getMainIni('blocks_all'); if (!isset($blocks)) { return; } $blocks = explode(',', $blocks); foreach ($blocks as $val) { self::$blocksContent[$val] = self::parseBlock($val); } }
/** * Before parsing of the commandline options * This loads all commandline options from file system * and modules found in the database */ public static function beforeParse() { self::loadBaseModules(); $url = conf::getMainIni('url'); if ($url) { self::loadDbModules(); } }