How to create a new .MDB file with php? - php

In our in house system, we have csv & xls files generated for users (phpexcel) from our MySQL database, but my boss is asking if is's possible to create a mdb file.
I've never come across any sample on creating a new MDB file on the fly, and I wonder if it's possible. I'm not an expert programmer by any chance, but I can manage if anyone could guide me on how I should proceed.
We're trying to reduce user load/mistakes by providing them with mdb instead of CSV that they have to import into Access. Currently they have to import over 100 csv files into Access.
Thank you.

You can use COM for accessing the MDB driver, There is a simple class located at phpclasses that acts as a wrapper for this, you can either use it for inspiration or port it directly, either way it's perfectly possible:
Here is the class, the source link is provided below:
<?php
class mdb
{
var $RS = 0;
var $ADODB = 0;
var $RecordsAffected;
var $strProvider = 'Provider=Microsoft.Jet.OLEDB.4.0';
var $strMode = 'Mode=ReadWrite';
var $strPSI = 'Persist Security Info=False';
var $strDataSource = '';
var $strConn = '';
var $strRealPath = '';
var $recordcount = 0;
var $ok = false;
/**
* Constructor needs path to .mdb file
*
* #param string $dsn = path to *.mdb file
* #return boolean success
*/
function mdb( $dsn='Please enter DataSource!' )
{
$this->strRealPath = realpath( $dsn );
if( strlen( $this->strRealPath ) > 0 )
{
$this->strDataSource = 'Data Source='.$this->strRealPath;
$result = true;
}
else
{
echo "<br>mdb::mdb() File not found $dsn<br>";
$result = false;
}
$this->RecordsAffected = new VARIANT();
$this->open();
} // eof constructor mdb()
function open( )
{
if( strlen( $this->strRealPath ) > 0 )
{
$this->strConn =
$this->strProvider.';'.
$this->strDataSource.';'.
$this->strMode.';'.
$this->strPSI;
$this->ADODB = new COM( 'ADODB.Connection' );
if( $this->ADODB )
{
$this->ADODB->open( $this->strConn );
$result = true;
}
else
{
echo '<br>mdb::open() ERROR with ADODB.Connection<br>'.$this->strConn;
$result = false;
}
}
$this->ok = $result;
return $result;
} // eof open()
/**
* Execute SQL-Statement
* #param string $strSQL = sql statement
* #param boolean $getrecordcount = true when a record count is wanted
*/
function execute( $strSQL, $getrecordcount = false )
{
$this->RS = $this->ADODB->execute( $strSQL, &$this->RecordsAffected );
if( $getrecordcount == true )
{
$this->RS->MoveFirst();
$this->recordcount = 0;
# brute force loop
while( $this->RS->EOF == false )
{
$this->recordcount++;
$this->RS->MoveNext();
}
$this->RS->MoveFirst();
}
} // eof execute()
function eof()
{
return $this->RS->EOF;
} // eof eof()
function movenext( )
{
$this->RS->MoveNext();
} // eof movenext()
function movefirst()
{
$this->RS->MoveFirst();
} // eof movefirst()
function close()
{
#$this->RS->Close(); // Generates a warning when without "#"
$this->RS=null;
#$this->ADODB->Close();
$this->ADODB=null;
} // eof close()
function fieldvalue( $fieldname )
{
return $this->RS->Fields[$fieldname]->value;
} // eof fieldvalue()
function fieldname( $fieldnumber )
{
return $this->RS->Fields[$fieldnumber]->name;
} // eof fieldname()
function fieldcount( )
{
return $this->RS->Fields->Count;
} // eof fieldcount()
} // eoc mdb
?>
And an example:
include 'class_mdb.php';
$mdb = new mdb('mymdbfile.mdb'); // your own mdb filename required
$mdb->execute('select * from table'); // your own table in the mdb file
#
# first example: using fieldnames
#
while( !$mdb->eof() )
{
echo $mdb->fieldvalue('description'); // using your own fields name
echo ' = ';
echo $mdb->fieldvalue( 1 ); // using the fields fieldnumber
echo '<br>';
$mdb->movenext();
}
echo '<br><hr><br>';
#
# Going back to the first recordset for the second example
#
$mdb->movefirst();
#
# This works, too: Make each Field an object. The values change
# when the data pointer advances with movenext().
#
$url = $mdb->RS->Fields(1);
$bez = $mdb->RS->Fields(2);
$kat = $mdb->RS->Fields(3);
while( !$mdb->eof() )
{
# works!
echo $bez->value;
echo ' = ';
echo $url->value;
echo '<br>';
$mdb->movenext();
}
$mdb->close();
Source: http://www.phpclasses.org/package/1700-PHP-Access-Microsoft-Access-mdb-database-files.html

