コード例 #1
0
 /**
  * initialize exception handler list
  */
 public function init()
 {
     // if this object is already initialized, do nothing
     if ($this->init) {
         return TRUE;
     }
     // if our sandbox is not loaded, do nothing
     if (!$this->sandbox->isLoaded()) {
         return FALSE;
     }
     // read initialization options from sandbox profile
     $this->log_enabled = ub($this->sandbox->getProfile()->getBoolean('LOG_ENABLED', FALSE));
     $this->log_level = us($this->sandbox->getProfile()->getString('LOG_LEVEL', 'W'));
     $this->log_no_buffer = ub($this->sandbox->getProfile()->getBoolean('LOG_NO_BUFFER', FALSE));
     $this->log_tag_filters = uv($this->sandbox->getProfile()->getArray('LOG_TAG_FILTERS', array()));
     $this->log_loggers = uv($this->sandbox->getProfile()->getArray('LOG_LOGGERS', array()));
     $this->loggers = array();
     // create loggers on demand
     if ($this->log_loggers) {
         foreach ($this->log_loggers as $logger_name) {
             if (strlen($logger_name) === 0) {
                 continue;
             }
             if (!isset($this->loggers[$logger_name])) {
                 $logger = $this->sandbox->createObject($logger_name, 'logger', array(), 'Charcoal_ILogger');
                 self::register($logger_name, $logger);
             } else {
                 log_warning("system,debug,error", "Logger[{$logger_name}] is already registered!");
             }
         }
     }
     $this->init = TRUE;
     return TRUE;
 }
コード例 #2
0
function process($info)
{
    $commit_info = $info['commit_info'];
    $module = $info['module'];
    $git_path = $info['git_path'];
    $svn_path = $info['svn_path'];
    if (empty($module) || empty($git_path) || empty($svn_path)) {
        log_warning(sprintf("some parameter is invalid. " . "module[%s] git_path[%s] svn_path[%s]", $module, $git_path, $svn_path));
        return false;
    }
    $svn_path_name = basename($svn_path);
    if ($svn_path_name != $module) {
        log_warning("svn module does not match git module", $svn_path_name, $module);
        return false;
    }
    if ($commit_info['ref'] != 'refs/heads/master') {
        log_debug("omit non master commit");
        return true;
    }
    $pwd = dirname(__FILE__);
    $cmd = "(source ~/.bashrc && cd {$pwd} && nohup ./git2svn.sh {$module} {$git_path} {$svn_path}) >./log/job.\$\$.log 2>&1 & echo \$!";
    exec($cmd, $output, $ret);
    log_debug(sprintf("start background sync script. cmd[%s] ret[%s] job-pid[%s]", $cmd, $ret, $output[0]));
    if ($ret == 0) {
        return true;
    } else {
        return false;
    }
}
コード例 #3
0
ファイル: ForgotController.php プロジェクト: ryo-endo/ec-cube
 /**
  * パスワードリマインダ.
  *
  * @param Application $app
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  */
 public function index(Application $app, Request $request)
 {
     $builder = $app['form.factory']->createNamedBuilder('', 'forgot');
     $event = new EventArgs(array('builder' => $builder), $request);
     $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_FORGOT_INDEX_INITIALIZE, $event);
     $form = $builder->getForm();
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $Customer = $app['eccube.repository.customer']->getActiveCustomerByEmail($form->get('login_email')->getData());
         if (!is_null($Customer)) {
             // リセットキーの発行・有効期限の設定
             $Customer->setResetKey($app['eccube.repository.customer']->getUniqueResetKey($app))->setResetExpire(new \DateTime('+' . $app['config']['customer_reset_expire'] . ' min'));
             // リセットキーを更新
             $app['orm.em']->persist($Customer);
             $app['orm.em']->flush();
             $event = new EventArgs(array('form' => $form, 'Customer' => $Customer), $request);
             $app['eccube.event.dispatcher']->dispatch(EccubeEvents::FRONT_FORGOT_INDEX_COMPLETE, $event);
             // 完了URLの生成
             $reset_url = $app->url('forgot_reset', array('reset_key' => $Customer->getResetKey()));
             // メール送信
             $app['eccube.service.mail']->sendPasswordResetNotificationMail($Customer, $reset_url);
             // ログ出力
             $app['monolog']->addInfo('send reset password mail to:' . "{$Customer->getId()} {$Customer->getEmail()} {$request->getClientIp()}");
         } else {
             log_warning('Un active customer try send reset password email: ', array('Enter email' => $form->get('login_email')->getData()));
         }
         return $app->redirect($app->url('forgot_complete'));
     }
     return $app->render('Forgot/index.twig', array('form' => $form->createView()));
 }
コード例 #4
0
 /**
  *  load config
  *
  * @param  string|Charcoal_String $key                  config key
  *
  * @return mixed   configure data
  */
 public function loadConfig($key)
 {
     //        Charcoal_ParamTrait::validateString( 1, $key );
     $source = $key . '.ini';
     $is_debug = b($this->debug)->isTrue();
     $result = NULL;
     if (!is_file($source)) {
         if ($is_debug) {
             print "ini file[{$source}] does not exist." . eol();
             log_warning("system, debug, config", "config", "ini file[{$source}] does not exist.");
         }
     } else {
         // read ini file
         $result = @parse_ini_file($source, TRUE);
         if ($is_debug) {
             print "[{$source}] parse_ini_file({$source})=" . eol();
             ad($result);
             if ($result === FALSE) {
                 print "parse_ini_file failed: [{$source}]" . eol();
                 log_warning("system, debug, config", "config", "parse_ini_file failed: [{$source}]");
             } else {
                 log_debug("system, debug, config", "config", "read ini file[{$source}]:" . print_r($result, true));
             }
         }
     }
     return $result;
 }
コード例 #5
0
 /**
  * execute exception handlers
  *
  * @param Exception $e     exception to handle
  *
  * @return boolean        TRUE means the exception is handled, otherwise FALSE
  */
 public function handleException($e)
 {
     Charcoal_ParamTrait::validateException(1, $e);
     if ($e instanceof Charcoal_HttpStatusException) {
         $status_code = $e->getStatusCode();
         // Show HTTP error document
         self::showHttpErrorDocument($status_code);
         log_warning('system,error', 'exception', "http_exception: status_code={$status_code}");
         return TRUE;
     }
     return FALSE;
 }
コード例 #6
0
 protected function blockComment()
 {
     if (starts_with($this->line, '//')) {
         $this->interrupted = true;
     } elseif (starts_with($this->line, '#')) {
         log_warning('Using the # symbol for comments is deprecated');
         $this->interrupted = true;
     } elseif (starts_with($this->line, '/*')) {
         if (ends_with($this->line, '*/')) {
             return null;
         }
         $this->isComment = true;
     } elseif (ends_with($this->line, '*/')) {
         $this->isComment = false;
     }
 }
コード例 #7
0
 public static function loadModule($sandbox, $module_path, $task_manager)
 {
     //        Charcoal_ParamTrait::validateSandbox( 1, $sandbox );
     //        Charcoal_ParamTrait::validateStringOrObjectPath( 2, $module_path );
     //        Charcoal_ParamTrait::validateImplements( 3, 'Charcoal_ITaskManager', $task_manager );
     try {
         log_debug('debug, event', "loading module: {$module_path}");
         if ($module_path instanceof Charcoal_ObjectPath) {
             $module_path = $module_path->toString();
         } else {
             $module_path = us($module_path);
         }
         // check if module is already loaded
         if (isset(self::$loaded_paths[$module_path])) {
             log_warning('system, event, debug', "module[{$module_path}] is already loaded.");
             return;
         }
         /** @var Charcoal_IModule $module */
         /** @var Charcoal_Sandbox $sandbox */
         $module = $sandbox->createObject($module_path, 'module', array(), 'Charcoal_IModule', 'Charcoal_SimpleModule');
         // load module tasks
         $loaded_tasks = $module->loadTasks($task_manager);
         // load module events source code
         $loaded_events = $module->loadEvents($task_manager);
         // if no tasks or events are loaded, you maybe passed a wrong module path
         if (empty($loaded_tasks) && empty($loaded_events)) {
             _throw(new Charcoal_ModuleLoaderException($module_path, "no tasks and events are loaded."));
         }
         // load required modules
         $required_modules = $module->getRequiredModules();
         if ($required_modules) {
             $loaded_modules = NULL;
             foreach ($required_modules as $module_name) {
                 if (strlen($module_name) === 0) {
                     continue;
                 }
                 self::loadModule($sandbox, $module_name, $task_manager);
             }
         }
         self::$loaded_paths[$module_path] = $module_path;
         log_debug('debug, event, module', "loaded module: {$module_path}");
     } catch (Exception $ex) {
         _catch($ex);
         _throw(new Charcoal_ModuleLoaderException($module_path, "failed to load  module.", $ex));
     }
 }
