Efetua o carregamento automático dos scripts php dentro do diretório app.
186140
private function autoload()
    {
        $app = $this;
        $finder = new Finder();

        foreach ($finder->in($app['singular.directory.app'])->files()->name('*.php') as $file) {
            include_once $file->getRealpath();
        }
    }
1318922
function compile() {
		$code = $this->match_code($this->value) ;

		$id = $this->varid() ;

		if ( $this->optional ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array( 'FAIL' => $this->restore($id,true) ))
				);
		}

		if ( $this->zero_or_more ) {
			$code = PHPBuilder::build()
				->b( 'while (true)',
					$this->save($id),
					$code->replace( array(
						'MATCH' => NULL,
						'FAIL' =>
							$this->restore($id,true)
							->l( 'break;' )
					))
				)
				->l(
				'MATCH'
				);
		}

		if ( $this->one_or_more ) {
			$code = PHPBuilder::build()
				->l(
				'$count = 0;'
				)
				->b( 'while (true)',
					$this->save($id),
					$code->replace( array(
						'MATCH' => NULL,
						'FAIL' =>
							$this->restore($id,true)
							->l( 'break;' )
					)),
					'$count += 1;'
				)
				->b( 'if ($count > 0)', 'MATCH' )
				->b( 'else',            'FAIL' );
		}

		if ( $this->positive_lookahead ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array(
					'MATCH' =>
						$this->restore($id)
						->l( 'MATCH' ),
					'FAIL' =>
						$this->restore($id)
						->l( 'FAIL' )
				)));
		}

		if ( $this->negative_lookahead ) {
			$code = PHPBuilder::build()
				->l(
				$this->save($id),
				$code->replace( array(
					'MATCH' =>
						$this->restore($id)
						->l( 'FAIL' ),
					'FAIL' =>
						$this->restore($id)
						->l( 'MATCH' )
				)));
		}

		if ( $this->tag && !($this instanceof TokenRecurse ) ) {
			$code = PHPBuilder::build()
				->l(
				'$stack[] = $result; $result = $this->construct( $matchrule, "'.$this->tag.'" ); ',
				$code->replace(array(
					'MATCH' => PHPBuilder::build()
						->l(
						'$subres = $result; $result = array_pop($stack);',
						'$this->store( $result, $subres, \''.$this->tag.'\' );',
						'MATCH'
						),
					'FAIL' => PHPBuilder::build()
						->l(
						'$result = array_pop($stack);',
						'FAIL'
						)
				)));
		}

		return $code ;
	}
417412
public function generateScripts()
    {
        $parameters = $this->generateJson();

        return new HtmlString(
            sprintf($this->template(), $this->getTableAttribute('id'), $parameters)
        );
    }
