How can I run a TYPO3 extension in cron jobs? - cron

Can anyone tell me how to setup a cronjob in TYPO3? I've created a TYPO3 extension which I want to run once a week. I've already installed the scheduler extension, but it only allows some extensions (e.g., tt_news ) to be executed.
Thank you.

your extension must support the Scheduler - system extension (maybe you'll need to install it first). Therefore you have to register your extension in the Scheduler Service.
via your ext_localconf.php
if (!defined ('TYPO3_MODE')) die ('Access denied.');
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks']['TX_YOUR_EXTENSIONKEY'] = array(
'extension' => $_EXTKEY,
'title' => 'Some meningful Title',
'description' => 'Some Discription of the Task'
);
you need to create the file tasks/class.TX_YOUREXTENSKEY.php in your extension directory
class TX_YOUREXTENSKEY extends tx_scheduler_Task {
public function execute() {}
...
}
the execute function is called if the task gets executed. it should return true if everything went fine and false if you got some error.
at last your class needs to be loaded this can be done using ext_autoload.php (in your extension root, see TYPO3 Wiki: Autoload for more details)
<?php
return array(
'tx_sfpinger_pinger' => t3lib_extMgm::extPath('sfpinger', 'tasks/class.tx_sfpinger_pinger.php')
);
?>
Finally you need to add to your system cron command that will be running Scheduler ext periodically (you'll find it on the Scheduler's Setup check section) and also add your created task to the its tasks list.
You can check a demo task which is just a sample from which you can copy code and paste in your extension.
Also check documentation delivered with scheduler task in folder on your TYPO3 implementation: /typo3/sysext/scheduler/doc/manual.sxw

Related

Manually call a cron task Symfony 1.4

I have a cron task placed under myProject/lib/task. This cron works daily for over a year.
However now I have to create a button inside my project to do the same process as the cron whenever my client needs. The code is too complex and I can't rewrite everything on a normal action.
Is there a way to call a cron task from a normal action?
Here's how you can call a task from an action, you just need to add a link to it and you'll be good. I've used the standard Symfony 'Clear Cache' task in the example, but you can change it to yours:
public function executeRunTaskTest(sfWebRequest $request)
{
// need to be working in the project root
chdir(sfConfig::get('sf_root_dir'));
// init the task we want to run
$task = new sfCacheClearTask($this->dispatcher, new sfFormatter());
// run the task
$task->run(
array(), // array of arguments
array(
'app' => 'frontend',
'env' => 'prod',
'type' => 'all',
) // array of options
);
// back to where we came from
$this->redirect($request->getReferer());
}
You could also use the PHP exec() or shell_exec() functions, but this Symfony solution is probably easier. :)

Can js code in chrome extension detect that it's executed as content script?

I have a google chrome extension that shares some code between it's content script and background process / popup. If it some easy and straightforward way for this code to check if it's executed as content script or not? (message passing behavior differs).
I can include additional "marker" javascript in manifest or call some chrome fnction unavailable from content script and check for exceptions - but these methods looks awkward to be. Maybe it's some easy and clean way to make this check?
To check whether or not your script is running as a content script, check if it is not being executed on a chrome-extension scheme.
if (location.protocol == 'chrome-extension:') {
// Running in the extension's process
// Background-specific code (actually, it could also be a popup/options page)
} else {
// Content script code
}
If you further want to know if you're running in a background page, use chrome.extension.getBackgroundPage()=== window. If it's true, the code is running in the background. If not, you're running in the context of a popup / options page / ...
(If you want to detect if the code is running in the context of an extension, ie not in the context of a regular web page, check if chrome.extension exists.)
Explanation of revised answer
Previously, my answer suggested to check whether background-specific APIs such as chrome.tabs were defined. Since Chrome 27 / Opera 15, this approach comes with an unwanted side-effect: Even if you don't use the method, the following error is logged to the console (at most once per page load per API):
chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.
This doesn't affect your code (!!chrome.tabs will still be false), but users (developers) may get annoyed, and uninstall your extension.
The function chrome.extension.getBackgroundPage is not defined at all in content scripts, so alone it can be used to detect whether the code is running in a content script:
if (chrome.extension.getBackgroundPage) {
// background page, options page, popup, etc
} else {
// content script
}
There are more robust ways to detect each context separately in a module I wrote
function runningScript() {
// This function will return the currently running script of a Chrome extension
if (location.protocol == 'chrome-extension:') {
if (location.pathname == "/_generated_background_page.html")
return "background";
else
return location.pathname; // Will return "/popup.html" if that is the name of your popup
}
else
return "content";
}