コード例 #8
0
ファイル: error.lib.php プロジェクト: romlg/cms36
function Engine_ErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
        case E_ERROR:
            log_error($errstr, $errfile, $errline);
            break;
        case E_PARSE:
            log_error($errstr, $errfile, $errline);
            break;
        case E_WARNING:
            log_warning($errstr, $errfile, $errline);
            break;
        case E_NOTICE:
            log_notice($errstr, $errfile, $errline);
            break;
        default:
            log_notice($errstr, $errfile, $errline);
    }
}
コード例 #9
0
ファイル: geoutils.php プロジェクト: nateforsyth/openheatmap
function read_csv_file_from_handle($file_handle, $seperator)
{
    $result = array();
    $column_names = array();
    $line_index = 0;
    while (!feof($file_handle)) {
        $current_parts = fgetcsv($file_handle, 0, $seperator);
        if (empty($current_parts)) {
            continue;
        }
        $line_index += 1;
        if ($line_index < 2) {
            $seperators = array("\t", ";", "|");
            foreach ($seperators as $seperator_candidate) {
                if (count($current_parts) >= 2) {
                    continue;
                }
                $seperator = $seperator_candidate;
                rewind($file_handle);
                $current_parts = fgetcsv($file_handle, 0, $seperator);
            }
            $column_names = array_map('trim', $current_parts);
            continue;
        }
        $row = array();
        $column_index = 0;
        foreach ($column_names as $column_name) {
            if (!empty($column_name)) {
                if (isset($current_parts[$column_index])) {
                    $row[$column_name] = $current_parts[$column_index];
                } else {
                    $row[$column_name] = null;
                    log_warning($line_index, "No value found in the '{$column_name}' column", 'http://wiki.github.com/petewarden/openheatmap/no-value-found-in-column');
                }
            }
            $column_index += 1;
        }
        $result[] = $row;
    }
    return $result;
}
コード例 #10
0
 /**
  * Lookup routing rules
  *
  * @return array returns combined array, FALSE if any pattern is matched.
  */
 public function route(Charcoal_IRequest $request, Charcoal_IRoutingRule $rule)
 {
     // Get path info
     //$request_uri = $_SERVER["REQUEST_URI"];
     //$script_name = $_SERVER["SCRIPT_NAME"];
     //$dir_name    = dirname($script_name);
     //$pos = strpos( $request_uri, $dir_name );
     //$url = substr( $request_uri, $pos + strlen($dir_name) );
     $url = rtrim($_SERVER["REQUEST_URI"], '/');
     log_info('debug,router', "routing started. URL=[{$url}]");
     $proc_key = $this->getSandbox()->getProfile()->getString('PROC_KEY', 'proc');
     $rule_keys = $rule->getKeys();
     if ($rule_keys && is_array($rule_keys)) {
         log_info('debug,router', "rule keys=[" . implode(",", $rule_keys) . "]");
         foreach ($rule_keys as $pattern) {
             $proc = $rule->getProcPath(s($pattern));
             log_info('debug,router', "pattern=[{$pattern}] proc=[{$proc}]");
             if ($proc) {
                 log_info('debug,router', "testing pattern=[{$pattern}] url=[{$url}]");
                 $params = self::_match($pattern, $url);
                 log_info('debug,router', "params:" . print_r($params, true));
                 // match
                 if ($params !== NULL) {
                     $request->setArray($params);
                     $request->set($proc_key, $proc);
                     log_info('debug,router', "routing rule matched! pattern=[{$pattern}] proc_path=[{$proc}]");
                     $result = array('proc' => $proc, 'params' => $params, 'pattern' => $pattern);
                     return $result;
                 }
             }
         }
         log_warning('system,debug,router', "no routing rule is matched.");
     } else {
         log_warning('system,debug,router', "routing rule are not defined.");
     }
     return FALSE;
 }
コード例 #11
0
 /**
  *    Get cache data
  *
  * @param Charcoal_String $key                   string name to identify cached data
  * @param Charcoal_String $type_name_checked     checks type(class/interface) if not NULL
  */
 public function getCache($key, Charcoal_String $type_name_checked = NULL)
 {
     //        Charcoal_ParamTrait::validateString( 1, $key );
     //        Charcoal_ParamTrait::validateString( 2, $type_name_checked, TRUE );
     try {
         $type_name_checked = us($type_name_checked);
         $cached_data = Charcoal_Cache::get($key);
         $type_check = $cached_data instanceof Charcoal_Object;
         if (!$type_check) {
             $actual_type = get_class($cached_data);
             log_warning("system, debug, cache", "cache", "cache type mismatch: expected=[Charcoal_Object] actual=[{$actual_type}]");
             return FALSE;
         }
         if ($cached_data !== FALSE && $type_name_checked !== NULL) {
             $type_check = $cached_data instanceof $type_name_checked;
             if (!$type_check) {
                 $actual_type = get_class($cached_data);
                 log_warning("system, debug, cache", "cache", "cache type mismatch: expected=[{$type_name_checked}] actual=[{$actual_type}]");
                 return FALSE;
             }
         }
         return $cached_data;
     } catch (Exception $ex) {
         _catch($ex);
         _throw(new Charcoal_EventContextException(__METHOD__ . '() failed.', $ex));
     }
 }
コード例 #12
0
ファイル: Log.php プロジェクト: jokopurnomoa/elips-php
 /**
  * Warning logging
  * 
  * @param string $message
  */
 public static function warning($message)
 {
     log_warning($message);
 }
コード例 #13
0
ファイル: parse.php プロジェクト: erico-deh/ocPortal
function handle_comment($comment)
{
    global $OK_EXTRA_FUNCTIONS;
    if (substr($comment[1], 0, 17) == 'EXTRA FUNCTIONS: ') {
        $OK_EXTRA_FUNCTIONS = substr($comment[1], 17);
    }
    if (isset($GLOBALS['TODO'])) {
        if (strpos($comment[1], 'TODO') !== false) {
            log_warning('TODO comment found', $GLOBALS['i']);
        }
        if (strpos($comment[1], 'HACKHACK') !== false) {
            log_warning('HACKHACK comment found', $GLOBALS['i']);
        }
        if (strpos($comment[1], 'FIXME') !== false) {
            log_warning('FIXME comment found', $GLOBALS['i']);
        }
    }
}
コード例 #14
0
 /**
  *   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;
 }
コード例 #15
0
ファイル: main.php プロジェクト: JarJak/shimmie2
 /**
  * @param Page $page
  * @param bool $with_images
  * @param bool $with_comments
  */
 private function delete_user(Page $page, $with_images = false, $with_comments = false)
 {
     global $user, $config, $database;
     $page->set_title("Error");
     $page->set_heading("Error");
     $page->add_block(new NavBlock());
     if (!$user->can("delete_user")) {
         $page->add_block(new Block("Not Admin", "Only admins can delete accounts"));
     } else {
         if (!isset($_POST['id']) || !is_numeric($_POST['id'])) {
             $page->add_block(new Block("No ID Specified", "You need to specify the account number to edit"));
         } else {
             log_warning("user", "Deleting user #{$_POST['id']}");
             if ($with_images) {
                 log_warning("user", "Deleting user #{$_POST['id']}'s uploads");
                 $rows = $database->get_all("SELECT * FROM images WHERE owner_id = :owner_id", array("owner_id" => $_POST['id']));
                 foreach ($rows as $key => $value) {
                     $image = Image::by_id($value['id']);
                     if ($image) {
                         send_event(new ImageDeletionEvent($image));
                     }
                 }
             } else {
                 $database->Execute("UPDATE images SET owner_id = :new_owner_id WHERE owner_id = :old_owner_id", array("new_owner_id" => $config->get_int('anon_id'), "old_owner_id" => $_POST['id']));
             }
             if ($with_comments) {
                 log_warning("user", "Deleting user #{$_POST['id']}'s comments");
                 $database->execute("DELETE FROM comments WHERE owner_id = :owner_id", array("owner_id" => $_POST['id']));
             } else {
                 $database->Execute("UPDATE comments SET owner_id = :new_owner_id WHERE owner_id = :old_owner_id", array("new_owner_id" => $config->get_int('anon_id'), "old_owner_id" => $_POST['id']));
             }
             send_event(new UserDeletionEvent($_POST['id']));
             $database->execute("DELETE FROM users WHERE id = :id", array("id" => $_POST['id']));
             $page->set_mode("redirect");
             $page->set_redirect(make_link("post/list"));
         }
     }
 }