1341799
public function execute() {
        global $CFG, $DB;

        $timenow = time();
        // Run the auth cron, if any before enrolments
        // because it might add users that will be needed in enrol plugins.
        $auths = get_enabled_auth_plugins();
        mtrace("Running auth crons if required...");
        foreach ($auths as $auth) {
            $authplugin = get_auth_plugin($auth);
            if (method_exists($authplugin, 'cron')) {
                mtrace("Running cron for auth/$auth...");
                $authplugin->cron();
                if (!empty($authplugin->log)) {
                    mtrace($authplugin->log);
                }
            }
            unset($authplugin);
        }

        // It is very important to run enrol early
        // because other plugins depend on correct enrolment info.
        mtrace("Running enrol crons if required...");
        $enrols = enrol_get_plugins(true);
        foreach ($enrols as $ename => $enrol) {
            // Do this for all plugins, disabled plugins might want to cleanup stuff such as roles.
            if (!$enrol->is_cron_required()) {
                continue;
            }
            mtrace("Running cron for enrol_$ename...");
            $enrol->cron();
            $enrol->set_config('lastcron', time());
        }

        // Run all cron jobs for each module.
        mtrace("Starting activity modules");
        if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
            foreach ($mods as $mod) {
                $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
                if (file_exists($libfile)) {
                    include_once($libfile);
                    $cronfunction = $mod->name."_cron";
                    if (function_exists($cronfunction)) {
                        mtrace("Processing module function $cronfunction ...\n", '');
                        $predbqueries = null;
                        $predbqueries = $DB->perf_get_queries();
                        $pretime      = microtime(1);
                        if ($cronfunction()) {
                            $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                        }
                        if (isset($predbqueries)) {
                            mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries");
                            mtrace("... used " . (microtime(1) - $pretime) . " seconds");
                        }
                        // Reset possible changes by modules to time_limit. MDL-11597.
                        \core_php_time_limit::raise();
                        mtrace("done.");
                    }
                }
            }
        }
        mtrace("Finished activity modules");

        mtrace("Starting blocks");
        if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
            // We will need the base class.
            require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
            foreach ($blocks as $block) {
                $blockfile = $CFG->dirroot.'/blocks/'.$block->name.'/block_'.$block->name.'.php';
                if (file_exists($blockfile)) {
                    require_once($blockfile);
                    $classname = '\\block_'.$block->name;
                    $blockobj = new $classname;
                    if (method_exists($blockobj, 'cron')) {
                        mtrace("Processing cron function for ".$block->name.'....', '');
                        if ($blockobj->cron()) {
                            $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                        }
                        // Reset possible changes by blocks to time_limit. MDL-11597.
                        \core_php_time_limit::raise();
                        mtrace('done.');
                    }
                }

            }
        }
        mtrace('Finished blocks');

        mtrace('Starting admin reports');
        cron_execute_plugin_type('report');
        mtrace('Finished admin reports');

        mtrace('Starting course reports');
        cron_execute_plugin_type('coursereport');
        mtrace('Finished course reports');

        // Run gradebook import/export/report cron.
        mtrace('Starting gradebook plugins');
        cron_execute_plugin_type('gradeimport');
        cron_execute_plugin_type('gradeexport');
        cron_execute_plugin_type('gradereport');
        mtrace('Finished gradebook plugins');

        // All other plugins.
        cron_execute_plugin_type('message', 'message plugins');
        cron_execute_plugin_type('filter', 'filters');
        cron_execute_plugin_type('editor', 'editors');
        cron_execute_plugin_type('format', 'course formats');
        cron_execute_plugin_type('profilefield', 'profile fields');
        cron_execute_plugin_type('webservice', 'webservices');
        cron_execute_plugin_type('repository', 'repository plugins');
        cron_execute_plugin_type('qbehaviour', 'question behaviours');
        cron_execute_plugin_type('qformat', 'question import/export formats');
        cron_execute_plugin_type('qtype', 'question types');
        cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
        cron_execute_plugin_type('theme', 'themes');
        cron_execute_plugin_type('tool', 'admin tools');
        cron_execute_plugin_type('local', 'local plugins');
    }
478861
protected function setupScript() {
    // The PHP that proc_open() will find may not be the same one as run by
    // the webserver, and indeed, on some systems may be an out-of-date version,
    // so detect the PHP that we're currently running and ensure we use that.
    $php = PHP_BINDIR . '/php';

    $script_name = __DIR__ . '/../../class_safety_checker.php';
    $drupal_root = $this->environment->getRoot();
    $autoloader_filepath = $drupal_root . '/autoload.php';

    // We need to pass all the dynamic namespaces to the script, as Composer's
    // generated autoloader knows only about /vendor and /core/lib, but not
    // modules.
    // This code is taken from DrupalKernel::attachSynthetic().
    $container = $this->environment->getContainer();
    $namespaces = $container->getParameter('container.namespaces');
    $psr4 = [];
    foreach ($namespaces as $prefix => $paths) {
      if (is_array($paths)) {
        foreach ($paths as $key => $value) {
          $paths[$key] = $drupal_root . '/' . $value;
        }
      }
      elseif (is_string($paths)) {
        $paths = $drupal_root . '/' . $paths;
      }

      // Build a list of data to pass to the script on STDIN.
      // $paths is never an array, AFAICT.
      $psr4[] = $prefix . '\\' . '::' . $paths;
    }

    // Debug option for the script.
    $debug_int = (int) $this->debug;

    $command = "{$php} {$script_name} '{$autoloader_filepath}' {$debug_int}";

    // Open pipes for both input and output.
    $descriptorspec = array(
       0 => array("pipe", "r"),
       1 => array("pipe", "w")
    );
    $this->checking_script_resource = proc_open($command, $descriptorspec, $this->pipes);

    if (!is_resource($this->checking_script_resource)) {
      throw new \Exception("Could not create process for classIsUsable().");
    }

    foreach ($psr4 as $line) {
      $this->sendCommand('PSR4', $line);
    }
  }
