/** * Initialize instance * * @param Charcoal_Config $config configuration data */ public function configure($config) { parent::configure($config); $this->task_manager = us($config->getString('task_manager', '')); $this->forward_target = us($config->getString('forward_target', '')); $this->modules = uv($config->getArray('modules', array())); $this->events = uv($config->getArray('events', array())); $this->debug_mode = ub($config->getBoolean('debug_mode', FALSE)); $this->log_enabled = ub($config->getBoolean('log_enabled')); $this->log_level = us($config->getString('log_level')); $this->log_loggers = uv($config->getArray('log_loggers')); // eventsに記載しているイベントのモジュールも読み込む if (is_array($this->events)) { foreach ($this->events as $event) { $pos = strpos($event, "@"); if ($pos !== FALSE) { $this->modules[] = substr($event, $pos); } } } if ($this->getSandbox()->isDebug()) { log_info("system, debug, config", "task_manager:" . $this->task_manager, self::TAG); log_info("system, debug, config", "forward_target:" . $this->forward_target, self::TAG); log_info("system, debug, config", "modules:" . print_r($this->modules, true), self::TAG); log_info("system, debug, config", "events:" . print_r($this->events, true), self::TAG); log_info("system, debug, config", "debug_mode" . $this->debug_mode, self::TAG); log_info("system, debug, config", "log_enabled" . $this->log_enabled, self::TAG); log_info("system, debug, config", "log_level" . $this->log_level, self::TAG); log_info("system, debug, config", "log_loggers" . print_r($this->log_loggers, true), self::TAG); } }
/** * Initialize instance * * @param Charcoal_Config $config configuration data */ public function configure($config) { parent::configure($config); $this->debug_mode = ub($config->getBoolean('debug_mode', FALSE)); $this->smarty->caching = 0; //$config->getBoolean( 'caching' )->unbox(); $this->smarty->compile_check = ub($config->getBoolean('compile_check', FALSE)); $this->smarty->template_dir = us($config->getString('template_dir', '', TRUE)); $this->smarty->compile_dir = us($config->getString('compile_dir', '', TRUE)); $this->smarty->config_dir = us($config->getString('config_dir', '', TRUE)); $this->smarty->cache_dir = us($config->getString('cache_dir', '', TRUE)); $this->smarty->left_delimiter = us($config->getString('left_delimiter', '{', FALSE)); $this->smarty->right_delimiter = us($config->getString('right_delimiter', '}', FALSE)); // $this->smarty->default_modifiers = $config->getArray( 'default_modifiers', array() )->unbox(); $plugins_dir = uv($config->getArray('plugins_dir', array(), TRUE)); // add default plugins_dir: Smarty/Smarty/plugins $reflector = new ReflectionClass($this->smarty); $plugins_dir[] = dirname($reflector->getFileName()) . '/plugins'; $this->smarty->plugins_dir = $plugins_dir; log_debug("smarty", "smarty->plugins_dir=" . print_r($this->smarty->plugins_dir, true), self::TAG); log_debug("smarty", "smarty=" . spl_object_hash($this->smarty), self::TAG); if ($this->debug_mode) { $smarty_options = array('caching' => $this->smarty->caching, 'compile_check' => $this->smarty->compile_check, 'template_dir' => $this->smarty->template_dir, 'compile_dir' => $this->smarty->compile_dir, 'config_dir' => $this->smarty->config_dir, 'cache_dir' => $this->smarty->cache_dir, 'default_modifiers' => $this->smarty->default_modifiers, 'plugins_dir' => $this->smarty->plugins_dir, 'left_delimiter' => $this->smarty->left_delimiter, 'right_delimiter' => $this->smarty->right_delimiter); ad($smarty_options); foreach ($smarty_options as $key => $value) { log_debug('system, debug, smarty', "smarty option: [{$key}]=" . Charcoal_System::toString($value)); } } }
public function __construct($name, $value, $params) { Charcoal_ParamTrait::validateString(1, $name); Charcoal_ParamTrait::validateString(2, $value); Charcoal_ParamTrait::validateVector(3, $params); $this->name = us($name); $this->value = us($value); $this->params = uv($params); }
/** * プレースホルダーのリストを作成 * */ public static function makePlaceHolderList(Charcoal_Vector $values) { $values = uv($values); $str = ""; foreach ($values as $value) { if (strlen($str) > 0) { $str .= ","; } $str .= "?"; } return $str; }
public function convertArray($ary) { // Charcoal_ParamTrait::validateVector( 1, $ary ); $from = us($this->from); $to = us($this->to); $new_array = array(); foreach (uv($ary) as $key => $value) { $new_value = mb_convert_encoding($value, $to, $from); $new_array[$key] = $new_value; } return $new_array; }
public function newInstance($args = NULL) { // Charcoal_ParamTrait::validateVector( 1, $args, TRUE ); $args = uv($args); switch (count($args)) { case 0: return new $this->class_name(); case 1: return new $this->class_name($args[0]); case 2: return new $this->class_name($args[0], $args[1]); case 3: return new $this->class_name($args[0], $args[1], $args[2]); case 4: return new $this->class_name($args[0], $args[1], $args[2], $args[3]); case 5: return new $this->class_name($args[0], $args[1], $args[2], $args[3], $args[4]); case 6: return new $this->class_name($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]); case 7: return new $this->class_name($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]); } return NULL; /* try{ // reflection object $ref_class = new ReflectionClass( $this->class_name ); $object = $args ? $ref_class->newInstanceArgs( uv($args) ) : $ref_class->newInstanceArgs(); return $object; } catch( ReflectionException $ex ){ _throw( new Charcoal_ClassNewException( $this, $args, $ex ) ); } catch( Exception $ex ){ _throw( new Charcoal_ClassNewException( $this, $args, $ex ) ); } */ }
public function writeln(Charcoal_LogMessage $msg) { $req_path = $this->getSandbox()->getEnvironment()->get('%REQUEST_PATH%'); $req_id = $this->getSandbox()->getEnvironment()->get('%REQUEST_ID%'); $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-'; $level = $msg->getLevel(); $message = $msg->getMessage(); $file = $msg->getFile(); $line = $msg->getLine(); $time = date("y/m/d H:i:s"); $file = basename($file); // エンコーディング変換 $message = $this->convertEncoding(s($message)); // 接続処理 $this->open(); // 区切り文字 $delimiter = ","; if (ui($this->_delimiter) == 1) { $delimiter = "\t"; } // 改行コード $eol = self::CRLF; if (ui($this->_eol_code) == 1) { $eol = self::CR; } if (ui($this->_eol_code) == 2) { $eol = self::LF; } // ファイル書き込み $orders = uv($this->_field_order); $out = ""; foreach ($orders as $field) { $field = strtoupper(trim($field)); if (strlen($out) > 0) { $out .= $delimiter; } switch ($field) { case "%REQUEST_PATH%": $out .= $this->EscapeQuote(s($req_path)); break; case "%IP%": $out .= $this->EscapeQuote(s($ip)); break; case "%REQUEST_ID%": $out .= $this->EscapeQuote(s($req_id)); break; case "%TIME%": $out .= $this->EscapeQuote(s($time)); break; case "%LEVEL%": $out .= $this->EscapeQuote(s($level)); break; case "%MESSAGE%": $out .= $this->EscapeQuote(s($message)); break; case "%FILE%": $out .= $this->EscapeQuote(s($file)); break; case "%LINE%": $out .= $this->EscapeQuote(s($line)); break; default: break; } } $out .= $eol; $this->write(s($out)); }
/** * flush a message * * @param Charcoal_LogMessage $msg message object to flush */ public function flushMessage($msg) { // Charcoal_ParamTrait::validateIsA( 1, 'Charcoal_LogMessage', $msg ); if (!$this->log_enabled) { return; } // 対象ロガーに対してのみ出力 $output_loggers = array_flip($this->log_loggers); $level = $msg->getLevel(); $logger_names = $msg->getLoggerNames(); // プロファイルに設定したレベル以下ならば出力しない $cmp = self::_compareLogLevel($level, $this->log_level); if ($cmp > 0) { return; } // タグフィルタが設定されている場合、マッチしないログは無視 $log_tag_filters = $this->log_tag_filters; if (is_array($log_tag_filters) && !empty($log_tag_filters)) { if (!in_array($msg->getTag(), $log_tag_filters)) { return; } } foreach (uv($logger_names) as $key) { // 登録されていて、かつプロファイルにエントリがあるログだけに出力する if (isset($this->loggers[$key]) && isset($output_loggers[$key])) { /** @var Charcoal_ILogger $logger */ $logger = $this->loggers[$key]; $logger->writeln($msg); } } }
/** * process events * * @param Charcoal_IEventContext $context * * @return int * * @throws Charcoal_BusinessException|Charcoal_RuntimeException */ public function processEvents($context) { $debug = $this->getSandbox()->isDebug() || $context->getProcedure()->isDebugMode(); if ($debug) { log_debug('system,event', "processEvents start."); } // $procedure = $context->getProcedure(); // $request = $context->getRequest(); // $sequence = $context->getSequence(); // $response = $context->getResponse(); $max_event_loop = $this->max_event_loop; $exit_code = 0; try { $queue = $this->queue; $timer_all = Charcoal_Benchmark::start(); $loop_id = 0; while (!$queue->isEmpty()) { if ($debug) { log_debug('system,event', "event queue(" . count($queue) . "): {$queue}"); } // increment loop counter $loop_id++; // イベント一覧を優先度でソートする $queue->sortByPriority(); /** @var Charcoal_IEvent $event */ $event = $queue->dequeue(); /** @var string $event_name */ $event_name = $event->getObjectName(); /** @var Charcoal_ObjectPath $event_id */ $event_id = $event->getObjectPath(); $delete_event = FALSE; $context->setEvent($event); // if this event loop exceeds [max_event_loop], thro exception if ($loop_id > $max_event_loop) { log_warning("system,event", "[loop:{$loop_id}/{$event_name}] aborting by overflow maximum loop count[{$max_event_loop}].", "task_manager"); log_warning("system,event", "[loop:{$loop_id}/{$event_name}] event queue=[{$queue}].", "task_manager"); _throw(new Charcoal_EventLoopCounterOverflowException($max_event_loop)); } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event loop start."); } // タスク一覧を優先度でソートする $key_priority = array(); foreach ($this->tasks as $key => $task) { $key_priority[$key] = ui($task->getPriority()); } $a_task_list = uv($this->tasks); array_multisort($key_priority, SORT_DESC, $a_task_list); $this->tasks = v($a_task_list); // task list to remove on end of this loop $remove_tasks = NULL; // すべてのタスクにイベントをディスパッチする if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] task list: [{$this->tasks}]"); } foreach ($this->tasks as $task) { $task_name = $task->getObjectName(); $task_id = $task->getObjectPath(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is dispatching to task[{$task_name}]."); } // イベントフィルタ $process = FALSE; $event_filters = $task->getEventFilters(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task event filter: " . $event_filters); } foreach ($event_filters as $filter) { if ($event_id->getObjectPathString() == us($filter)) { $process = TRUE; break; } } if (!$process) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is NOT found in task's event filters: [{$event_filters}]. Passing this task."); } continue; } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$event_name}] is found in task's event filters: [{$event_filters}]."); } // task timer start $timer_task = Charcoal_Benchmark::start(); $result = NULL; try { $result = $task->processEvent($context); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] returned from processEvent with result:" . print_r($result, true)); } } catch (Charcoal_BusinessException $e) { // just handle the exception $exception_handled = $task->handleException($e, $context); if (b($exception_handled)->isFalse()) { // just re-throw the exception, if the exception was not handled by the task throw $e; } } catch (Charcoal_RuntimeException $e) { // write log and handle the exception _catch($e); $exception_handled = $task->handleException($e, $context); if (b($exception_handled)->isFalse()) { // write log and re-throw the exception, if the exception was not handled by the task _throw($e); } } // result value handling $result_str = NULL; if ($result === NULL) { $result_str = 'NULL'; } elseif ($result === FALSE || $result instanceof Charcoal_Boolean && $result->isFalse()) { $result_str = 'FALSE'; $result = FALSE; } elseif ($result === TRUE || $result instanceof Charcoal_Boolean && $result->isTrue()) { $result_str = 'TRUE'; $result = TRUE; } else { $msg = "processEvent() must return a [boolean] value. but returned:" . print_r($result, true); log_error('system,event,error', $msg, self::TAG); _throw(new Charcoal_ProcessEventAtTaskException($event, $task, $result, $msg)); } // task timer stop $elapse = Charcoal_Benchmark::stop($timer_task); log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event was processed by task. result=[{$result_str}] time=[{$elapse}]msec."); // ポストアクション $post_actions = $task->getPostActions(); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task post actions: {$post_actions}"); } if ($result && $post_actions) { foreach ($post_actions as $key => $action) { $target = NULL; $action = us($action); if (strpos(":", $action) !== FALSE) { list($action, $target) = explode(":", trim($action)); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] post action[{$action}] with target[{$target}]."); } } else { $action = trim($action); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] post action[{$action}]."); } } switch ($action) { case "remove_task": // タスク実行リストからタスクを削除 if (!$target) { $target = $task_id; } if ($target == $task_id) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] task[{$target}] is marked to remove."); } $remove_tasks[] = $task_id; } break; case "remove_event": // イベントを削除 if (!$target) { $target = $event_id; } if ($target == $event_id) { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] event[{$target}] is marked to remove."); } $delete_event |= TRUE; } break; case "continue_event": // イベントをキューに再投入 break; } } } else { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}/{$task_name}] no post action is defined for event."); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] task loop end."); } } // task loop end // remove tasks if ($remove_tasks) { foreach ($remove_tasks as $task_id) { unset($this->tasks["{$task_id}"]); if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] removed task: {$task_id}"); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] next task list: [{$this->tasks}]"); } } if (!$delete_event) { // push back the event into our event queue $this->pushEvent($event); } else { if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event[{$event}] is removed."); } } if ($debug) { log_debug('system,event', "[loop:{$loop_id}/{$event_name}] event loop end."); } } // event loop end if ($queue->isEmpty()) { if ($debug) { log_debug('system,event', "event queue is empty."); } $exit_code = Charcoal_Event::EXIT_CODE_OK; } // ログ $elapse = Charcoal_Benchmark::stop($timer_all); if ($debug) { log_debug('system,event', "event loop end. time=[{$elapse}]msec."); } } catch (Charcoal_RuntimeException $e) { _catch($e, true); if ($debug) { log_debug('system,event,debug', "an exception occured while processing event."); } _throw(new Charcoal_ProcessEventAtTaskManagerException($e)); } if ($debug) { log_debug('system,event', "processEvents end: exit_code=" . print_r($exit_code, true)); } return $exit_code; }
/** * Generate RDBMS-specific SQL for bulk insert * * @param Charcoal_ITableModel $model table model object related with th query * @param string $alias table model alias which is specified by $model * @param array $data_set array of array or HashMap of objects * @param array $override association field set which you want to override * * @return array the first element means SQL, the second element means parameter values */ public function buildBulkInsertSQL($model, $alias, $data_set, $override = NULL) { Charcoal_ParamTrait::validateIsA(1, 'Charcoal_ITableModel', $model); Charcoal_ParamTrait::validateString(2, $alias, TRUE); Charcoal_ParamTrait::validateVector(3, $data_set); Charcoal_ParamTrait::validateHashMap(4, $override, TRUE); try { $SQL_field_list = NULL; $SQL_value_list = NULL; $SQL_params = array(); $override = up($override); $field_list = $model->getFieldList(); // determin field list foreach ($field_list as $field) { $insert = $model->getAnnotationValue(s($field), s('insert')); if ($override && isset($override[$field])) { $insert = isset($override[$field]['insert']) ? $override[$field]['insert'] : $insert; } if (!$insert) { // 無指定の場合エラー _throw(new Charcoal_TableModelFieldException($model, $field, '[@insert] annotation is required')); } // @insertアノテーションの値によって分岐 $insert_anno = us($insert->getValue()); switch ($insert_anno) { case 'value': case 'function': $SQL_field_list[] = $field; break; case 'no': break; default: _throw(new Charcoal_TableModelFieldException($model, $field, '[@insert] value is invalid')); } } // determin value list foreach ($data_set as $dto) { $SQL_value_list_line = array(); foreach ($SQL_field_list as $field) { $insert = $model->getAnnotationValue(s($field), s('insert')); if ($override && isset($override[$field])) { $insert = isset($override[$field]['insert']) ? $override[$field]['insert'] : $insert; } if (!$insert) { // 無指定の場合エラー _throw(new Charcoal_TableModelFieldException($model, $field, '[@insert] annotation is required')); } // @insertアノテーションの値によって分岐 $insert_anno = us($insert->getValue()); switch ($insert_anno) { case 'value': // 値で更新 $value = $dto->{$field}; if (is_array($value)) { $type = isset($value[0]) ? $value[0] : NULL; $arg = isset($value[1]) ? $value[1] : NULL; $processed = false; if (is_string($type) && is_string($arg)) { switch (strtolower($type)) { case 'value': if (strtolower($arg) == 'null') { $SQL_value_list_line[] = 'NULL'; $processed = true; } break; case 'function': if (strtolower($arg) == 'now') { $SQL_value_list_line[] = 'NOW()'; $processed = true; } break; } } // is not processed, save the array as a JSON string if (!$processed) { $SQL_value_list_line[] = '?'; $SQL_params[] = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } } elseif ($value !== NULL) { $SQL_value_list_line[] = '?'; $SQL_params[] = $value; } break; case 'function': // 関数を決定 $params = uv($insert->getParameters()); $function = 'NULL'; if (count($params) == 1) { switch ($params[0]) { case 'now': $function = 'NOW()'; break; default: break; } } // 関数で更新 $SQL_value_list_line[] = $function; break; case 'no': // 更新しない break; default: _throw(new Charcoal_TableModelFieldException($model, $field, '[@insert] value is invalid')); } } $SQL_value_list[] = $SQL_value_list_line; } $SQL_field_list = implode(',', $SQL_field_list); $table = $model->getTableName(); $sql = "INSERT INTO " . us($table) . "(" . us($SQL_field_list) . ") VALUES"; $values = array(); foreach ($SQL_value_list as $line) { $SQL_value_list = implode(',', $line); $values[] = "(" . us($SQL_value_list) . ")"; } $sql .= implode(',', $values); return array($sql, $SQL_params); } catch (Exception $e) { _throw(new Charcoal_SQLBuilderException("DefaultSQLBuilder#buildInsertSQL failed")); } return array(); }
public function getKeys() { $global_keys = $this->_global->getKeys(); $local_keys = $this->_local->getKeys(); $keys = array_merge(uv($global_keys), uv($local_keys)); return $keys; }
/** * Add multiple parameters * * @param Charcoal_Vector|array $params array data to add */ public function addParams($params) { Charcoal_ParamTrait::validateVector(1, $params); if ($this->params) { $this->params = array_merge($this->params, $params); } else { $this->params = uv($params); } }