コード例 #16
0
ファイル: lex.php プロジェクト: erico-deh/ocPortal
function lex($text = NULL)
{
    global $PCONTINUATIONS, $PCONTINUATIONS_SIMPLE, $PTOKENS, $TEXT;
    if (!is_null($text)) {
        $TEXT = $text;
    }
    // ocPortal doesn't make use of this, so no need to understand it
    $matches = array();
    if (strpos($TEXT, '<' . '?php') === false) {
        if (strpos($TEXT, '<' . '?') !== false) {
            if (strpos($TEXT, '?' . '>') !== false) {
                log_warning('It is best to only have one PHP code block and not to terminate it. This stops problems with white-space at the end of files.');
            } else {
                $TEXT .= '?' . '>';
            }
            log_warning('Use "<' . '?php" tagging for compatibility.');
            $num_matches = preg_match_all('#<\\?(.*)\\?' . '>#sU', $TEXT, $matches, PREG_OFFSET_CAPTURE);
        } elseif (strpos($TEXT, '<' . '%') !== false) {
            if (strpos($TEXT, '%' . '>') !== false) {
                log_warning('It is best to only have one PHP code block and not to terminate it. This stops problems with white-space at the end of files.');
            } else {
                $TEXT .= '%>';
            }
            log_warning('Use "<' . '?php" tagging for compatibility.');
            $num_matches = preg_match_all('#<%(.*)\\%>#sU', $TEXT, $matches, PREG_OFFSET_CAPTURE);
        } else {
            $num_matches = 0;
        }
    } else {
        if (strpos($TEXT, '?' . '>') !== false) {
            log_warning('It is best to only have one PHP code block and not to terminate it. This stops problems with white-space at the end of files.');
        } else {
            $TEXT .= '?' . '>';
        }
        $num_matches = preg_match_all('#<\\?php(.*)\\?' . '>#s', $TEXT, $matches, PREG_OFFSET_CAPTURE);
        // TODO: Put U back. I had to take it out because some kind of limit seemed to get hit with how much matching can be done with it on.
    }
    $new_text = '';
    $between_all = '';
    $extra_skipped = 0;
    $last_m = NULL;
    for ($i = 0; $i < $num_matches; $i++) {
        $m = $matches[1][$i];
        if (is_string($m)) {
            continue;
        } else {
            $between = substr($TEXT, strlen($new_text) + $extra_skipped, $m[1] - 5 - strlen($new_text) - $extra_skipped);
            $extra_skipped += 7;
            $between_all .= $between;
            $new_text .= preg_replace('#[^\\n]#s', ' ', $between);
            $new_text .= $m[0];
            $last_m = $m;
        }
    }
    if (!is_null($last_m)) {
        $between = substr($TEXT, $last_m[1] + strlen($last_m[0]) + 2);
        $between_all .= $between;
        $new_text .= preg_replace('#[^\\n]#', ' ', $between);
    }
    if ($num_matches == 0) {
        $between_all = $TEXT;
    }
    $TEXT = $new_text;
    if (trim($between_all) != '' && isset($GLOBALS['FILENAME'])) {
        global $WITHIN_PHP;
        $WITHIN_PHP = $num_matches != 0;
        require 'xhtml.php';
    }
    // So that we don't have to consider end-of-file states as much.
    $TEXT .= "\n";
    $tokens = array();
    // We will be lexing into this list of tokens
    $special_token_value = '';
    // This will be used during special lexing modes to build up the special token value being lexed
    $special_token_value_2 = '';
    $previous_state = NULL;
    $lex_state = PLEXER_FREE;
    $escape_flag = false;
    // Used for string_literal escaping
    $heredoc_simple = false;
    $heredoc_buildup = array();
    $heredoc_symbol = '';
    $tokens_since_comment = 0;
    $indentation = 0;
    $new_line = false;
    $brace_stack = array();
    // Lex the code. Hard coded state changes occur. Understanding of tokenisation implicit. Trying to match tokens to $PTOKENS, otherwise an identifier.
    $char = '';
    $i = 0;
    $len = strlen($TEXT);
    while (true) {
        switch ($lex_state) {
            case PLEXER_FREE:
                // Jump over any white space in our way
                do {
                    $previous_char = $char;
                    list($reached_end, $i, $char) = plex__get_next_char($i);
                    if ($reached_end) {
                        break 3;
                    }
                    if ($new_line) {
                        if ($char == ' ') {
                            $indentation++;
                        } elseif ($char == "\t") {
                            $indentation += 3;
                        }
                    }
                    if ($char == chr(10)) {
                        $indentation = 0;
                        $new_line = true;
                    }
                } while (trim($char) == '');
                if (trim($previous_char) == '') {
                    if ($char == '{') {
                        if (!$new_line) {
                            log_warning('Bracing error (type 2/1) ', $i, true);
                        }
                        array_push($brace_stack, $indentation);
                    } elseif ($char == '}') {
                        if (!$new_line) {
                            log_warning('Bracing error (type 2/2) ', $i, true);
                        }
                        $past_indentation = array_pop($brace_stack);
                        if ($past_indentation != $indentation) {
                            log_warning('Bracing error (' . $past_indentation . ' vs ' . strval($indentation) . ')', $i, true);
                        }
                    }
                }
                if ($new_line && $indentation % (isset($GLOBALS['NON_TERSE']) ? 4 : 3) != 0) {
                    log_warning('Bad indentation according to coding standards', $i, true);
                }
                $new_line = false;
                // We need to know where our token is starting
                $i--;
                $i_current = $i;
                // Try and work out what token we're looking at next
                $maybe_applicable_tokens = $PTOKENS;
                $applicable_tokens = array();
                $token_so_far = '';
                while (count($maybe_applicable_tokens) != 0) {
                    list($reached_end, $i, $char) = plex__get_next_char($i);
                    if ($reached_end) {
                        break 3;
                    }
                    $token_so_far .= $char;
                    // Filter out any tokens that no longer match
                    foreach ($maybe_applicable_tokens as $token_name => $token_value) {
                        // Hasn't matched (or otherwise, may still match)
                        if (substr($token_value, 0, strlen($token_so_far)) != $token_so_far) {
                            unset($maybe_applicable_tokens[$token_name]);
                        } else {
                            // Is it a perfect match?
                            if (strlen($token_so_far) == strlen($token_value) && (!in_array($token_so_far[0], $PCONTINUATIONS) || !in_array($TEXT[$i], $PCONTINUATIONS))) {
                                $applicable_tokens[] = $token_name;
                                unset($maybe_applicable_tokens[$token_name]);
                            }
                        }
                    }
                }
                // If we have any applicable tokens, find the longest and move $i so it's as we just read it
                $i = $i_current;
                if (count($applicable_tokens) != 0) {
                    usort($applicable_tokens, 'plex__strlen_sort');
                    $token_found = $applicable_tokens[count($applicable_tokens) - 1];
                    $i += strlen($PTOKENS[$token_found]);
                    // Is it a special state jumping token?
                    if ($token_found == 'VARIABLE') {
                        $lex_state = PLEXER_VARIABLE;
                        break;
                    } elseif ($token_found == 'START_HEREDOC') {
                        $lex_state = PLEXER_HEREDOC;
                        $matches = array();
                        preg_match('#[A-Za-z0-9\\_]*#', substr($TEXT, $i, 30), $matches);
                        $heredoc_symbol = $matches[0];
                        $i += strlen($heredoc_symbol);
                        break;
                    } elseif ($token_found == 'START_ML_COMMENT') {
                        $lex_state = PLEXER_ML_COMMENT;
                        break;
                    } elseif ($token_found == 'COMMENT') {
                        $lex_state = PLEXER_COMMENT;
                        break;
                    } elseif ($token_found == 'DOUBLE_QUOTE') {
                        $lex_state = PLEXER_DOUBLE_QUOTE_STRING_LITERAL;
                        break;
                    } elseif ($token_found == 'SINGLE_QUOTE') {
                        $lex_state = PLEXER_SINGLE_QUOTE_STRING_LITERAL;
                        break;
                    } else {
                        if (!in_array($token_found, array('COMMA', 'DOUBLE_ARROW'))) {
                            $tokens_since_comment++;
                            if (isset($GLOBALS['pedantic']) && $tokens_since_comment > 200) {
                                log_warning('Bad comment density', $i, true);
                                $tokens_since_comment = 0;
                            }
                        }
                    }
                    if ($token_found == 'IF' && @$tokens[count($tokens) - 1][0] == 'ELSE') {
                        log_warning('Use \'elseif\' not \'else if\'', $i, true);
                    }
                    /*$terse_style=!isset($GLOBALS['NON_TERSE']); TODO Maybe put back, but should be optional
                    		if ($terse_style)
                    		{
                    			if (($i_current>0) && ($TEXT{$i_current-1}==' ') && (in_array($token_found,array('COMMA','IS_EQUAL','IS_GREATER','IS_SMALLER','IS_GREATER_OR_EQUAL','IS_SMALLER_OR_EQUAL','IS_IDENTICAL','IS_NOT_EQUAL','IS_NOT_IDENTICAL','CONCAT_EQUAL','DIV_EQUAL','MINUS_EQUAL','MUL_EQUAL','PLUS_EQUAL','BOR_EQUAL','EQUAL','COMMA','BW_XOR','BW_OR','SL','SR','CONC','ADD','SUBTRACT','MULTIPLY','DIVIDE','REMAINDER','OBJECT_OPERATOR')))) log_warning('Superfluous spacing (for '.$token_found.') against coding standards',$i,true);
                    		} else
                    		{
                    			if (($i_current>0) && ($TEXT{$i_current-1}==' ') && (in_array($token_found,array('OBJECT_OPERATOR')))) log_warning('Superfluous spacing (for '.$token_found.') against coding standards',$i,true);
                    			if (($i_current>0) && (($TEXT{$i}!=' ') && ($TEXT{$i}!=chr(10)) && ($TEXT{$i}!=chr(13))) && (in_array($token_found,array('COMMA')))) log_warning('Missing surrounding spacing (for '.$token_found.') against coding standards',$i,true);
                    			if (($i_current>0) && (($TEXT{$i_current-1}!=' ') || (($TEXT{$i}!=' ') && ($TEXT{$i}!=chr(10)) && ($TEXT{$i}!=chr(13)))) && (in_array($token_found,array('IS_EQUAL','IS_GREATER','IS_SMALLER','IS_GREATER_OR_EQUAL','IS_SMALLER_OR_EQUAL','IS_IDENTICAL','IS_NOT_EQUAL','IS_NOT_IDENTICAL','CONCAT_EQUAL','DIV_EQUAL','MINUS_EQUAL','MUL_EQUAL','PLUS_EQUAL','BOR_EQUAL','EQUAL','COMMA','BW_XOR','BW_OR','SL','SR','CONC','ADD','SUBTRACT','MULTIPLY','DIVIDE','REMAINDER')))) log_warning('Missing surrounding spacing (for '.$token_found.') against coding standards',$i,true);
                    		}
                    		if (($TEXT{$i}!=' ') && ($TEXT{$i}!=chr(10)) && ($TEXT{$i}!=chr(13)) && (in_array($token_found,array('IF','ELSEIF','FOREACH','FOR','WHILE','DO')))) log_warning('Missing following spacing (for '.$token_found.') against coding standards',$i,true);
                    		if (($i_current>0) && (($TEXT{$i_current-1}!=' ') || (($TEXT{$i}!=' ') && ($TEXT{$i}!=chr(10)) && ($TEXT{$i}!=chr(13)))) && (in_array($token_found,array('BOOLEAN_AND','BOOLEAN_XOR','BOOLEAN_OR','BOOLEAN_OR_2')))) log_warning('Missing surrounding spacing (for '.$token_found.') against coding standards',$i,true);*/
                    $tokens[] = array($token_found, $i);
                } else {
                    // Otherwise, we've found an identifier or numerical literal token, so extract it
                    $token_found = '';
                    $numeric = NULL;
                    do {
                        list($reached_end, $i, $char) = plex__get_next_char($i);
                        if ($reached_end) {
                            break 3;
                        }
                        if (is_null($numeric)) {
                            $numeric = in_array($char, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'));
                        }
                        if (!in_array($char, $PCONTINUATIONS) && ($numeric === false || $char != '.' || !is_numeric($TEXT[$i]))) {
                            break;
                        }
                        $token_found .= $char;
                    } while (true);
                    $i--;
                    if ($numeric) {
                        if (strpos($token_found, '.') !== false) {
                            $tokens[] = array('float_literal', floatval($token_found), $i);
                        } elseif (strpos($token_found, 'x') !== false) {
                            $tokens[] = array('integer_literal', intval($token_found, 16), $i);
                        } elseif ($token_found[0] == '0') {
                            $tokens[] = array('integer_literal', intval($token_found, 8), $i);
                        } else {
                            $tokens[] = array('integer_literal', intval($token_found), $i);
                        }
                    } else {
                        if ($token_found == '') {
                            log_warning('Bad token found', $i, true);
                            exit;
                        }
                        $tokens[] = array('IDENTIFIER', $token_found, $i);
                    }
                }
                //print_r($tokens[count($tokens)-1]);
                //echo '<br />';
                //flush();
                break;
            case PLEXER_VARIABLE:
                list($reached_end, $i, $char) = plex__get_next_char($i);
                if ($reached_end) {
                    break 2;
                }
                // Exit case
                if (!in_array($char, $PCONTINUATIONS)) {
                    $lex_state = PLEXER_FREE;
                    $tokens[] = array('variable', $special_token_value, $i);
                    $special_token_value = '';
                    $i--;
                    break;
                }
                // Normal case
                $special_token_value .= $char;
                break;
            case PLEXER_HEREDOC:
                list($reached_end, $i, $char) = plex__get_next_chars($i, strlen($heredoc_symbol) + 2);
                // Exit case
                if ($char == chr(10) . $heredoc_symbol . ';') {
                    $lex_state = PLEXER_FREE;
                    if (isset($GLOBALS['CHECKS']) && preg_match('#\\<[^\\<\\>]*\\>#', $special_token_value) != 0) {
                        log_warning('It looks like HTML used outside of templates', $i, true);
                    }
                    $tokens[] = array('string_literal', $special_token_value, $i);
                    $tokens[] = array('COMMAND_TERMINATE', $i);
                    if (isset($GLOBALS['CHECKS']) && isset($GLOBALS['PEDANTIC']) && strpos($special_token_value, '<') !== false && strpos($special_token_value, '<') != strlen($special_token_value) - 1) {
                        log_warning('Should\'t this be templated?', $i, true);
                    }
                    $special_token_value = '';
                    break;
                }
                $i -= strlen($heredoc_symbol) + 1;
                if (!isset($char[0])) {
                    break 2;
                }
                $char = $char[0];
                // Escape flag based filtering
                $actual_char = $char;
                if ($escape_flag) {
                    if ($char == '$') {
                        $actual_char = '$';
                    } elseif ($char == '{') {
                        $actual_char = '{';
                    } elseif ($char == '}') {
                        $actual_char = '}';
                    } else {
                        $actual_char = '\\' . $char;
                    }
                } else {
                    $heredoc_simple = !($char == '{' && $TEXT[$i] == '$' || $char == '$' && $TEXT[$i] == '{');
                    if ($char == '$' || !$heredoc_simple) {
                        if (!$heredoc_simple) {
                            $i++;
                        }
                        $tokens[] = array('string_literal', $special_token_value, $i);
                        $tokens[] = array('CONC', $i);
                        $special_token_value = '';
                        $lex_state = PLEXER_EMBEDDED_VARIABLE;
                        $previous_state = PLEXER_HEREDOC;
                        $heredoc_buildup = array();
                        break;
                    } elseif ($char == '\\' || $char == '{') {
                        $actual_char = '';
                    }
                    // Technically we should only allow "$whatever" if whatever exists, but this future proofs checked code
                }
                // Normal case
                $special_token_value .= $actual_char;
                $escape_flag = !$escape_flag && $char == '\\';
                break;
            case PLEXER_EMBEDDED_VARIABLE:
                list($reached_end, $i, $char) = plex__get_next_char($i);
                if ($reached_end) {
                    break 2;
                }
                if (!in_array($char, $heredoc_simple ? $PCONTINUATIONS_SIMPLE : $PCONTINUATIONS)) {
                    $exit = false;
                    if (!$heredoc_simple) {
                        // Complex
                        if ($char == '}') {
                            $exit = true;
                        } else {
                            $matches = array();
                            if ($char == '[' && $TEXT[$i] == '\'' && preg_match('#^\\[\'([^\']*)\'\\]#', substr($TEXT, $i - 1, 40), $matches) != 0) {
                                $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                                $special_token_value_2 = '';
                                $heredoc_buildup[] = array('EXTRACT_OPEN', $i);
                                $heredoc_buildup[] = array('string_literal', $matches[1], $i);
                                $heredoc_buildup[] = array('EXTRACT_CLOSE', $i);
                                $i += strlen($matches[1]) + 3;
                            } elseif ($char == '[' && preg_match('#^\\[([A-Za-z0-9\\_]+)\\]#', substr($TEXT, $i - 1, 40), $matches) != 0) {
                                $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                                $special_token_value_2 = '';
                                $heredoc_buildup[] = array('EXTRACT_OPEN', $i);
                                $heredoc_buildup[] = array('IDENTIFIER', $matches[1], $i);
                                $heredoc_buildup[] = array('EXTRACT_CLOSE', $i);
                                $i += strlen($matches[1]) + 1;
                            } elseif ($char == '-' && $TEXT[$i] == '>') {
                                $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                                $special_token_value_2 = '';
                                $heredoc_buildup[] = array('OBJECT_OPERATOR', $i);
                                $i++;
                            } else {
                                log_warning('Bad token found', $i, true);
                                exit;
                            }
                        }
                    } else {
                        // Simple
                        $matches = array();
                        if ($char == '-' && $TEXT[$i] == '>') {
                            $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                            $special_token_value_2 = '';
                            $heredoc_buildup[] = array('OBJECT_OPERATOR', $i);
                            $i++;
                        } elseif ($char == '[' && preg_match('#^\\[([\'A-Za-z0-9\\_]+)\\]#', substr($TEXT, $i - 1, 40), $matches) != 0) {
                            if (strpos($matches[1], "'") !== false) {
                                log_warning('Do not use quotes with the simple variable embedding syntax', $i, true);
                                exit;
                            }
                            $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                            $special_token_value_2 = '';
                            $heredoc_buildup[] = array('EXTRACT_OPEN', $i);
                            $heredoc_buildup[] = array('string_literal', $matches[1], $i);
                            $heredoc_buildup[] = array('EXTRACT_CLOSE', $i);
                            $i += strlen($matches[1]) + 1;
                        } else {
                            $exit = true;
                        }
                    }
                    if ($exit) {
                        $lex_state = $previous_state;
                        if ($special_token_value_2 != '') {
                            $heredoc_buildup[] = array(count($heredoc_buildup) == 0 ? 'variable' : 'IDENTIFIER', $special_token_value_2, $i);
                        }
                        if (count($heredoc_buildup) > 0) {
                            $tokens[] = array('IDENTIFIER', 'strval', $i);
                            $tokens[] = array('BRACKET_OPEN', $i);
                            $tokens = array_merge($tokens, $heredoc_buildup);
                            $tokens[] = array('BRACKET_CLOSE', $i);
                            $tokens[] = array('CONC', $i);
                        }
                        $special_token_value_2 = '';
                        if ($heredoc_simple) {
                            $i--;
                        }
                        break;
                    }
                } else {
                    // Normal case
                    $special_token_value_2 .= $char;
                }
                break;
            case PLEXER_COMMENT:
                $tokens_since_comment = 0;
                list($reached_end, $i, $char) = plex__get_next_char($i);
                if ($reached_end) {
                    break 2;
                }
                // Exit case
                if ($char == chr(10)) {
                    $lex_state = PLEXER_FREE;
                    $tokens[] = array('comment', $special_token_value, $i);
                    $special_token_value = '';
                    $i--;
                    break;
                }
                // Normal case
                $special_token_value .= $char;
                break;
            case PLEXER_ML_COMMENT:
                $tokens_since_comment = 0;
                list($reached_end, $i, $char) = plex__get_next_chars($i, 2);
                // Exit case
                if ($char == '*/') {
                    $lex_state = PLEXER_FREE;
                    $tokens[] = array('comment', $special_token_value, $i);
                    $special_token_value = '';
                    break;
                }
                $i -= 1;
                if (!isset($char[0])) {
                    break 2;
                }
                $char = $char[0];
                // Normal case
                $special_token_value .= $char;
                break;
            case PLEXER_DOUBLE_QUOTE_STRING_LITERAL:
                list($reached_end, $i, $char) = plex__get_next_char($i);
                if ($reached_end) {
                    break 2;
                }
                // Exit case
                if ($char == '"' && !$escape_flag) {
                    $lex_state = PLEXER_FREE;
                    $tokens[] = array('string_literal', $special_token_value, $i);
                    if (isset($GLOBALS['CHECKS']) && isset($GLOBALS['PEDANTIC']) && strpos($special_token_value, '<') !== false && strpos($special_token_value, '<') != strlen($special_token_value) - 1) {
                        log_warning('Should\'t this be templated?', $i, true);
                    }
                    $special_token_value = '';
                    break;
                }
                // Escape flag based filtering
                $actual_char = $char;
                if ($escape_flag) {
                    if ($char == 'n') {
                        $actual_char = "\n";
                    } elseif ($char == 'r') {
                        $actual_char = "\r";
                    } elseif ($char == 't') {
                        $actual_char = "\t";
                    }
                } else {
                    $heredoc_simple = !($char == '{' && $TEXT[$i] == '$' || $char == '$' && $TEXT[$i] == '{');
                    if ($char == '$' || !$heredoc_simple) {
                        if (!$heredoc_simple) {
                            $i++;
                        }
                        $tokens[] = array('string_literal', $special_token_value, $i);
                        $tokens[] = array('CONC', $i);
                        $special_token_value = '';
                        $lex_state = PLEXER_EMBEDDED_VARIABLE;
                        $previous_state = PLEXER_DOUBLE_QUOTE_STRING_LITERAL;
                        $heredoc_buildup = array();
                        break;
                    }
                    if ($char == '\\') {
                        $actual_char = '';
                    }
                }
                // Normal case
                $special_token_value .= $actual_char;
                $escape_flag = !$escape_flag && $char == '\\';
                break;
            case PLEXER_SINGLE_QUOTE_STRING_LITERAL:
                list($reached_end, $i, $char) = plex__get_next_char($i);
                if ($reached_end) {
                    break 2;
                }
                // Exit case
                if ($char == "'" && !$escape_flag) {
                    $lex_state = PLEXER_FREE;
                    $tokens[] = array('string_literal', $special_token_value, $i);
                    if (isset($GLOBALS['CHECKS']) && isset($GLOBALS['PEDANTIC']) && strpos($special_token_value, '<') !== false && strpos($special_token_value, '<') != strlen($special_token_value) - 1) {
                        log_warning('Should\'t this be templated?', $i, true);
                    }
                    $special_token_value = '';
                    break;
                }
                // Escape flag based filtering
                $actual_char = $char;
                if ($escape_flag) {
                    if ($char == "'") {
                        $actual_char = "'";
                    } elseif ($char == '\\') {
                        $actual_char = '\\';
                    } else {
                        $actual_char = '\\' . $char;
                    }
                } elseif ($char == '\\') {
                    $actual_char = '';
                }
                // Normal case
                $special_token_value .= $actual_char;
                $escape_flag = !$escape_flag && $char == '\\';
                break;
        }
    }
    return $tokens;
}
コード例 #17
0
ファイル: main.php プロジェクト: thelectronicnub/shimmie2
 public function onConfigSave(ConfigSaveEvent $event)
 {
     global $config;
     foreach ($_POST as $_name => $junk) {
         if (substr($_name, 0, 6) == "_type_") {
             $name = substr($_name, 6);
             $type = $_POST["_type_{$name}"];
             $value = isset($_POST["_config_{$name}"]) ? $_POST["_config_{$name}"] : null;
             switch ($type) {
                 case "string":
                     $config->set_string($name, $value);
                     break;
                 case "int":
                     $config->set_int($name, $value);
                     break;
                 case "bool":
                     $config->set_bool($name, $value);
                     break;
                 case "array":
                     $config->set_array($name, $value);
                     break;
             }
         }
     }
     log_warning("setup", "Configuration updated");
     foreach (glob("data/cache/*.css") as $css_cache) {
         unlink($css_cache);
     }
     log_warning("setup", "Cache cleared");
 }
コード例 #18
0
 /**
  * process event
  *
  * @param Charcoal_IEventContext $context   event context
  *
  * @return Charcoal_Boolean|bool
  */
 public function processEvent($context)
 {
     $request = $context->getRequest();
     //        $response  = $context->getResponse();
     //        $sequence  = $context->getSequence();
     //        $procedure = $context->getProcedure();
     echo PHP_EOL;
     echo "==========================================" . PHP_EOL;
     echo "CharcoalPHP Test Runner" . PHP_EOL;
     echo "   Framework Version:" . Charcoal_Framework::getVersion() . PHP_EOL;
     echo "==========================================" . PHP_EOL;
     // get paramter from command line
     $scenario = $request->getString('scenario');
     $scenario = trim($scenario);
     log_debug("debug,scenario", "scenario: {$scenario}");
     if ($scenario === NULL) {
         echo "actions or scenario parameter must be specified." . PHP_EOL;
         log_error("debug,error,scenario", "actions or scenario parameter must be specified.");
         return TRUE;
     }
     $scenario_file = $this->scenario_dir . '/' . $scenario . '.scenario.ini';
     if (!is_file($scenario_file)) {
         echo "scenario file not found: {$scenario_file}" . PHP_EOL;
         log_error("debug,error,scenario", "scenario file not found: {$scenario_file}");
         return TRUE;
     }
     $scenario_data = parse_ini_file($scenario_file, TRUE);
     log_debug("debug,scenario", "scenario_data: " . print_r($scenario_data, true));
     if (empty($scenario_data)) {
         echo "couldn't read scenario file: {$scenario_file}" . PHP_EOL;
         log_error("debug,error,scenario", "couldn't read scenario file: {$scenario_file}");
         return TRUE;
     }
     foreach ($scenario_data as $section => $data) {
         $target = isset($data['target']) ? $data['target'] : NULL;
         $actions = isset($data['actions']) ? $data['actions'] : NULL;
         $enabled = isset($data['enabled']) ? $data['enabled'] : TRUE;
         log_debug("debug,scenario", "target: {$target}");
         log_debug("debug,scenario", "actions: {$actions}");
         log_debug("debug,scenario", "enabled: {$enabled}");
         if (in_array(strtolower($enabled), array('0', 'false', 'no'))) {
             echo "section[{$section}] is DISABLED. will skip." . PHP_EOL;
             log_warning("debug, scenario", "section[{$section}] is DISABLED.");
             continue;
         }
         if (empty($target)) {
             echo "[WARNING] 'target' is not found at section[{$section}]" . PHP_EOL;
             log_warning("debug, scenario", "'target' is not found at section[{$section}]");
             continue;
         }
         if (empty($actions)) {
             echo "[WARNING] 'actions' is not found at section[{$section}]" . PHP_EOL;
             log_warning("debug, scenario", "'actions' is not found at section[{$section}]");
             continue;
         }
         $target_path = new Charcoal_ObjectPath($target);
         $module_path = '@' . $target_path->getVirtualPath();
         $context->loadModule($module_path);
         log_info("debug,scenario", "loaded module: {$module_path}");
         $event_args = array($section, $target, $actions);
         /** @var Charcoal_IEvent $event */
         $event = $context->createEvent('test', $event_args);
         $context->pushEvent($event);
         log_debug("debug,scenario", "event_args: " . print_r($event_args, true));
         log_debug("debug,scenario", "pushed event: " . print_r($event, true));
     }
     // request fo test summary
     /** @var Charcoal_IEvent $event */
     $event = $context->createEvent('test_summary');
     $context->pushEvent($event);
     return TRUE;
 }
コード例 #19
0
function http_multi(&$requests)
{
    $handles = array();
    $responses = array();
    foreach ($requests as $req) {
        $url = $req['url'];
        $method = isset($req['method']) ? strtoupper($req['method']) : 'GET';
        $body = is_array($req['body']) ? $req['body'] : null;
        $headers = is_array($req['headers']) ? $req['headers'] : array();
        $more = is_array($req['more']) ? $req['more'] : array();
        $more['return_curl_handle'] = 1;
        if ($method == 'HEAD') {
            $ch = http_head($url, $headers, $more);
        } else {
            if ($method == 'GET') {
                $ch = http_get($url, $headers, $more);
            } else {
                if ($method == 'POST') {
                    $ch = http_post($url, $body, $headers, $more);
                } else {
                    if ($method == 'DELETE') {
                        $ch = http_delete($url, $body, $headers, $more);
                    } else {
                        if ($method == 'PUT') {
                            $ch = http_put($url, $body, $headers, $more);
                        } else {
                            log_warning("http", "unsupported HTTP method : {$method}");
                            continue;
                        }
                    }
                }
            }
        }
        $handles[] = $ch;
    }
    # http://us.php.net/manual/en/function.curl-multi-init.php
    $mh = curl_multi_init();
    foreach ($handles as $ch) {
        curl_multi_add_handle($mh, $ch);
    }
    $active = null;
    $start = microtime_ms();
    # this syntax makes my eyes bleed but whatever...
    # (20110822/straup)
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }
    $end = microtime_ms();
    $GLOBALS['timings']['http_count'] += count($handlers);
    $GLOBALS['timings']['http_time'] += $end - $start;
    foreach ($handles as $ch) {
        $raw = curl_multi_getcontent($ch);
        $info = curl_getinfo($ch);
        curl_multi_remove_handle($mh, $ch);
        $rsp = _http_parse_response($raw, $info);
        $responses[] = $rsp;
    }
    curl_multi_close($mh);
    return $responses;
}
コード例 #20
0
function load_names_data($file_name)
{
    if (!file_exists($file_name)) {
        log_warning(0, "Couldn't find file '{$file_name}'");
        return;
    }
    $csv_data = read_csv_file($file_name);
    $output = array();
    foreach ($csv_data as $row) {
        $names_string = $row['names'];
        $names = explode('|', $names_string);
        foreach ($names as $name) {
            $name = normalize_name($name);
            $name_words = explode(' ', $name);
            $name_words = array_reverse($name_words);
            $first_word = $name_words[0];
            if (!isset($output[$first_word])) {
                $output[$first_word] = array();
            }
            $preceding_words = array_slice($name_words, 1);
            $output_row = array('name' => $name, 'preceding_words' => $preceding_words);
            foreach ($row as $key => $value) {
                if ($key !== 'name') {
                    $output_row[$key] = $value;
                }
            }
            $output[$first_word][] = $output_row;
        }
    }
    return $output;
}
コード例 #21
0
ファイル: main.php プロジェクト: thelectronicnub/shimmie2
 public function onPageRequest(PageRequestEvent $event)
 {
     global $page, $user;
     if ($event->page_matches("ext_manager")) {
         if ($user->can("manage_extension_list")) {
             if ($event->get_arg(0) == "set" && $user->check_auth_token()) {
                 if (is_writable("data/config")) {
                     $this->set_things($_POST);
                     log_warning("ext_manager", "Active extensions changed", true);
                     $page->set_mode("redirect");
                     $page->set_redirect(make_link("ext_manager"));
                 } else {
                     $this->theme->display_error(500, "File Operation Failed", "The config file (data/config/extensions.conf.php) isn't writable by the web server :(");
                 }
             } else {
                 $this->theme->display_table($page, $this->get_extensions(true), true);
             }
         } else {
             $this->theme->display_table($page, $this->get_extensions(false), false);
         }
     }
     if ($event->page_matches("ext_doc")) {
         $ext = $event->get_arg(0);
         if (file_exists("ext/{$ext}/main.php")) {
             $info = new ExtensionInfo("ext/{$ext}/main.php");
             $this->theme->display_doc($page, $info);
         } else {
             $this->theme->display_table($page, $this->get_extensions(false), false);
         }
     }
 }