261797
private function setupHeader()
    {
        // Não existem linhas de cabeçalho
        if ($this->getHeaderNumRows() == 0) {
            return false;
        }

        foreach ($this->header_rows as $index => $row) {

            $line = $index+1;

            // Insere a nova linha
            $this->getActiveSheet()->insertNewRowBefore($line, 1);

            // A linha possui estilos personalizados?
            $styles = count($row['styles'])>0 ? $row['styles'] : [];
            $styles = $this->normalizeStyles($styles, 'header');

            // Mescla as colunas para criar as linhas de cabeçalho
            if ($row['colspan'] == 'auto') {
                $row['colspan'] = $this->getLastColumn();
            }
            $colspan = $this->getColumnVowel($row['colspan']);
            $this->getActiveSheet()->mergeCells("A{$line}:{$colspan}{$line}");

            // Adiciona o conteudo formatado na linha
            $content = $this->parseHtmlText($row['content'], $styles);
            $this->getActiveSheet()->getCell("A{$line}")->setValue($content);

            $this->debugStyle('header', $line, 1, 'text-content', $this->last_text_content);
            $this->debugStyle('header', $line, 1, 'row-styles-setted', $row['styles']);

            // Aplica os estilos
            $this->applyStyles('header', $line, 1, $styles);
        }
    }
215213
public function actionGenerate()
	{
		$passwordList = \App::$domain->tool->password->generate();
		$text = implode(SPC, $passwordList);
		Output::line();
		Output::pipe('Generated passwords');
		Output::autoWrap($text);
		Output::pipe();
		Output::line();
	}