How to modify dashlets to auto-refresh?

Is there a simple way to modify a dashlet to automatically re-load itself periodically?
I am particularly thinking of the "My Tasks" dashlet - we are using pooled review workflows, so tasks may come and go all the time as they are created and then are claimed.
It may be frustrating for users to keep clicking on tasks that turn out to have already been claimed - or having to remember to keep re-loading their Dashboard page. I'd prefer the dashlet to refresh on a timed interval so it's always reasonably up to date.
In order to do this you will need to add a new capability to the client-side class Alfresco.dashlet.MyTasks (docs, source) found in the file components/dashlets/my-tasks.get.js. First you will need to add a new method to the prototype extension specified as the second parameter in the YAHOO.lang.augmentObject() call, e.g.
...
}, // end of last OOTB function - add a comment here
// begin changes
reloadData: function MyTasks_onReady()
{
this.widgets.alfrescoDataTable.loadDataTable(
this.options.filters[this.widgets.filterMenuButton.value]
);
}
// end changes
});
})();
It's not the ideal development environment, you can modify the JS file directly in the Share webapp, although you will also need to update the corresponding -min.js file.
Once you've done this, check that it works by running the following line in your browser's JavaScript console
Alfresco.util.ComponentManager.findFirst("Alfresco.dashlet.MyTasks").reloadData();
If that works, then you can wire up your new method to a title bar action (see my DevCon presentation for more background info), in the dashlet web script. The method depends on whether you are using v4.2 or a previous version, but if it is the latter then you need to add some code to the dashlet's Freemarker file my-tasks.get.html.ftl (under WEB-INF/classes/alfresco/site-webscripts/org/alfresco/components/dashlets).
In that file you should see some JavaScript code inside a <script> tag, this sets up an instance of the client-side class and some utility classes, the contents of which you can replace with the following, to add your custom title bar action.
(function()
{
var dashlet = new Alfresco.dashlet.MyTasks("${jsid}").setOptions(
{
hiddenTaskTypes: [<#list hiddenTaskTypes as type>"${type}"<#if type_has_next>, </#if></#list>],
maxItems: ${maxItems!"50"},
filters:
{<#list filters as filter>
"${filter.type?js_string}": "${filter.parameters?js_string}"<#if filter_has_next>,</#if>
</#list>}
}).setMessages(${messages});
new Alfresco.widget.DashletResizer("${id}", "${instance.object.id}");
var refreshDashletEvent = new YAHOO.util.CustomEvent("onDashletRefresh");
refreshDashletEvent.subscribe(dashlet.reloadData, dashlet, true);
new Alfresco.widget.DashletTitleBarActions("${args.htmlid}").setOptions(
{
actions:
[
{
cssClass: "refresh",
eventOnClick: refreshDashletEvent,
tooltip: "${msg("dashlet.refresh.tooltip")?js_string}"
},
{
cssClass: "help",
bubbleOnClick:
{
message: "${msg("dashlet.help")?js_string}"
},
tooltip: "${msg("dashlet.help.tooltip")?js_string}"
}
]
});
})();
You will need to add some styles for the class name specified, in the dashlet's CSS file my-tasks.css, such as the following
.my-tasks .titleBarActions .refresh
{
display: none;
background-image: url('refresh-icon.png');
}
The icon file (here is one you could re-use) must be in the same directory as the CSS file.
Lastly you'll need to define the label dashlet.refresh.tooltop used for the title bar action's tooltip. You can do this in the dashlet web script's .properties file.
For a similar example, check out the source of my Train Times dashlet, which features a refresh title bar action.
In some ways it's actually easier to define your own dashlets than it is to extend the Alfresco-supplied ones, but if you have the option of using 4.2.x, the new method allows you to extend the existing components without duplicating any code, which obviously makes upgrades much easier.

Cron and WordPress don't work. What have I forgotten?

I'm trying to implement a cron job in my wordpress blog. I want to do this stuff in a plugin, for testing I'm trying to write in one file some log information every 10 minutes, for do that I wrote this code (PHP):
add_filter( 'cron_schedules', 'ten_minute_prefix' );
function ten_minute_prefix( $schedules )
{
$schedules['tenmins'] = array(
'interval' => 600,
'display' => __( '10 minutes' ),
);
return $schedules;
}
//This must be here always
add_action('my_task_hook', 'foo_task');
function foo_task()
{
file_put_contents('data.txt', date("Y-m-d H:i:s") . "task do it\r\n", FILE_APPEND);
}
//This is executing in my plugin page in tools section
function myplugin()
{
//For checking permissions
file_put_contents('data.txt', date("Y-m-d H:i:s") . "Task begin\r\n", FILE_APPEND);
wp_schedule_event( time(), 'tenmins', 'my_task_hook' ); // hourly, daily and twicedaily
echo "SCHEDULE ACTION";
...
}
For checking that i have created really the cron job, i using for example this plugin http://wordpress.org/extend/plugins/cron-view/. This plugin says me this "Entry #10: my_task_hook √ action exists".
But nothing is happening, the file is not written, what is the problem?
Edit:
I have added one line in myplugin function for see if i have permission for writing files. In fact, i have got permissions, a data.txt file is created in wp-admin/ folder.
Edit2:
I just to understand the cron jobs in wordpress!
Cron in wordpress is not a real cron, it only fires when any user opens the webpage, if no one opens the page, the process won't fire. So, if a blog has not visitors, cron jobs dont work.
Please, correct me if i am in a mistake.
It could be because you don't have write permissions to write to the folder where data.txt is in. As you haven't explicitly defined which folder to write to, it will write to the folder your PHP file is in.
1) right. check is your directory writable...
if (is_writable(dirname(__FILE__))){
file_put_contents(dirname(__FILE__).'/data.txt', date("Y-m-d H:i:s") . "task do it\r\n", FILE_APPEND);
} else {
mail('yourmail#example.com', 'oops!', 'error writing');
}
2) where is your cron scheldule activated?
add_action('activate_' . __FILE__, 'plugin_activate_demo'));
add_action('deactivate_' .__FILE__, 'plugin_deactivate_demo'));
function plugin_activate_demo(){
wp_schedule_event( time(), 'tenmins', 'my_task_hook' );
}
function plugin_deactivate_demo(){
wp_clear_scheduled_hook('my_task_hook' );
}
3) almost imposible situation which i got on work - Check do you have working cron... simple by adding mail or something like that to your hook_action code. on some servers due dns problems (many networked servers and url routes issue) server name not responding while http://yourservername.com requested (by wp-cron).