コード例 #22
0
 public function validate($sequence, $form_token, $throws = TRUE)
 {
     Charcoal_ParamTrait::validateIsA(1, 'Charcoal_ISequence', $sequence);
     Charcoal_ParamTrait::validateString(2, $form_token);
     Charcoal_ParamTrait::validateBoolean(3, $throws);
     $throws = ub($throws);
     log_debug("debug", "sequence: " . print_r($sequence, true));
     log_debug("debug", "form_token: " . print_r($form_token, true));
     if ($this->getSandbox()->isDebug() && $this->debug_mode) {
         ad($sequence, array('title' => "sequence"));
     }
     $token_key = $this->token_key;
     log_debug("debug", "token_key: " . print_r($token_key, true));
     if ($this->getSandbox()->isDebug() && $this->debug_mode) {
         ad($token_key, array('title' => "token_key", "type" => "div"));
     }
     // get token container from session.
     $token_list = $sequence->get(s($token_key));
     if ($this->getSandbox()->isDebug() && $this->debug_mode) {
         ad($token_list, array('title' => "token list"));
     }
     log_debug("debug", "token_list: " . print_r($token_list, true));
     if ($token_list === NULL || !is_array($token_list)) {
         $token_list = array();
     }
     // find token from token list.
     $token_index = NULL;
     foreach ($token_list as $idx => $token) {
         log_info("debug", "token: {$token}");
         if ($this->getSandbox()->isDebug() && $this->debug_mode) {
             ad($token, array('title' => "token", "type" => "div"));
         }
         if ($token == $form_token) {
             $token_index = $idx;
             break;
         }
     }
     if ($token_index === NULL) {
         // illegal access
         log_warning("system, debug", "token not found: {$form_token}");
         if ($this->getSandbox()->isDebug() && $this->debug_mode) {
             ad($form_token, array('title' => "token not found", "type" => "div"));
         }
         if ($throws) {
             _throw(new Charcoal_FormTokenValidationException('token not found in sequence:' . $form_token), FALSE);
         }
         return FALSE;
     } else {
         // authorized access
         log_debug("debug", "token accepted: {$form_token}");
         if ($this->getSandbox()->isDebug() && $this->debug_mode) {
             ad($form_token, array('title' => "token accepted", "type" => "div"));
         }
         // erase token from token list to prevent duplicate form submission.
         unset($token_list[$token_index]);
     }
     // update token list in sequence.
     $sequence->set($token_key, $token_list);
     // the event was successfully processed.
     return TRUE;
 }
