public function __construct($name, $type, $install = false) { if (empty($name) || empty($type)) { return false; } if (empty($this->extName)) { $this->extName = $name; } if (empty($this->className)) { $this->className = ucfirst($name); } if (empty($this->extType)) { $this->extType = $type; } if (empty($this->extPrefix) && !empty($this->prefixes[$this->extType])) { $this->extPrefix = $this->prefixes[$this->extType] . '_'; } if ($this->extInstall == null) { $this->extInstall = (bool) $install; } if (empty($this->cli)) { $this->cli = JCli::getInstance(); } $this->scaffoldPath = dirname(__FILE__) . '/scaffold'; }
/** * Returns a reference to the global JCli object, only creating it if it * doesn't already exist. * * This method must be invoked as: $cli = JCli::getInstance(); * * @return JCli A JCli object * * @since 11.1 */ public static function &getInstance() { // Only create the object if it doesn't exist. if (empty(self::$instance)) { self::$instance = new JCli(); } return self::$instance; }
/** * Class constructor. * * This constructor invokes the parent JCli class constructor, * and then creates a connector to the database so that it is * always available to the application when needed. * * @return void * * @since 11.3 * @throws JDatabaseException */ public function __construct() { // Call the parent __construct method so it bootstraps the application class. parent::__construct(); jimport('joomla.database.database'); // Note, this will throw an exception if there is an error // creating the database connection. $this->dbo = JDatabase::getInstance(array('driver' => $this->get('dbDriver'), 'host' => $this->get('dbHost'), 'user' => $this->get('dbUser'), 'password' => $this->get('dbPass'), 'database' => $this->get('dbName'), 'prefix' => $this->get('dbPrefix'))); }
/** * Returns a reference to the global JCli object, only creating it if it * doesn't already exist. * * This method must be invoked as: $cli = JCli::getInstance(); * * @return JCli A JCli object * * @since 11.1 */ public static function &getInstance($name = null) { // Only create the object if it doesn't exist. if (empty(self::$instance)) { if (class_exists($name) && $name instanceof JCli) { self::$instance = new $name(); } else { self::$instance = new JCli(); } } return self::$instance; }
function invoke($numParams, &$arg1, &$arg2, &$arg3, &$arg4, &$arg5, &$arg6, $fnSuffix) { // ensure that we are running in a joomla context // we've not yet figured out how to bootstrap joomla, so we should // not execute hooks if joomla is not loaded if (defined('_JEXEC')) { //Invoke the Joomla plugin system to observe to civicrm events. jimport('joomla.plugin.helper'); jimport('cms.plugin.helper'); // Joomla 3.2 JPluginHelper::importPlugin('civicrm'); // get app based on cli or web if (PHP_SAPI != 'cli') { $app = JFactory::getApplication('administrator'); } else { // condition on Joomla version if (version_compare(JVERSION, '3.0', 'lt')) { $app = JCli::getInstance(); } else { $app = JApplicationCli::getInstance(); } } $result = $app->triggerEvent($fnSuffix, array(&$arg1, &$arg2, &$arg3, &$arg4, &$arg5, &$arg6)); $moduleResult = $this->commonInvoke($numParams, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6, $fnSuffix, 'joomla'); if (!empty($moduleResult) && is_array($moduleResult)) { if (empty($result)) { $result = $moduleResult; } else { if (is_array($moduleResult)) { $result = array_merge($result, $moduleResult); } } } if (!empty($result)) { // collapse result returned from hooks // CRM-9XXX $finalResult = array(); foreach ($result as $res) { if (!is_array($res)) { $res = array($res); } $finalResult = array_merge($finalResult, $res); } $result = $finalResult; } return $result; } }
/** * Class constructor. * * This constructor invokes the parent JCli class constructor, * and then creates a connector to the database so that it is * always available to the application when needed. * * @return void * * @since 11.3 * @throws JDatabaseException */ public function __construct() { // Call the parent __construct method so it bootstraps the application class. parent::__construct(); // // Prepare the logger. // // Include the JLog class. jimport('joomla.log.log'); // Get the date so that we can roll the logs over a time interval. $date = JFactory::getDate()->format('Y-m-d'); // Add the logger. JLog::addLogger(array('text_file' => 'cron.' . $date . '.php', 'text_file_path' => __DIR__ . '/logs')); // // Prepare the database connection. // jimport('joomla.database.database'); // Note, this will throw an exception if there is an error // creating the database connection. $this->dbo = JDatabase::getInstance(array('driver' => $this->get('dbDriver'), 'host' => $this->get('dbHost'), 'user' => $this->get('dbUser'), 'password' => $this->get('dbPass'), 'database' => $this->get('dbName'), 'prefix' => $this->get('dbPrefix'))); }
/** * Allows public access to protected method. * * @return void * * @since 11.3 */ public function loadDispatcher() { return parent::loadDispatcher(); }
public $version; public $description; public $helpKey; private $builder; private $zipFiles = array(); public function execute() { $this->out('Hello. What do you want to build today:' . "\n" . '1 - Component; 2 - Plugin; 3 - Module'); $choice = $this->in(); switch ($choice) { case 1: case 2: $this->out('Sorry but we can offer you only Modules :)'); break; case 3: default: $this->type = 'module'; } $this->out('Please enter an extension name in lower case e.g. "testmodule"'); $extName = JFolder::makeSafe($this->in()); $this->out('Do you want to install the extension on completion?'); $this->out("1 - Yes\n2 - No\n"); $install = $this->in(); $extInstall = $install == 1 ? true : false; $manifestPath = 'scaffold/module/'; $this->builder = new JBuilder($extName, 'module', $extInstall); $this->builder->build(); } } JCli::getInstance('BuilderService')->execute();
// Load system defines if (file_exists(dirname(__FILE__) . '/../defines.php')) { dirname(__FILE__) . '/../defines.php'; } if (!defined('_JDEFINES')) { define('JPATH_BASE', dirname(__FILE__) . '/../'); require_once JPATH_BASE . '/includes/defines.php'; } require_once JPATH_LIBRARIES . '/import.php'; require_once JPATH_LIBRARIES . '/cms.php'; class Updatecron extends JApplicationCli { public function execute() { // Purge all old records $db = JFactory::getDBO(); // Get the update cache time jimport('joomla.application.component.helper'); $component = JComponentHelper::getComponent('com_installer'); $params = $component->params; $cache_timeout = $params->get('cachetimeout', 6, 'int'); $cache_timeout = 3600 * $cache_timeout; // Find all updates $this->out('Fetching updates...'); $updater = JUpdater::getInstance(); $results = $updater->findUpdates(0, $cache_timeout); $this->out('Finished fetching updates'); } } JCli::getInstance('Updatecron')->execute();
// Setting up plugins. $this->out(JText::_('FINDER_CLI_SETTING_UP_PLUGINS'), true); // Trigger the onBeforeIndex event. JDispatcher::getInstance()->trigger('onBeforeIndex'); // Startup reporting. $this->out(JText::sprintf('FINDER_CLI_SETUP_ITEMS', $state->totalItems, round(microtime(true) - $this->_time, 3)), true); // Get the number of batches. $t = (int) $state->totalItems; $c = (int) ceil($t / $state->batchSize); $c = $c === 0 ? 1 : $c; // Process the batches. for ($i = 0; $i < $c; $i++) { // Set the batch start time. $this->_qtime = microtime(true); // Reset the batch offset. $state->batchOffset = 0; // Trigger the onBuildIndex event. JDispatcher::getInstance()->trigger('onBuildIndex'); // Batch reporting. $this->out(JText::sprintf('FINDER_CLI_BATCH_COMPLETE', $i + 1, round(microtime(true) - $this->_qtime, 3)), true); } // Total reporting. $this->out(JText::sprintf('FINDER_CLI_PROCESS_COMPLETE', round(microtime(true) - $this->_time, 3)), true); // Reset the indexer state. FinderIndexer::resetState(); } } // Instantiate the application object, passing the class name to JCli::getInstance // and use chaining to execute the application. JCli::getInstance('FinderCli')->execute();
// OK, another case of deep magic here. JApplication supports three client // names. Using the "site" client name forces it to look in // JPATH_BASE.'/includes/application.php' for a class named JSite. // Essentially the platform is tied to the CMS, as it doesn't allow us to // specify custom applications. jimport('joomla.application.application'); $app = JApplication::getInstance('site'); // After instantiating the application object, we have to pass it to // JFactory so that we can retrieve it easily. The reason we don't just use // JFactory::getApplication('site') is that this generates the error message // "Not connected to server.". Huh! JFactory::$application = $app; // Set the debug mode, if necessary if(defined('JDEBUG') && (JDEBUG == 1)) JFactory::getConfig()->set('debug', 1); // Next up, we dispatch the application. Note how we force the component // name. $app->dispatch('com_akeebaexample'); // Let the application render itself (basically, mix the component output // with the template-generated HTML code) $app->render(); // This final step is mandatory to deliver the output to the browser :) echo $app; } else { // CLI application define('_CLIAPP', 1); // Things are much easier. Just include the CLI app class and execute it JLoader::import('includes.app_cli', JPATH_BASE); define('JPATH_COMPONENT', JPATH_BASE.'/components/com_akeebaexample'); JCli::getInstance('Akeebaexample')->execute(); }
// This is an example of an option using long args (--). $value = $this->input->get('set'); $this->out(sprintf('%25s = %s', 'set', var_export($value, true))); // You can also apply defaults to the command line options. $value = $this->input->get('f', 'default'); $this->out(sprintf('%25s = %s', 'f (with default)', var_export($value, true))); // You can also apply input filters found in the JFilterInput class. // Try running this file like this: // $ ./run.php -f one2 $value = $this->input->get('f', 0, 'INT'); $this->out(sprintf('%25s = %s', 'f (cast to int)', var_export($value, true))); // Print out all the remaining command line arguments used to run this file. if (!empty($this->input->args)) { $this->out(); $this->out('These are the remaining arguments passed:'); $this->out(); // Unallocated arguments are found in $this->input->args. // Try running the file like this: // $ ./run.php -f foo bar foreach ($this->input->args as $arg) { $this->out($arg); } } // Print a blank line at the end. $this->out(); } } // Instantiate the application object, passing the class name to JCli::getInstance // and use chaining to execute the application. JCli::getInstance('Argv')->execute();
<?php defined('_JEXEC') or die(); // When running in Joomla! context, _CLIAPP is not defined; force it to false if(!defined('_CLIAPP')) define('_CLIAPP', false); if(_CLIAPP) { $app = JCli::getInstance('Akeebaexample'); $view = 'list'; } else { $app = JFactory::getApplication(); $view = $app->input->get('view','list','cmd'); } JLog::add('Setting view to '.$view, JLog::DEBUG); $task = $app->input->get('task','default'); JLog::add('Task is now '.$task, JLog::DEBUG); $view = strtolower($view); $c = 'AkeebaexampleController'.ucfirst($view); jimport('joomla.filesystem.file'); $filename = JPATH_COMPONENT.'/controllers/'.$view.'.php'; JLog::add('Controller filename is '.$filename, JLog::DEBUG); if(!JFile::exists($filename)) { JLog::add('Controller file not found', JLog::CRITICAL); JError::raise(E_ERROR, 404, 'View not found'); } else { JLog::add('Importing controller', JLog::DEBUG); require_once $filename; JLog::add('Instanciating controller', JLog::DEBUG); $controller = new $c();
public function showList($cachable = false, $urlparams = false) { JLog::add('In '.__CLASS__.'::'.__METHOD__, JLog::DEBUG); // This trick allows us to get a global application instance, depending // on whether we are running under the CLI or a web interface if(_CLIAPP) { $app = JCli::getInstance('Akeebaexample'); } else { $app = JFactory::getApplication(); } // Fetch all parameters using the app's JInput instance. Note how we do // filtering by passing the appropriate filter in the third parameter. // This also demonstrates how NOT to use JRequest, therefore making your // code compatible with both CLI and web applications at the same time. $host = $app->input->get('host', '', 'string'); $secret = $app->input->get('secret', '', 'string'); $tpl = $app->input->get('tpl', null); $from = $app->input->get('from',0, 'int'); $to = $app->input->get('to', 50, 'int'); // Handle an invalid input case by delegating execution to another task // in the CLI app (a CLI app has to implement a continuous MVC pattern), // or redirecting to another URL in the web app (the web app provides a // "Model 2" kind of MVC implementation) if(empty($host) || empty($secret)) { JLog::add('Empty hostname or secret key', JLog::WARNING); if(_CLIAPP) { JLog::add('Redirecting to showUsage', JLog::DEBUG); $this->showUsage(); return; } else { // Redirect JLog::add('Redirecting to params', JLog::DEBUG); $app = JApplication::getInstance(0); $msg = JText::_('COM_AKEEBAEXAMPLE_ERR_NOHOST'); $this->setRedirect('index.php?option=com_akeebaexample&view=list&task=params', $msg); $this->redirect(); return; } } JLog::add('Instanciating model', JLog::DEBUG); // We need this fake object so that JModel doesn't try to connect to a // database (we don't use any in our example app) $fooDbo = new JObject(); // And so, we create the model, populate its state and do nothing more $model = $this->createModel('List','AkeebaexampleModel',array('dbo' => $fooDbo)); $model->setState('host', $host); $model->setState('secret', $secret); $model->setState('from', $from); $model->setState('to', $to); JLog::add('Instanciating view', JLog::DEBUG); // For the CLI app we use a special hard-coded "format" identifier, txt. $format = _CLIAPP ? 'txt' : $app->get('format','html','cmd'); // Get the view object and attach the model object to it $view = $this->getView('List',$format,'AkeebaexampleView'); JLog::add('Attaching model to view', JLog::DEBUG); $view->setModel($model, true); // Finally, ask the view object to render itself. JLog::add('Rendering view object', JLog::DEBUG); $view->display($tpl); }
// Import the JCli class from the platform. jimport('joomla.application.cli'); /** * A "hello world" command line application class. * * Simple command line applications extend the JCli class. * * @package Joomla.Examples * @since 11.3 */ class HelloWorld extends JCli { /** * Execute the application. * * The 'execute' method is the entry point for a command line application. * * @return void * * @since 11.3 */ public function execute() { // Send a string to standard output. $this->out('Hello world!'); } } // Instantiate the application object, passing the class name to JCli::getInstance // and use chaining to execute the application. JCli::getInstance('HelloWorld')->execute();
* * @return array * * @since 11.3 */ protected function getMergedPulls() { $cutoff = 10; $page = 1; $merged = array(); while ($cutoff--) { $http = new JHttp(); $r = $http->get('https://api.github.com/repos/joomla/joomla-platform/pulls?state=closed&page=' . $page++ . '&per_page=100'); $pulls = json_decode($r->body); // Check if we've gone past the last page. if (empty($pulls)) { break; } // Loop through each of the pull requests. foreach ($pulls as $pull) { // If merged, add to the white list. if ($pull->merged_at) { $merged[] = $pull->number; } } } return $merged; } } JCli::getInstance('Changelog')->execute();
/** * Returns a reference to the global JCli object, only creating it if it * doesn't already exist. * * This method must be invoked as: $cli = JCli::getInstance(); * * @param string $name The name of the JCli class to instantiate. * * @return JCli A JCli object * * @since 11.1 */ public static function & getInstance($name = null) { // Only create the object if it doesn't exist. if (empty(self::$instance)) { if (class_exists($name) && (is_subclass_of($name, 'JCli'))) { self::$instance = new $name; } else { self::$instance = new JCli; } } return self::$instance; }
/** * Load an object or array into the application configuration object. * * @param mixed $data Either an array or object to be loaded into the configuration object. * * @return JCli Instance of $this to allow chaining. * * @since 11.1 */ public function loadConfiguration($data) { // Execute the parent load method. parent::loadConfiguration($data); /* * Setup some application metadata options. This is useful if we ever want to write out startup scripts * or just have some sort of information available to share about things. */ // The application author name. This string is used in generating startup scripts and has // a maximum of 50 characters. $tmp = (string) $this->config->get('author_name', 'Joomla Platform'); $this->config->set('author_name', strlen($tmp) > 50 ? substr($tmp, 0, 50) : $tmp); // The application author email. This string is used in generating startup scripts. $tmp = (string) $this->config->get('author_email', '*****@*****.**'); $this->config->set('author_email', filter_var($tmp, FILTER_VALIDATE_EMAIL)); // The application name. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_name', 'JDaemon'); $this->config->set('application_name', (string) preg_replace('/[^A-Z0-9_-]/i', '', $tmp)); // The application description. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_description', 'A generic Joomla Platform application.'); $this->config->set('application_description', filter_var($tmp, FILTER_SANITIZE_STRING)); /* * Setup the application path options. This defines the default executable name, executable directory, * and also the path to the daemon process id file. */ // The application executable daemon. This string is used in generating startup scripts. $tmp = (string) $this->config->get('application_executable', basename($this->input->executable)); $this->config->set('application_executable', $tmp); // The home directory of the daemon. $tmp = (string) $this->config->get('application_directory', dirname($this->input->executable)); $this->config->set('application_directory', $tmp); // The pid file location. This defaults to a path inside the /tmp directory. $name = $this->config->get('application_name'); $tmp = (string) $this->config->get('application_pid_file', strtolower('/tmp/' . $name . '/' . $name . '.pid')); $this->config->set('application_pid_file', $tmp); /* * Setup the application identity options. It is important to remember if the default of 0 is set for * either UID or GID then changing that setting will not be attempted as there is no real way to "change" * the identity of a process from some user to root. */ // The user id under which to run the daemon. $tmp = (int) $this->config->get('application_uid', 0); $options = array('options' => array('min_range' => 0, 'max_range' => 65000)); $this->config->set('application_uid', filter_var($tmp, FILTER_VALIDATE_INT, $options)); // The group id under which to run the daemon. $tmp = (int) $this->config->get('application_gid', 0); $options = array('options' => array('min_range' => 0, 'max_range' => 65000)); $this->config->set('application_gid', filter_var($tmp, FILTER_VALIDATE_INT, $options)); // Option to kill the daemon if it cannot switch to the chosen identity. $tmp = (bool) $this->config->get('application_require_identity', 1); $this->config->set('application_require_identity', $tmp); /* * Setup the application runtime options. By default our execution time limit is infinite obviously * because a daemon should be constantly running unless told otherwise. The default limit for memory * usage is 128M, which admittedly is a little high, but remember it is a "limit" and PHP's memory * management leaves a bit to be desired :-) */ // The maximum execution time of the application in seconds. Zero is infinite. $tmp = $this->config->get('max_execution_time'); if ($tmp !== null) { $this->config->set('max_execution_time', (int) $tmp); } // The maximum amount of memory the application can use. $tmp = $this->config->get('max_memory_limit', '256M'); if ($tmp !== null) { $this->config->set('max_memory_limit', (string) $tmp); } return $this; }
// Print a blank line and new heading. $this->out(); $this->out('Configuration settings loaded from configuration.php:'); // JCli will automatically look for and load 'configuration.php'. // Use the 'get' method to access any configuration properties. $this->out(sprintf('%-25s = %2d', 'Default weapon strength', $this->get('weapons'))); $this->out(sprintf('%-25s = %2d', 'Default armour rating', $this->get('armour'))); $this->out(sprintf('%-25s = %4.1f', 'Default health level', $this->get('health'))); // Print a blank line and new heading. $this->out(); $this->out('System settings:'); // There are also a number of built in properties available, for example: $this->out(sprintf('%-25s = %s', 'cwd', $this->get('cwd'))); $this->out(sprintf('%-25s = %s', 'execution.timestamp', $this->get('execution.timestamp'))); $this->out(sprintf('%-25s = %s', 'execution.timestamp', $this->get('execution.timestamp'))); // Print a blank line and new heading. $this->out(); $this->out('Custom settings:'); // We can also make custom settings during the execution of the the application using the 'set' method. $this->set('race', 'elf'); $this->out(sprintf('%-25s = %s', 'Race', $this->get('race'))); // Finish up. $this->out(); $this->out('Thanks for playing!'); $this->out(); } } // Instantiate the application object, passing the class name to JCli::getInstance // and use chaining to execute the application. JCli::getInstance('ShowConfig')->execute();
public function loadConfiguration() { return parent::loadConfiguration(); }
/** * Tests the JCli::getInstance method. * * @return void * * @since 11.3 */ public function testGetInstance() { $this->assertInstanceOf('JCliInspector', JCli::getInstance('JCliInspector'), 'Tests that getInstance will instantiate a valid child class of JCli.'); $this->inspector->setClassInstance('foo'); $this->assertThat(JCli::getInstance('JCliInspector'), $this->equalTo('foo'), 'Tests that singleton value is returned.'); $this->inspector->setClassInstance(null); $this->assertInstanceOf('JCli', JCli::getInstance('Foo'), 'Tests that getInstance will instantiate a valid child class of JCli given a non-existent type.'); }