To create a new empty Microsoft Access Database we can use ADOX.
The code below creates an empty Test.mdb file in c:\
$adox_catalog = new COM("ADOX.Catalog");
$adox_catalog->create('Provider = Microsoft.Jet.OLEDB.4.0; Data Source=c:\Test.mdb');
$adodb_conection = $adox_catalog->activeconnection();

Related

AS3 not recieving myStatus from php login page

I am not receiving the myStatus when retrieving it from the php login. I get p_id and full name but not the status. I am parsing it to separate out the & but keep getting a null result from login. section 6 and section 7 are the areas I think I am having issues can anyone help?
login AS3
package {
import flash.display.MovieClip;
import flash.text.*;
import flash.events.*;
import flash.ui.Keyboard;
import flash.net.*;
import MainDocument;
public class Login extends MovieClip {
public function Login() {
// constructor code
// modify existing text boxes
login_txt.tabEnabled = true;
login_txt.tabIndex = 1;
login_txt.border = true;
login_txt.borderColor = 0xAAAAAA;
login_txt.background = true;
login_txt.backgroundColor = 0xFFFFDD;
pwd_txt.tabEnabled = true;
pwd_txt.tabIndex = 2;
pwd_txt.border = true;
pwd_txt.borderColor = 0xAAAAAA;
pwd_txt.background = true;
pwd_txt.backgroundColor = 0xFFFFDD;
login_btn.tabEnabled = true;
login_btn.tabIndex = 3;
//add button event listeners
login_btn.addEventListener(MouseEvent.MOUSE_UP, doLogin);
login_close_btn.addEventListener(MouseEvent.MOUSE_UP, doClose);
addEventListener(KeyboardEvent.KEY_DOWN, onEnter);
} // end construtor
private function onEnter(e:KeyboardEvent):void{
// nothing yet
if(e.keyCode == Keyboard.ENTER){
trace("User presses keyboard ENTER key");
doLogin(null); // must be null to meet the need for a parameter
}// end if
}// end function
// SECTION 1 – This is a function we need for removing extra whitespace coming from CWP server
function trimWhitespace($string:String):String {
if ($string == null) {
return "";
} //end if
return $string.replace(/^\s+|\s+$/g, ""); // see regular expressions
} // end function
private function doLogin(e:MouseEvent):void{
//trace("User presses OK button");
// SECTION 2 – URL request variable declared with path to server script
var req:URLRequest=new URLRequest(MainDocument.localPath + "login.php");
req.method = URLRequestMethod.POST;
// SECTION 3 – Upload variables are named as URL variables
var vars:URLVariables=new URLVariables();
vars.login = login_txt.text;
vars.pwd = pwd_txt.text;
req.data = vars;
// SECTION 4 – The URL Loader class instance is set to perform the HTTP POST
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(req);
// SECTION 5 – listeners are added for both the HTTP status and COMPLETE
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,onHTTPStatus);
loader.addEventListener(Event.COMPLETE, retrieveData);
// SECTION 6 – The complete handler function is embedded within the doLogin() function
function retrieveData(e:Event):void {
// For the CWP server we must parse our own incoming data
var rawString:String = trimWhitespace(unescape(e.target.data));
var stArray:Array = rawString.split("&"); //split on ampersand character
trace("retrieve data");
for(var i:uint; i<stArray.length; i++){
stArray[i] = trimWhitespace(stArray[i]);
var pair:Array = stArray[i].split("=");
pair[0] = trimWhitespace(pair[0]);
switch (pair[0]){
case "myStatus":
var ms:String = trimWhitespace(pair[1]); // status data value
break;
case "p_id":
var id:int = int(trimWhitespace(pair[1])); // player id
break;
case "fullname":
var fn:String = trimWhitespace(pair[1]); // fullname
break;
default: // this is all the other junk---> dump
//do nothing
} // end switch
} //end for
// SECTION 7 – A switch statement to deal with cases of myStatus
switch (ms){
case "NOTOK" :
MainDocument.doc.showMsg("There is a communication problem\nTry Again!");
break;
case "OK" :
if(fn != "INVALID"){
MainDocument.doc.showMsg("Welcome " + fn);
//MainDocument.player_id = id;
//MainDocument.player_name = fn;
MainDocument.doc.removeLogin();
MainDocument.doc.turnOffButton("both");
//MainDocument.doc.enable_chat_button();
//MainDocument.doc.activateConsole();
////////////////////////
// start game here
////////////////////////
}else{
MainDocument.doc.showMsg("Login or password is incorrect. Try again, or \nif you are not a member, please register");
MainDocument.doc.turnOnButton("register");
MainDocument.doc.turnOffButton("login");
}
break;
default:
//MainDocument.doc.showMsg("An unknown problem has occured");
} // end switch
} // end function
// SECTION 8 – Handler function for HTTP status – also embedded
function onHTTPStatus(event:HTTPStatusEvent):void {
//trace("HTTP response code " + event.status);
if(event.status!=200){
MainDocument.doc.showMsg("There is an I/O Error #" + event.status);
} // end if
} // end function
} // end function doLogin
private function doClose(e:MouseEvent):void{
// nothing yet
trace("User presses Close button");
MainDocument.doc.showMsg(""); // clears any message
MainDocument.doc.removeLogin();
MainDocument.doc.turnOnButton("both");
}// end function
}//end class
}// end package
login.php
<?php
require_once("settings.inc.php");
// Create vars and load with incoming POST data
$login = $_POST['login'];
if(!isset($login)){
$login = $_GET['login'];
}
$pwd = $_POST['pwd'];
if(!isset($pwd)){
$pwd = $_GET['pwd'];
}
//=========================================================================================
// MAIN
//=========================================================================================
if(!(isset($login) && isset($pwd))){
print "myStatus=NOTOK&dummy=dummy";
}else{
$query = "SELECT `p_id`,`p_name` FROM `player` WHERE `p_login`='$login' AND `p_pwd`='$pwd'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_row($result);
if($row[0] != null && $row[0] != ''){
$p_id = $row[0];
$fullname = trim($row[1]);
$myStatus = $row[2];
print "myStatus=OK&p_id=" . trim($p_id) . "&fullname=" . trim($fullname) . "&dummy=dummy";
}else{
$fullname = "INVALID";
print "myStatus=OK&fullname=" . trim($fullname) . "&dummy=dummy";
} //end else
} //end else
?>