コード例 #23
0
 /**
  *    real implementation of Charcoal_SmartGateway::queryValue()
  *
  * @param Charcoal_String|string $comment          comment text
  * @param Charcoal_String|string $sql              SQL statement(placeholders can be included)
  * @param Charcoal_HashMap|array $params           Parameter values for prepared statement
  * @param Charcoal_HashMap|array $driver_options   Driver options
  *
  * @return mixed|NULL
  */
 public function queryValue($comment, $sql, $params = NULL, $driver_options = NULL)
 {
     Charcoal_ParamTrait::validateString(1, $comment, TRUE);
     Charcoal_ParamTrait::validateString(2, $sql);
     Charcoal_ParamTrait::validateHashMap(3, $params, TRUE);
     Charcoal_ParamTrait::validateHashMap(4, $driver_options, TRUE);
     $sql = !empty($comment) ? $this->sql_builder->prependComment($sql, $comment) : $sql;
     $result = $this->data_source->prepareExecute($sql, $params, $driver_options);
     while ($row = $this->data_source->fetchAssoc($result)) {
         $value = array_shift($row);
         log_debug("debug,smart_gateway,sql", "queryValue:{$value}", self::TAG);
         return $value;
     }
     $this->data_source->free($result);
     log_warning("debug,smart_gateway,sql", "smart_gateway", "queryValue: no record");
     return NULL;
 }