Expressionengine hooks

I have a safecracker form that submits an entry. The form consists of title, url_title, and description. I want to create an extension hook that filters out certain words if they exist in the title of the entry.
I already have a function that take care of the cleaning function clean(){....}. I understand that we need to use an extension hook so we can clean the title upon saving the entry.
What extension hook do i need to use for that. can you give me a complete example of an extension hook. I'm very good with PHP but still new to hooks and how they should be implemented. I already read the EE documentation but still find some confusion of how a hook is used
First head over to http://pkg.io/ and get your base extension file.
You'll probably want to use the 'safecracker_submit_entry_start' hook to throw an error if unclean word is entered. The most important part of the extension is registering the method and hook you want to use, otherwise none of the code will run.
Your code should look something like this:
public function activate_extension()
{
// Setup custom settings in this array.
$this->settings = array();
$data = array(
'class' => __CLASS__,
'method' => 'clean', // point to the method that should run
'hook' => 'safecracker_submit_entry_end', // point to the hook you want to use to trigger the above method.
'settings' => serialize($this->settings),
'version' => $this->version,
'enabled' => 'y'
);
$this->EE->db->insert('extensions', $data);
}
Once the method has been called you can start your cleaning. Make sure you pass the safecracker object to your clean method when defining it. For example:
public function clean($sc){
print_r($sc);
}

Resources