PHP+Apache2+Ubuntu Server: How to get all threads to work in parallel?

I usually work with web hosting companies but I decided to start learning working with servers to expand my knowledge.
I'll better give a real example to explain my question the best:
I have a web application that gathers data from a slow API that returns JSON data of products.
I have a function running every 1AM running a lot of queries on "id"s in my database.
Crontab:
0 1 * * * cd /var/www/html/tools; php index.php aso Cli_kas kas_alert
So this creates a process for the app (please correct me here if I'm wrong) and each process creates threads, and just to be more accurate, they are multi-threads since they do more than one thing: like pulling data from the DB to get the right variables and string them to the API queries, getting the data from the API, organizing it, searching the relevant data, and then inserting new data to the database.
The main PHP functions:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
For #Raptor, this is the function that get's the API data:
// aaa tag Query
// Gets aaa prod dataing by ID.
public function get_data_aaa_by_id_and_tg($id, $tag, $query_country){
$tag_for_url = rawurlencode($tag);
$found = FALSE;
$i = 0;
$data = array();
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
));
$context = stream_context_create($context_opts);
while ($found == FALSE) {
// aaa Query
$json_query_aaa = "https://api.example.com:443/aaa/ajax/research_tag?app_id=$id&term=$tag_for_url&page_index=$i&country=$query_country&auth_token=666";
// Get the Json
$json_query_aaa = file_get_contents($json_query_aaa, false, $context);
// Turn Json to a PHP array
$json_query_aaa = json_decode($json_query_aaa, true);
// Get the data2
$data2 = $json_query_aaa['tag']['data2'];
if (is_null($data2)){ $data2 = 0; }
// Get data3
$data3 = $json_query_aaa['tag']['phone_prod']['data3'];
if (is_null($data3)){ $data3 = 0; }
// Finally, the main prod array.
$json_query_aaa = $json_query_aaa['tag']['phone_prod']['app_list'];
if ( count($json_query_aaa) > 2 ) {
for ( $j=0; $j<count($json_query_aaa); $j++ ) {
if ( $json_query_aaa[$j]['id'] == $id ) {
$found = TRUE;
$data = $json_query_aaa[$j]['data'] + 1;
break;
}
if ($found == TRUE){
break;
}
}
$i++;
} else {
$data = 0;
break;
}
}
$data['data1'] = $data;
$data['data2'] = $data2;
$data['data3'] = $data3;
return $data;
}
All threads are stacked one after an other, and when one thread is done, only then - the second thread can proceed, ect'.
And in technical view on this, all threads wait in the RAM until the one before them is done working "inside" the CPU. (correct me if I'm wrong again :] )
This doesn't even "tickle" the servers RAM or CPU when looking at it in the process manager (I use "htop"). RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%.
Making me feel this isn't the best I can get from my current server, and getting slow results from my web app.
How do I get things done in a way that all threads work in parallel, but not to a point that my app crashes due to lacks of CPU or RAM?

sqlite3 replacement for sqlite_has_more

First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)