コード例 #24
0
ファイル: code_quality.php プロジェクト: erico-deh/ocPortal
function ensure_type($_allowed_types, $actual_type, $pos, $alt_error = NULL, $extra_strict = false)
{
    if (is_array($actual_type)) {
        $actual_type = $actual_type[0];
    }
    if ($actual_type == 'mixed' || $actual_type == '?mixed' || $actual_type == '~mixed') {
        return true;
    }
    // We can't check it
    // Tidy up our allow list to be a nice map
    if (!$extra_strict && (in_array('boolean', $_allowed_types) || in_array('?boolean', $_allowed_types))) {
        $_allowed_types[] = 'boolean-false';
    }
    if ($extra_strict && $_allowed_types == array('boolean')) {
        $_allowed_types[] = 'boolean-false';
    }
    $allowed_types = array();
    foreach ($_allowed_types as $type) {
        if (is_array($type)) {
            $type = $type[0];
        }
        if ($type == 'mixed' || $type == '?mixed' || $type == '~mixed' || $type == 'resource' || $type == '?resource' || $type == '~resource') {
            return true;
        }
        // Anything works!
        if ($type[0] == '?') {
            $type = substr($type, 1);
            $allowed_types['NULL'] = 1;
        }
        if ($type[0] == '~') {
            $type = substr($type, 1);
            $allowed_types['boolean-false'] = 1;
        }
        if (substr($type, 0, 6) == 'object') {
            $type = 'object';
        }
        if ($type == 'REAL') {
            $allowed_types['float'] = 1;
        }
        if (in_array($type, array('AUTO', 'INTEGER', 'UINTEGER', 'SHORT_TRANS', 'LONG_TRANS', 'USER', 'MEMBER', 'SHORT_INTEGER', 'AUTO_LINK', 'BINARY', 'GROUP', 'TIME'))) {
            $allowed_types['integer'] = 1;
        }
        if (in_array($type, array('LONG_TEXT', 'SHORT_TEXT', 'MINIID_TEXT', 'ID_TEXT', 'LANGUAGE_NAME', 'URLPATH', 'PATH', 'IP', 'MD5', 'EMAIL'))) {
            $allowed_types['string'] = 1;
        }
        if (in_array($type, array('tempcode'))) {
            $allowed_types['object'] = 1;
        }
        if (in_array($type, array('list', 'map'))) {
            $allowed_types['array'] = 1;
        }
        $allowed_types[$type] = 1;
    }
    // Special cases for our actual type
    if ($actual_type[0] == '?') {
        //		if (isset($allowed_types['NULL'])) return true;		We can afford not to give this liberty due to is_null
        $actual_type = substr($actual_type, 1);
    }
    if ($actual_type[0] == '~') {
        if (isset($allowed_types['boolean-false'])) {
            return true;
        }
        $actual_type = substr($actual_type, 1);
    }
    if (substr($actual_type, 0, 6) == 'object') {
        $actual_type = 'object';
    }
    // The check
    if (isset($allowed_types[$actual_type])) {
        return true;
    }
    if ($actual_type == 'REAL') {
        if (isset($allowed_types['float'])) {
            return true;
        }
    }
    if (in_array($actual_type, array('AUTO', 'INTEGER', 'UINTEGER', 'SHORT_TRANS', 'LONG_TRANS', 'USER', 'MEMBER', 'SHORT_INTEGER', 'AUTO_LINK', 'BINARY', 'GROUP', 'TIME'))) {
        if (isset($allowed_types['integer'])) {
            return true;
        }
    }
    if (in_array($actual_type, array('LONG_TEXT', 'SHORT_TEXT', 'MINIID_TEXT', 'ID_TEXT', 'LANGUAGE_NAME', 'URLPATH', 'PATH', 'IP', 'MD5', 'EMAIL'))) {
        if (isset($allowed_types['string'])) {
            return true;
        }
    }
    if (in_array($actual_type, array('tempcode'))) {
        if (isset($allowed_types['object'])) {
            return true;
        }
    }
    if (in_array($actual_type, array('list', 'map'))) {
        if (isset($allowed_types['array'])) {
            return true;
        }
    }
    log_warning(is_null($alt_error) ? 'Type mismatch' : $alt_error, $pos);
    return false;
}
コード例 #25
0
ファイル: main.php プロジェクト: nsuan/shimmie2
 private function login($page)
 {
     global $user;
     $name = $_POST['user'];
     $pass = $_POST['pass'];
     $hash = md5(strtolower($name) . $pass);
     $duser = User::by_name_and_hash($name, $hash);
     if (!is_null($duser)) {
         $user = $duser;
         $this->set_login_cookie($name, $pass);
         if ($user->is_admin()) {
             log_warning("user", "Admin logged in");
         } else {
             log_info("user", "User logged in");
         }
         $page->set_mode("redirect");
         $page->set_redirect(make_link("user"));
     } else {
         log_warning("user", "Failed to log in as " . html_escape($name) . " [{$hash}]");
         $this->theme->display_error($page, "Error", "No user with those details was found");
     }
 }
