/** * install an orbit module * * @param array $params */ public function action_permissions($params) { $folders = \CCEvent::fire('ccdoctor.permissions'); if (!is_array($folders)) { $folders = array(); } // add storage directories foreach (\ClanCats::$config->get('storage.paths') as $folder) { $folders[] = $folder; } foreach ($folders as $folder) { $display_folder = \CCStr::replace($folder, array(CCROOT => '')); // create directory if not existing if (!is_dir($folder)) { if (!mkdir($folder, 0755, true)) { $this->error("doctor could not create folder at: {$display_folder}"); } } // check permissions $perm = substr(decoct(fileperms($folder)), 2); if ($perm < 755) { CCCli::line(CCCli::color($perm, 'red') . ' - ' . $display_folder . ' fixing with ' . CCCli::color('755', 'green')); if (!chmod($folder, 0755)) { CCCli::line("doctor - is not able to change permissions for: {$display_folder}", 'red'); } } elseif ($perm == 777) { CCCli::line(CCCli::color($perm, 'yellow') . ' - ' . $display_folder . ' warning! this can be dangerous.'); } else { $this->success('- ' . $display_folder, $perm); } } }
/** * Add something to the packer * This method allows you to add stylesheets, javascript files etc. * to one single file. * * exmaple: * CCAsset::pack( 'jquery.js', 'footer', 'core' ); * * @param string |array $item An single or an array of assets * @param string $name The holders name like header / theme / footer * @param string $pack The package like core lib etc. * @return void */ public static function pack($item, $name = null, $pack = 'pack') { if (!is_array($item)) { $items = array($item => $name); } $path = PUBLICPATH . static::holder($name)->path; foreach ($items as $file => $holder) { static::holder($name)->assets['_packtacular'][$pack][CCStr::extension($item)][] = $path . $file; } }
/** * initialize the ship * * @return void */ public function wake() { if (!\ClanCats::in_development()) { return; } // get all controllers in the dev namespace foreach (\CCFile::ls(\CCPath::controllers('Dev::*Controller' . EXT)) as $path) { $name = \CCStr::cut(basename($path), 'Controller' . EXT); \CCRouter::on('dev/' . \CCStr::lower($name), 'Dev::' . $name); } }
/** * Get the current builder output * * @return string */ public function output() { $shema = \DB::fetch("DESCRIBE {$this->table};", array(), null, 'assoc'); if (empty($shema)) { throw new CCException('CCShipyard - The given database table is invalid or does not exist.'); } $class = \CCShipyard::create('class', $this->name, "\\DB\\Model"); $class->add('property', '_table', 'protected static', $this->table, 'The database table name'); // timestamps if ($this->timestamps) { $class->add('line', 2); $class->add('property', '_timestamps', 'protected static', true, 'Allow automatic timestamps'); } // shema $class->add('line', 2); // define the internal types $internal_types = array('bool', 'int', 'float', 'double', 'string'); $match_types = array('tinyint' => 'int', 'text' => 'string', 'varchar' => 'string'); foreach ($shema as $item) { $default = $item['Default']; $field = $item['Field']; if (empty($default)) { $type = \CCStr::cut($item['Type'], '('); if (array_key_exists($type, $match_types)) { $type = $match_types[$type]; } elseif (!in_array($type, $internal_types)) { $type = null; } // The primary key should not contain a default value if ($item['Key'] == 'PRI') { $type = null; } elseif ($item['Type'] == 'tinyint(1)') { $type = 'bool'; } if ($type !== null) { settype($default, $type); } } $buffer = "\t'{$field}'"; if (!is_null($type)) { $buffer .= " => array( '" . $type . "'"; if (!is_null($default)) { $buffer .= ", " . var_export($default, true) . " )"; } } $props[] = $buffer; } $class->add('property', '_defaults', 'protected static', "array(\n" . implode(",\n", $props) . "\n)", 'The ' . $class . ' default properties', false); return $class->output(); }
/** * Add an asset to the holder. Basically this method checks the * file extension to sort them and generate the correct code using the macros. * * $holder->add( 'jquery.js' ); * $holder->add( 'style.css' ); * $holder->add( '<script>document.write( "Hello World" );</script>' ); * * @param string $item * @return void */ public function add($item) { // when the first character is a "smaller than" we simply assume // that a custom tag has been passed and not a filepath if (strpos($item, "<") !== false) { $macro = '_'; } else { $macro = CCStr::extension($item); } if (!isset($this->assets[$macro])) { $this->assets[$macro] = array(); } $this->assets[$macro][] = $item; }
/** * show php info */ public function action_phpinfo() { // set topic $this->theme->topic = "php info"; // get php info in a string ob_start(); phpinfo(); $pinfo = ob_get_contents(); ob_end_clean(); // get only the body $pinfo = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo); // add table class $pinfo = str_replace('<table', '<table class="table table-bordered"', $pinfo); // better headers $pinfo = \CCStr::replace($pinfo, array('</h2>' => '</h2><hr>')); echo $pinfo; }
/** * error class init * * @return void */ public static function _init() { // we capture non fatal errors only in dev environments if (ClanCats::in_development()) { // add a hook to the main resposne CCEvent::mind('response.output', function ($output) { if (strpos($output, '</body>') === false) { return $output; } $table = \UI\Table::create(array('style' => array('width' => '100%'), 'cellpadding' => '5', 'class' => 'table debug-table debug-table-errors')); $table->header(array('#', 'message', 'file')); foreach (\CCError::$non_fatals as $key => $item) { $table->row(array($key + 1, $item->getMessage(), CCStr::strip($item->getFile(), CCROOT) . ':' . $item->getLine())); } return str_replace('</body>', $table . "\n</body>", $output); }); } }
/** * check if a controller implements an action * * @param string $path * @param string $action * @return bool */ public static function has_action($path, $action = null) { $path = CCStr::cut($path, '@'); $path = CCStr::cut($path, '?'); // fix closure given if (!is_string($path)) { return false; } // get controllers default action if (is_null($action)) { $action = static::$_default_action; } // try to load the controller if (!($controller = static::create($path))) { return false; } return method_exists($controller, static::$_action_prefix . $action); }
/** * connect to database * * @param array $conf * @return bool */ public function connect($conf) { $connection_params = array(); foreach ($conf as $key => $value) { if (is_string($value)) { $connection_params['{' . $key . '}'] = $value; } } $connection_string = \CCStr::replace($this->connection_string, $connection_params); $this->connection = new \PDO($connection_string, $conf['user'], $conf['pass'], $this->connection_attributes($conf)); // At the moment this will never happen because pdo is going to // trhow an exception when the connection fails /*if ( !$this->connection ) { return false; }*/ // let pdo throw exceptions $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); return true; }
/** * handle some files * * @param array $files * @param string $dir * @param string $file */ public static function handle($files, $dir, $file) { if (empty($files)) { return null; } $last_change = static::last_change($files); $file = str_replace("{time}", $last_change, $file); // the main needed paths $file = static::$path . $dir . $file; $dir = static::$path . $dir; // does the file already exist? if (file_exists(PUBLICPATH . $file)) { return $file; } // is there a cache dir? if (!is_dir(PUBLICPATH . $dir)) { if (!mkdir(PUBLICPATH . $dir, 0755, true)) { throw new CCException("CCPacktacular - could not create Packtacular folder at: {$dir}"); } } // get the pack file extention $ext = CCStr::extension($file); // get all the content $content = ""; foreach ($files as $tmp_file) { $content .= "\n\n/*\n * file: " . str_replace(PUBLICPATH, '', $tmp_file) . "\n */\n\n"; $content .= file_get_contents($tmp_file); } // call the modifier if (method_exists(get_class(), "handle_" . $ext)) { $content = call_user_func_array("static::handle_" . $ext, array($content)); } // save the file if (!file_put_contents(PUBLICPATH . $file, $content)) { throw new CCException("CCPacktacular - could not create packed file {$file}!"); } // return the path return $file; }
/** * Creates a new migrator instance * * @param string $path The path of the migration * @return void */ protected function __construct($path) { $this->path = $path; $this->name = \CCStr::cut(substr(basename($path), 0, strrpos(basename($path), '_')), '.'); }
/** * modify the headers to force a download * * @param string $filename * @return void */ public function as_download($filename = null) { if (is_null($filename)) { $filename = 'file.' . CCStr::suffix($this->header('Content-Type'), '/'); } $this->header('Content-Description', 'File Transfer'); $this->header('Content-Disposition', 'attachment; filename=' . $filename); $this->header('Content-Transfer-Encoding', 'binary'); $this->header('Expires', '0'); $this->header('Cache-Control', 'must-revalidate'); $this->header('Pragma', 'public'); $this->header('Content-Length', strlen($this->body())); return $this; }
/** * generates an closure * * @param string $str * @param int $wordwrap * @return string */ public function closure($name, $content = null, $comment) { return $this->add(($comment ? static::make('comment', array($comment)) . "\n" : '') . $name . "\n{\n" . str_replace("\n", "\n\t", "\t" . CCStr::capture($content)) . "\n}"); }
/** * Prepares a file with the parameters * * @param string $file * @return $file */ public static function file($file) { $params = array_merge(static::$params, array('time' => time(), 'fingerprint' => \CCSession::fingerprint(), 'random' => CCStr::random())); foreach ($params as $param => $value) { $file = str_replace(':' . $param, $value, $file); } return $file; }
/** * Always hash the passwort * * @param string $password * @return string */ protected function _set_modifier_password($password) { return \CCStr::hash($password); }
/** * install a ship * * string $path | the ship name / the folder. If the path is not absolute, ORBITPATH gets used */ public static function install($path) { // load ship at path $ship = CCOrbit_Ship::create($path); if (static::$data->has('installed.' . $ship->name)) { throw new CCException("CCOrbit::install - {$ship->name} ship already installed."); } if ($ship->install !== false) { $ship->event($ship->install); } static::$data->set('installed.' . $ship->name, CCStr::strip($ship->path, CCROOT)); // save changes static::$data->write('json'); }
/** * returns current execution time * * @param bool $format * @return string */ public static function time($format = false) { $time = microtime(true) - CCF_PROFILER_TME; if ($format) { return CCStr::microtime($time); } return $time; }
/** * Search and replace vars with . array access * * @param string $view * @return void */ private function compile_arrays($view) { $tokens = token_get_all($view); $tags = array(0 => ''); $tag_index = 0; $in_tag = false; // parse all php tags out of the view foreach ($tokens as $token) { if (is_array($token)) { if ($token[0] === T_OPEN_TAG) { $in_tag = true; } if ($in_tag && !in_array($token[0], array(T_INLINE_HTML))) { $tags[$tag_index] .= $token[1]; } if ($token[0] === T_CLOSE_TAG) { $in_tag = false; $tag_index++; } } else { if ($in_tag) { $tags[$tag_index] .= $token; } } } // lets make the tags search keys $tags = array_flip($tags); // now search and replace var in the php sections foreach ($tags as $search => &$replace) { $replace = preg_replace_callback('/(\\$[a-zA-Z0-9\\_\\.\\-\\>\\;]+)/s', function ($match) { $var = $match[1]; if (strpos($var, '.') !== false) { $buffer = ''; $length = strlen($var); $inside_arr = false; for ($i = 0; $i < $length; $i++) { $char = $var[$i]; if ($char == '.' && !$inside_arr) { $buffer .= "['"; $inside_arr = true; } else { if ($inside_arr && in_array($char, array(';', '-', ','))) { $buffer .= "']"; $inside_arr = false; } if ($char == '.') { $buffer .= "']['"; $inside_arr = true; } else { $buffer .= $char; } } } if ($inside_arr) { $buffer .= "']"; } $var = $buffer; } return $var; }, $search); } return CCStr::replace($view, $tags); }
<?php /* *--------------------------------------------------------------- * Database configuration *--------------------------------------------------------------- */ return array('main' => array('db' => 'db_' . CCStr::clean_url(App::name(), '_'), 'driver' => 'mysql', 'host' => '127.0.0.1', 'user' => 'root', 'pass' => '', 'charset' => 'utf8'));
/** * default help formatter * * @param array $params * @return void */ protected function help_formatter($help = null) { if (is_null($help)) { CCCli::line('Invalid data passed to help formatter.', 'red'); return; } $output = array(); // print the name if (isset($help['name'])) { $output[] = '+-' . str_repeat('-', strlen($help['name'])) . '-+'; $output[] = '| ' . CCCli::color($help['name'], 'light_yellow') . ' |'; $output[] = '+-' . str_repeat('-', strlen($help['name'])) . '-+'; } // description if (isset($help['desc'])) { $output[] = wordwrap(str_replace("\n", "\n" . ' * ', $help['desc']), 60); } // list the actions if (isset($help['actions']) && !empty($help['actions'])) { // for every action in this console controller foreach ($help['actions'] as $action => $attributes) { // print the action $output[] = ''; $output[] = '| ' . CCStr::suffix(get_called_class(), '\\') . '::' . CCCli::color($action, 'cyan'); $output[] = '|'; // for every attribute ( arguments, usage etc. ) foreach ($attributes as $attribute => $options) { $output[] = '| ' . CCCli::color(ucfirst($attribute), 'light_yellow'); // if we just got a string if (is_string($options)) { $output[] = '| ' . CCCli::color($options, 'green'); } elseif (is_array($options)) { // print every option and its description foreach ($options as $option => $description) { $buffer = CCCli::color($option, 'green'); $buffer .= str_repeat(' ', 35 - strlen($buffer)); $buffer .= $description; $buffer = '| ' . $buffer; // is the line to long? if (strlen($buffer) > 80) { $overflow = substr($buffer, 80); $buffer = substr($buffer, 0, 80) . "\n"; $overflow = wordwrap($overflow, 45); $overflow = explode("\n", $overflow); foreach ($overflow as $key => $value) { $overflow[$key] = '| ' . str_repeat(' ', 25) . trim($value); } $buffer .= implode("\n", $overflow); } $output[] = $buffer; } } $output[] = '|'; } array_pop($output); } } return $output; }
/** * test string bytes */ public function testBytes() { $this->assertEquals('956b', CCStr::bytes(956)); $this->assertEquals('42.4kb', CCStr::bytes(43413)); $this->assertEquals('423.96kb', CCStr::bytes(434131)); $this->assertEquals('41.4mb', CCStr::bytes(43413313)); $this->assertEquals('4.04gb', CCStr::bytes(4341311313)); $this->assertEquals('42kb', CCStr::bytes(43413, 0)); $this->assertEquals('423.956kb', CCStr::bytes(434131, 3)); $this->assertEquals('41.4022mb', CCStr::bytes(43413313, 4)); $this->assertEquals('41.4mb', CCStr::bytes(43434513, 1)); }
/** * Create a image from file * * @param string $file * @param string $type jpg|png|gif * * @return CCImage|false */ public static function create($file, $type = null) { // when no type is given use the file extension if (is_null($type)) { $type = CCStr::extension($file); // validate type if (!in_array($type, static::$available_image_types)) { $type = null; } } $image_data = getimagesize($file); if ($image_data === false) { return false; } $image = null; switch ($image_data['mime']) { case 'image/gif': $image = imagecreatefromgif($file); break; case 'image/jpeg': $image = imagecreatefromjpeg($file); break; case 'image/png': $image = imagecreatefrompng($file); break; default: // we dont support other image types return false; break; } // when the image type is still null we are going to use // the mime type of the image if (is_null($type)) { $type = CCStr::suffix($image_data['mime'], '/'); } return new static($image, $type); }
function _e($in, $recursive = false) { return CCStr::htmlentities($in, $recursive = false); }
/** * Create a new from instance * * @param callback $callback * @param string $key The form key used for identification. * @param array $attr The form dom attributes. * @return UI\Form */ public static function capture($callback = null, $key = null, $attr = null) { // we got some dynamics in the parameters here so in case // of this shift stuff if (is_callable($attr) && !is_callable($callback)) { $new_attr = $key; $key = $callback; $callback = $attr; $attr = $new_attr; } $form = new static(); if (is_null($callback)) { throw new Exception('Cannot use capture without a callback or string given.'); } // fix no array given if (!is_array($attr)) { $attr = array(); } return static::start($key, $attr) . \CCStr::capture($callback, array($form)) . static::end(); }
/** * Validate an identifier with the password * In other words is the login correct? * * @param string $identifier * @param string $password * @return mixed false on failure, user object on success */ public function validate($identifier, $password) { $user = null; $user_model = $this->config->user_model; foreach ($this->config->identifiers as $property) { if ($user = $user_model::find($property, $identifier)) { break; } } // when could not find a user matching the identifiers return false if (!$user) { return false; } // in case the user has no password set always return false // you might implement a oauth login so you dont need to set a // password but this makes sure that validating fails the password fails if (empty($user->password)) { return false; } // when the passwords match return the user object if (\CCStr::verify_hash($password, $user->password)) { return $user; } // otherwise return false return false; }
/** * Check and complete a route * * @param CCRoute $route * @param mixed $raw_route * @return false|CCRoute */ protected static function configure($route, $raw_route) { // deal with emptiness if (is_null($raw_route)) { return false; } // this might be a controller if (is_string($raw_route)) { // are there overwrite parameters? if (strpos($raw_route, '?') !== false) { $route->params = explode(',', CCStr::suffix($raw_route, '?')); $raw_route = CCStr::cut($raw_route, '?'); } // is there a overwrite action? if (strpos($raw_route, '@') !== false) { $route->action = CCStr::suffix($raw_route, '@'); $raw_route = CCStr::cut($raw_route, '@'); } // try creating an controller instance $controller = CCController::create($raw_route); // set the callback on controller execute $route->callback = array($controller, 'execute'); } elseif (is_callable($raw_route)) { $route->callback = $raw_route; } return $route; }
/** * get the requestet uri * * @param bool $full Don't cut the get params * @return string */ public function uri($full = false) { // check if we already set the current uri if (is_null($this->uri)) { $this->uri = $this->server('REQUEST_URI', '/'); // fix doubled slashes $this->uri = preg_replace('/(\\/+)/', '/', $this->uri); // remove get params if (!$full) { $this->uri = CCStr::cut($this->uri, '?'); } // cut the offset from the config $this->uri = substr($this->uri, strlen(ClanCats::$config->get('url.path'))); // if null or false set to default if (!$this->uri) { $this->uri = ''; } } return $this->uri; }
/** * Generate a new session id and checks the dirver for dublicates. * * @return string The new generated session id. */ public function regenerate() { do { $id = \CCStr::random(32); } while ($this->_driver->has($id)); $this->fingerprint = sha1($id); return $this->id = $id; }
/** * Send the mail * * @param CCMail $mail The mail object. * @return void * * @throws Mail\Exception */ public function send(CCMail $mail) { $data = $mail->export_data(); $filename = 'mails/' . date('Y-m') . '/' . date('d') . '/' . date("H-i-s") . '-' . \CCStr::clean_url($data['subject']) . '.log'; \CCFile::append(\CCStorage::path($filename), \CCJson::encode($data, true)); }
/** * just like capture but it appends * * @param string $key * @param callback $callback * @return void */ public function capture_append($key, $callback) { return $this->set($key, $this->get($key, '') . CCStr::capture($callback, $this)); }