My iMacro script(s) doesnt run inside my PHP script. Why?

I am learning how to run iMacros from my php scripts so that PHP script calls an iMacros browser session and passes any variables that I have (url and macro name for example). The iMacros session then runs the iMacro, after the macro is done running it passes the resulting html page back to the PHP script and closes itself. In an ideal world, anyway.
Here is the iMacros calling script:
<?php
require 'src/iimfx.class.php';
$iim = new imacros();
$vars = array();
$iim->play($vars,'grab_data.iim');
?>
But when i run this script from cmd.exe [command line] on WAMP, I get this:
New imacros session started!
Using Proxy: MY_PROXY_IP:MY_PROXY_PORT
-runner -fx -fxProfile default
--------------------------------------------------------
Setting Value IP => MY_PROXY_IP
Setting Value port => MY_PROXY_PORT
Playing Macro proxy.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
--------------------------------------------------------
Playing Macro grab_google.iim
--------MACRO ERROR!-------------------
ERROR: Browser was not started. iimInit() failed?
P.S. MY_PROXY_IP and MY_PROXY_PORT are replaced with actual numbers both in error messages above and iimfx.class.php.
And here is code for the iimfx.class.php :
<?php
class imacros {
function __construct($proxyip = 'MY_PROXY_IP', $proxyport = 'MY_PROXY_PORT', $silent = false, $noexit = false) {
echo "--------------------------------------\nNew imacros session started!\nUsing Proxy: $proxyip:$proxyport\n";
$this->proxyip = $proxyip;
$this->proxyport = $proxyport;
if (empty ( $this->proxyip ))
echo "NO PROXY!!\n";
$this->noexit = $noexit;
$this->fso = new COM ( 'Scripting.FileSystemObject' );
$this->fso = NULL;
$this->iim = new COM ( "imacros" );
$toexec = "-runner -fx -fxProfile default";
if ($silent === true)
$toexec .= " -silent";
if ($noexit === true)
$toexec .= " -noexit";
echo $toexec . "\n";
$this->iim->iimInit ( $toexec );
if (! empty ( $this->proxyip )) {
$dvars ['IP'] = $this->proxyip;
$dvars ['port'] = $this->proxyport;
$this->play ( $dvars, 'proxy.iim' );
}
}
function __destruct() {
if ($this->noexit === false)
$this->iim->iimExit ();
}
function play($immvars = '', $macro) {
echo "--------------------------------------------------------\n";
if (is_array ( $immvars )) {
foreach ( $immvars as $key => $value ) {
echo "Setting Value $key => $value\n";
$this->iim->iimSet ( "-var_" . $key, $value );
}
}
echo "Playing Macro $macro\n";
$s = $this->iim->iimPlay ( $macro );
if($s>0){
echo "Macro successfully played!\n";
}else{
echo "--------MACRO ERROR!-------------------\n ERROR: " . $this->getLastError() . "\n";
}
return $s;
}
// This function retrieves extracts in your iMacros script if you have any.
function getLastExtract($num) {
return $this->iim->iimGetLastExtract ( $num );
}
// Returns the last error :)
function getLastError(){
return $this->iim->iimGetLastError();
}
// Enables/disables images
function setImages($images = 1) { // 1 = on 2 = off
$dvars ['images'] = $images;
$this->play ( $dvars, 'images.iim' );
}
// Enables or disables adblockplus
function enableABP($status = true){
$dvars['status'] = $status;
$this->play ( $dvars, 'abp.iim' );
}
}
?>
Is there something I am missing here?
I have iimRunner.exe running during all of this [started manually before running the script] and I have iMacros Browser V8+.
Also, my grab_data.iim and all other required .iim are in the same place as the php script that is trying to call them and execute them.
Any kind of help and/or steer towards the right direction would be greatly appreciated!!
Thanks in advance.
U must by start the immrunner, before start the script =)
http://wiki.imacros.net/iimRunner

php script is parsing content from RTE (tt_news) but internal links are not appearing as speaking url