コード例 #26
0
ファイル: main.php プロジェクト: thelectronicnub/shimmie2
 private function recount_tag_use()
 {
     global $database;
     $database->Execute("\n\t\t\tUPDATE tags\n\t\t\tSET count = COALESCE(\n\t\t\t\t(SELECT COUNT(image_id) FROM image_tags WHERE tag_id=tags.id GROUP BY tag_id),\n\t\t\t\t0\n\t\t\t)\n\t\t");
     $database->Execute("DELETE FROM tags WHERE count=0");
     log_warning("admin", "Re-counted tags", true);
     return true;
 }
コード例 #27
0
ファイル: main.php プロジェクト: JarJak/shimmie2
 /**
  * @return bool
  */
 private function update_shimmie()
 {
     global $config, $page;
     $commitSHA = $_GET['sha'];
     $g_userrepo = $config->get_string('update_guserrepo');
     log_info("update", "Download succeeded. Attempting to update Shimmie.");
     $config->set_bool("in_upgrade", TRUE);
     $ok = FALSE;
     /** TODO: Backup all folders (except /data, /images, /thumbs) before attempting this?
         Either that or point to https://github.com/shish/shimmie2/blob/master/README.txt -> Upgrade from 2.3.X **/
     $zip = new ZipArchive();
     if ($zip->open("./data/update_{$commitSHA}.zip") === TRUE) {
         for ($i = 1; $i < $zip->numFiles; $i++) {
             $filename = $zip->getNameIndex($i);
             if (substr($filename, -1) !== "/") {
                 copy("zip://" . dirname(dirname(__DIR__)) . '/' . "./data/update_{$commitSHA}.zip" . "#" . $filename, substr($filename, 50));
             }
         }
         $ok = TRUE;
         //TODO: Do proper checking to see if everything copied properly
     } else {
         log_warning("update", "Update failed to open ZIP.");
     }
     $zip->close();
     unlink("./data/update_{$commitSHA}.zip");
     $config->set_bool("in_upgrade", FALSE);
     if ($ok) {
         $config->set_string("commit_hash", $commitSHA);
         $config->set_string("update_time", date('d-m-Y'));
         log_info("update", "Update succeeded?");
     }
     return $ok;
 }