924691
public function run()
  {
    if ( \count((array)$this->obj) === 0 ){
      header('HTTP/1.0 404 Not Found');
      exit();
    }

    if ( $this->mode === 'cli' ){
      if ( !headers_sent() && !$this->obj->content ){
        exit('No output...');
      }
      if ( $this->obj->content ){
        echo $this->obj->content;
      }
      @ob_end_flush();
      exit();
    }

    if ( isset($this->obj->prescript) ){
      if ( empty($this->obj->prescript) ){
        unset($this->obj->prescript);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->prescript);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->prescript, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->prescript = $tmp;
        }
      }
    }
    if ( isset($this->obj->script) ){
      if ( empty($this->obj->script) ){
        unset($this->obj->script);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->script);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->script, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->script = $tmp;
        }

      }
    }
    if ( isset($this->obj->postscript) ){
      if ( empty($this->obj->postscript) ){
        unset($this->obj->postscript);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->postscript);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->postscript, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->postscript = $tmp;
        }
      }
    }
    if ( empty($this->obj->content) || ( ($this->mode === 'file') || ($this->mode === 'image') ) ){
      if (!empty($this->obj->file)){
        if (\is_string($this->obj->file) && is_file($this->obj->file)){
          $this->obj->file = new bbn\file($this->obj->file);
        }
        if (\is_object($this->obj->file) &&
          method_exists($this->obj->file, 'download') &&
          method_exists($this->obj->file, 'test') &&
          $this->obj->file->test()
        ){
          $this->mode = 'file';
        }
      }
      else if (!empty($this->obj->img)){
        if (\is_string($this->obj->img) && is_file($this->obj->img)){
          $this->obj->img = new bbn\file\image($this->obj->img);
        }
        if (\is_object($this->obj->img) &&
          method_exists($this->obj->img, 'display') &&
          method_exists($this->obj->img, 'test') &&
          $this->obj->img->test()
        ){
          $this->mode = 'image';
        }
      }
    }
    switch ( $this->mode ){
      case 'public':
      case 'json':
      case 'js':
      case 'css':
      case 'doc':
      case 'html':
        if ( !ob_start("ob_gzhandler" ) ){
          ob_start();
        }
        else{
          header('Content-Encoding: gzip');
        }
        break;
      default:
        ob_start();
    }
    if ( (empty($this->obj->content) && empty($this->obj->file) && empty($this->obj->img) && ($this->mode !==
          'public')) ||
      (($this->mode === 'public') && empty($this->obj)) ){
      $this->mode = '';
    }
    else if ( !empty($this->obj->content) && !empty($this->obj->help) ){
      $Parsedown = new \Parsedown();
      $this->obj->help = $Parsedown->text($this->obj->help);
    }
    switch ( $this->mode ){

      case 'public':
        header('Content-type: application/json; charset=utf-8');
        echo json_encode($this->obj);
        break;

      case 'js':
        header('Content-type: application/javascript; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'css':
        header('Content-type: text/css; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'text':
        header('Content-type: text/plain; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'xml':
        header('Content-type: text/xml; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'image':
        if ( isset($this->obj->img) && \is_object($this->obj->img) ){
          $this->obj->img->display();
        }
        else{
          $this->log("Impossible to display the following image: ".$this->obj->img->name);
          header('HTTP/1.0 404 Not Found');

        }
        break;

      case 'file':
        if ( isset($this->obj->file) && \is_object($this->obj->file) && method_exists($this->obj->file, 'download') ){
          $this->obj->file->download();
        }
        else{
          $this->log("Impossible to display the following controller", $this);
          header('HTTP/1.0 404 Not Found');
          exit();
        }
        break;

      default:
        header('Content-type: text/html; charset=utf-8');
        echo isset($this->obj->content) ? $this->obj->content : '';

    }
  }
1066242
private function execute()
    {
        $this->Connect();
        try {
            $this->delete->execute($this->places);
            $this->result = true;
            $this->react = new React("delete", str_replace(PRE, '', $this->tabela), $this->resultsUpdates, $this->resultsUpdates);
        } catch (\PDOException $e) {
            $this->result = null;
            $this->erro = "<b>Erro ao Deletar:</b> {$e->getMessage()}";
        }

        parent::setDefault();
    }
1137425
function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
	{
		global $debug_object;

		// prepare
		$this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
		// strip out cdata
		$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
		// strip out comments
		$this->remove_noise("'<!--(.*?)-->'is");
		// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
		// Script tags removal now preceeds style tag removal.
		// strip out <script> tags
		$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
		$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
		// strip out <style> tags
		$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
		$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
		// strip out preformatted tags
		$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
		// strip out server side scripts
		$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
		// strip smarty scripts
		$this->remove_noise("'(\{\w)(.*?)(\})'s", true);

		// parsing
		while ($this->parse());
		// end
		$this->root->_[HDOM_INFO_END] = $this->cursor;
		$this->parse_charset();

		// make load function chainable
		return $this;

	}
857983
public function script()
    {
        echo $this->view->make('Assely::script', [
            'slug' => $this->metabox->getModel()->getSlug(),
            'fingerprint' => $this->metabox->getModel()->getFingerprint(),
            'fields' => json_encode($this->metabox->getFields()->all()),
        ]);
    }
1313156
public function run()
    {
        $default = [
            'module_name' => null,
            'action' => 'setting',
            'class' => 'form-control',
            'section' => 'main',
            'fieldset' => 'general',
            'name' => null,
            'type' => 'string',
            'value' => null,
            // '{"id":"id"}'
            'params' => null,
            'html_flags' => 'required',
        ];

        \DB::table('settings')->insert($this->getArticles($default));
        \DB::table('settings')->insert($this->getComments($default));
        \DB::table('settings')->insert($this->getFiles($default));
        \DB::table('settings')->insert($this->getSystem($default));
        \DB::table('settings')->insert($this->getTags($default));
        \DB::table('settings')->insert($this->getThemes($default));
        \DB::table('settings')->insert($this->getUsers($default));
    }
916606
public function find_standard_scripts() {
        global $PAGE;

        $plugindir = $this->plugin_dir();
        $plugindirrel = 'question/type/' . $this->name();

        if (file_exists($plugindir . '/script.js')) {
            $PAGE->requires->js('/' . $plugindirrel . '/script.js');
        }
        if (file_exists($plugindir . '/script.php')) {
            $PAGE->requires->js('/' . $plugindirrel . '/script.php');
        }
    }
60713
function tmp()
    {
        //$xlog = new Model\Xlog;

        //$xlog->decodeAgent();

        //Fazendo login
        //Lib\User::this()->login('admin', 'admin#123');
        //Lib\User::this()->setCriptoCookie();

        //Lib\User::this()->unsetCriptoCookie();
        $user = new Lib\User();

        $user->login('jessica', 'jessica#123');

        //$user->unsetCriptoCookie();
        //
        //
        Lib\App::p($user->get(), true);
        Lib\App::p(Lib\User::this()->get(), true);
        Lib\App::p($_SERVER['REMOTE_ADDR'], true);
        Lib\App::p($_SERVER['HTTP_USER_AGENT'], true);
        Lib\App::p($_SERVER['HTTP_ACCEPT_LANGUAGE'], true);

        echo "<br>OS: </b>".$this->operating_system_detection();

        echo '<hr/>';

        $jsonBrowser = json_encode(get_browser());

        echo '<br><b>Tamanho do arquivo: </b>'.strlen($jsonBrowser).'<br>';
        Lib\App::p(json_decode($jsonBrowser), true);


        //Fazendo login
        //Lib\User::this()->login('jessica', 'jessica#123');
        //Lib\User::this()->setCriptoCookie();

        //Lib\App::p(Lib\User::this()->get(), true);

        echo "<hr/><b>Finished!</b>";
    }
391654
private function _script() {
        // we need to compress?
        if($this->compress && $this->_config['compress']['js']) {
            // get cache
            $cache = $this->filename('js');
            if(!$cache)
                return false;

            // get paths
            $web_path = $this->_config['paths']['js'] . '/' . $cache;
            $system_path = $this->js['full'] . DS . $cache;

            // no cache file? write it
            if(!file_exists($system_path)) {
                // process compression
                $output = $this->process('js');

                // write to file
                file_put_contents($system_path, $output);
            }

            // output the cached file with the HTML helper
            return $this->Html->script($web_path);

        // no need to compress? output separately with the HTML helper
        } else return $this->Html->script($this->js['extern']);
    }
945945
public static function init() {
		if ( php_sapi_name() == 'cli' ) {
			self::$BasePath = str_replace( '/', DIRECTORY_SEPARATOR, dirname( __FILE__ ) . '/' );
		} else {
			self::$BasePath = str_replace( '/', DIRECTORY_SEPARATOR, realpath( dirname( __FILE__ ) ) . "/" );
		}

		if ( isset( $_SERVER['HTTPS'] ) ||
		     ( isset( $_SERVER['SERVER_PORT'] ) && $_SERVER['SERVER_PORT'] == 443 ) ||
		     ( isset( $_SERVER['HTTP_X_FORWARDED_PORT'] ) && $_SERVER['HTTP_X_FORWARDED_PORT'] == 443 )
		) {
			self::$protocol = "https://";
		} else {
			self::$protocol = "http://";
		}

		$PathInfo = pathinfo( $_SERVER['PHP_SELF'] );

		$index = basename( $_SERVER["SCRIPT_FILENAME"], '.php' ) . '.php';
		Config::set( 'index', $index );

		if ( strpos( $PathInfo['dirname'], '/' . $index ) > 0 ) {
			$StrLimit = strpos( $PathInfo['dirname'], '/' . $index );
		} elseif ( $PathInfo['dirname'] == '/' . $index ) {
			$StrLimit = 0;
		} else {
			$StrLimit = strlen( $PathInfo['dirname'] );
		}

		if ( php_sapi_name() == 'cli-server' ) {
			self::$BaseUrl = self::$protocol . $_SERVER['HTTP_HOST'] . '/';
		} else if ( php_sapi_name() == 'cli' ) {
			self::$params = $_SERVER['argv'];
			chdir( self::$BasePath );
			self::$BaseUrl = self::$BasePath;
		} else {

			/**
			 * ID: Terkadang terdapat masalah bagian base url, kamu dapat mengedit bagian ini. Biasanya masalah pada
			 *     $PathInfo['dirname']
			 * EN: Sometimes have a problem in base url section, you can editi this section. normally at
			 *     $PathInfo['dirname']
			 */
			self::$BaseUrl = self::$protocol . $_SERVER['HTTP_HOST'] . substr( $PathInfo['dirname'], 0, $StrLimit );

			if ( substr( self::$BaseUrl, - 1, 1 ) != '/' ) {
				self::$BaseUrl .= '/';
			}

		}

		if ( php_sapi_name() == 'cli' ) {
			$ResultSegment = $_SERVER['argv'];
			array_shift( $ResultSegment );

			self::$params     = $ResultSegment;
			self::$RealParams = self::$params;
			self::$ParamsStr  = implode( '/', $ResultSegment );
		} else {
            $path = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);

            if (substr($path, 0, 1) == '/' && strlen($path) > 1) {
                $path = substr($path, 1);
            }

			$segments = explode( '/', $path );

			if ( $segments[ count( $segments ) - 1 ] == '' && count( $segments ) > 1 ) {
				unset( $segments[ count( $segments ) - 1 ] );
			}

			$ResultSegment = array();

			while ( list( $key, $seg ) = each( $segments ) ) {

				if ( $segments[ $key ] != $index && $seg != '' ) {
					array_push( $ResultSegment, urldecode( $seg ) );
				}
			}

			self::$ParamsStr  = implode( '/', $ResultSegment );
			self::$params     = $ResultSegment;
			self::$RealParams = self::$params;
		}

		unset( $StrLimit );
		unset( $PathInfo );

	}
621437
public function index()
    {
        //  Command line only
        $oInput = Factory::service('Input');
        if (Environment::is(Environment::ENV_PROD) && !$oInput::isCli()) {
            header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
            echo '<h1>' . lang('unauthorised') . '</h1>';
            exit(401);
        }

        // --------------------------------------------------------------------------

        /**
         * Look for a controller, app version first then the module's cron controllers directory
         */
        $aControllerPaths = [
            NAILS_APP_PATH . 'application/modules/cron/controllers/',
        ];

        $nailsModules = Components::modules();

        foreach ($nailsModules as $oModule) {

            if ($oModule->moduleName === $this->sModuleName) {
                $aControllerPaths[] = $oModule->path . 'cron/controllers/';
                break;
            }
        }

        //  Look for a valid controller
        $sControllerName    = ucfirst($this->sClassName) . '.php';
        $bDidfindController = false;

        foreach ($aControllerPaths as $sPath) {

            $sControllerPath = $sPath . $sControllerName;

            if (is_file($sControllerPath)) {
                $bDidfindController = true;
                break;
            }
        }

        if (!empty($bDidfindController)) {

            //  Load the file and try and execute the method
            require_once $sControllerPath;

            $this->sModuleName = 'Nails\\Cron\\' . ucfirst($this->sModuleName) . '\\' . ucfirst($this->sClassName);

            if (class_exists($this->sModuleName)) {

                //  New instance of the controller
                $oInstance = new $this->sModuleName($this);

                if (is_callable([$oInstance, $this->sMethod])) {

                    //  Begin timing
                    $this->writeLog('Starting job');

                    if (!empty($this->aParams)) {

                        $this->writeLog('Passed parameters');
                        $this->writeLog(print_r($this->aParams, true));
                    }

                    $iStart = microtime(true) * 10000;

                    call_user_func_array([$oInstance, $this->sMethod], $this->aParams);

                    $iEnd      = microtime(true) * 10000;
                    $iDuration = ($iEnd - $iStart) / 10000;
                    $this->writeLog('Finished job');
                    $this->writeLog('Job took ' . number_format($iDuration, 5) . ' seconds');

                } else {

                    $this->writeLog('Cannot call method "' . $this->sMethod . '"');
                }

            } else {

                $this->writeLog(
                    '"' . $this->sModuleName . '" is incorrectly configured; could not find class ' . $this->sModuleName . '  at path ' . $sControllerPath
                );
            }

        } else {

            $this->writeLog(
                '"' . $this->sModuleName . '/' . $this->sClassName . '/' . $this->sMethod . '" is not a valid route.'
            );
        }
    }