I have a news article with internal links. In the RTE I see links like
http://www.yourdomain.com/?id=3
in the html text mode. The problem is that this link also appears on the frontend. RealURL should convert this link to something like
http://www.yourdomain.com/products/
The content of RTE is currently parsed like this
$parseObj = t3lib_div::makeInstance('t3lib_parsehtml_proc');
$txt = $parseObj->TS_links_rte($result['bodytext']);
$txt = $parseObj->TS_transform_rte($txt);
I read that I should use something like this
$pObj = t3lib_div::makeInstance('tslib_pibase');
$txt = $pObj->pi_RTEcssText($result['bodytext']);
but I don't know how can I access this function. I get
Fatal error: Call to a member function parseFunc() on a non-object in /home/myuser/www/home/typo3/sysext/cms/tslib/class.tslib_pibase.php on line 1384
What is the right way doing this? How can I access the function pi_RTEcssText? Do I have to use a class? Are there other ways doing it without a class?
EDIT:
I created a new template with TemplaVoila and defined lib.newscontent as TS object path.
TS Main Template
includeLibs.user_news = fileadmin/templates/php_scripts/news/class.news.php
lib.newscontent = USER_INT
lib.newscontent {
userFunc = user_news->main
userFunc.bodytext.parseFunc < lib.parseFunc_RTE
}
class.news.php
<?
class user_news {
var $cObj;
private $conf;
function main($content,$conf) {
$this->conf = $conf;
$this->setPreferences();
$content .= $this->aktuelleNews();
return $content;
}
private function aktuelleNews() {
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
'*', // SELECT ...
'tt_news', // FROM ...
'pid=22 AND deleted=0 AND hidden=0', // WHERE...
'', // GROUP BY...
'datetime DESC' // ORDER BY...
);
$i = 1;
$out_list = '<ul id="news">';
while ($data = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
$date = date("d.m.Y",$data['datetime']);
$out_list .= '<li>'.$date.': '.$data['title'].'</li>';
$out_detail.= $this->outputnewsdetail($data,$i);
$i++;
}
$out_list .= '</ul>';
return $out_list . $out_detail;
}
private function outputnewsdetail($result,$count){
$this->cObj->start($result, 'tt_news');
$bodytext = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext']);
$bodytext = $this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
return $bodytext;
}
private function setPreferences() {
}
}
?>
localconf.php
include(PATH_site.'fileadmin/templates/php_scripts/news/class.news.php');
Remaining question
Why does the rendering part in the TS Main Template doesn't work? I used
$this->cObj->parseFunc($bodytext,$GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
to get my result.
I would prefer:
$txt = $this->cObj->stdWrap($result['bodytext'], $this->conf['bodytext.']);
You need in your main method: $this->conf = $conf;
In your TypoScript add the parseFunc to bodytext:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
}
The main idea is to use the usual parseFunc which is used by content elements. So you have the same rendering. Another benefit is, that your application is more flexible.
Just as a side note. It is worth to make a lokal cObj for that and hand over the complete data. So you are able to use alle fields in TypoScript. F.e. field = bodytext in your case.
# create lokal cObj - do not override the original data!
$cObj = t3lib_div::makeInstance('tslib_cObj');
foreach ($row = ...) {
# override data array with row. Every field in $row is now accesible via
# TypoScript field = fieldname
$cObj->start($row, $tableName);
$content .= $cObj->stdWrap($row['bodytext'], $this->conf['bodytext.']);
}
# TS Setup:
# in your case you could do somesthing like:
plugin.tx_yourplugin_pi1 {
bodytext.parseFunc < lib.parseFunc_RTE
bodytext.wrap = <div class="hide">|</div>
bodytext.prepend = TEXT
bodytext.prepend.field = bodytext
bodytext.prepend.stripHtml = 1
bodytext.prepend.crop = 30 | ... | 1
bodytext.prepend.wrap = <span title="|" onclick="showBodytext()">info</span>
}
If you need it in an user function try it like this:
function user_yourfunction($content,$conf) {
$result = *magic*
$cObj = t3lib_div::makeInstance('tslib_cObj');
$cObj->start($result, 'your table name');
return $cObj->stdWrap($result['bodytext'], $conf['bodytext.']);
}
In TypoScript:
includeLibs.something = media/scripts/example_callfunction.php
page.10 = TEXT
page.10 {
value = Hello World
postUserFunc = user_yourfunction
postUserFunc.bodytext.parseFunc < lib.parseFunc_RTE
}

Categories