コード例 #28
0
ファイル: main.php プロジェクト: thelectronicnub/shimmie2
 /**
  * @param string $text
  * @return bool
  */
 private function is_spam_akismet($text)
 {
     global $config, $user;
     if (strlen($config->get_string('comment_wordpress_key')) > 0) {
         $comment = array('author' => $user->name, 'email' => $user->email, 'website' => '', 'body' => $text, 'permalink' => '');
         # akismet breaks if there's no referrer in the environment; so if there
         # isn't, supply one manually
         if (!isset($_SERVER['HTTP_REFERER'])) {
             $comment['referrer'] = 'none';
             log_warning("comment", "User '{$user->name}' commented with no referrer: {$text}");
         }
         if (!isset($_SERVER['HTTP_USER_AGENT'])) {
             $comment['user_agent'] = 'none';
             log_warning("comment", "User '{$user->name}' commented with no user-agent: {$text}");
         }
         $akismet = new Akismet($_SERVER['SERVER_NAME'], $config->get_string('comment_wordpress_key'), $comment);
         if ($akismet->errorsExist()) {
             return false;
         } else {
             return $akismet->isSpam();
         }
     }
     return false;
 }
コード例 #29
0
 /**
  * write session data
  */
 public function write($id, $sess_data)
 {
     $file = $this->getSessionFile($id);
     //        log_info( "session", __CLASS__, __CLASS__.'#write: file=' . $file . ' id=' . $id . ' data=' . print_r($sess_data,true) );
     $fp = @fopen($file, 'w');
     if (!$fp) {
         log_warning("system,debug,error,session", "fopen failed: {$file}", self::TAG);
         return false;
     }
     $write = fwrite($fp, $sess_data);
     fclose($fp);
     return $write !== FALSE ? TRUE : FALSE;
 }
コード例 #30
0
ファイル: organizer.php プロジェクト: klr2003/sourceread
         $end_date = new CDate($row["task_start_date"]);
         $durn = convert2days($row["task_duration"], $row["task_duration_type"]);
         $end_date->addDays($durn);
         $row["task_end_date"] = $end_date->getDate();
         if ($do == "ask" && $option_no_end_date_warning) {
             log_warning("Task " . task_link($row) . " has no end date. Using tasks duration instead.", '<input type="checkbox" name="set_end_date[' . $row['task_id'] . ']" id="set_end_date[' . $row['task_id'] . ']" value="1" /> ' . '<label for="set_end_date[' . $row['task_id'] . ']">Set end date to ' . $row["task_end_date"] . '</label>');
         }
     }
     // check delayed tasks
     if ($do == "ask") {
         if (!$row["task_dynamic"] && $row["task_percent_complete"] == 0) {
             // nothing has be done yet
             $end_time = new CDate(db_dateTime2unix($row["task_end_date"]));
             if ($end_time < time()) {
                 if ($option_check_delayed_tasks) {
                     log_warning("Task " . task_link($row) . " started on " . $row["task_start_date"] . " and ended on " . formatTime($end_time) . ".", '<input type="checkbox" name="set_dynamic[' . $row["task_id"] . ']" id="set_dynamic[' . $row["task_id"] . ']" value="1" checked="checked" /> <label for="set_dynamic[' . $row["task_id"] . ']">Set as dynamic task and reorganize</label><br />' . '<input type="checkbox" name="set_priority[' . $row["task_id"] . ']" id="set_priority[' . $row["task_id"] . ']" value="1" checked="checked" /> <label for="set_priority[' . $row["task_id"] . ']">Set priority to high</label><br />');
                 }
             }
         }
     }
     array_push($tasks, $row);
 }
 if (!$errors) {
     for ($i = 0, $xi = count($tasks); $i < $xi; $i++) {
         process_dependencies($i);
     }
 }
 if ($option_fix_task_group_date_ranges) {
     // query taskgroups
     $sql = "select distinct a.* from tasks as a, tasks as b " . "WHERE (b.task_parent = a.task_id and a.task_id != b.task_id) " . " AND (a.task_project = {$project_id} AND b.task_project = {$project_id})";
     $taskgroups = mysql_query($sql);