Category Archives: PHP

GLPI 9.1.2 fix inline images KB

First make the stored images visible in the GLPI output

In %glpiroot%/lib/htmlawed/htmlawed.php add ‘; src: data’ in line 47

output

If there where any previous inline images stored, these should now be visible in the KB. If you have images stored, but they still do not turn up, you might need to replace the ‘denied’ string stored in the glpi database. Use the SQL below to achieve this.

update glpi_knowbaseitems set answer = REPLACE(answer, 'denied:', '');
Second make inserting inline HTML images possible (within the WYSIWYG)
In %glpiroot%/inc/html.class.php file on rule 3917 add the paste plugin by adding the paste plugin and adding the paste option to the editor. Review and alter your code to reflect the snippet below:
$js = "tinyMCE.init({
language: '$language',
browser_spellcheck: true,
mode: 'exact',
elements: '$name',
relative_urls: false,
remove_script_host: false,
entity_encoding: 'raw',
menubar: false,
statusbar: false,
skin: 'light',
plugins: [
'table directionality searchreplace paste',
'tabfocus autoresize link image',
'code fullscreen textcolor colorpicker',
'paste'
],
toolbar: 'styleselect | bold italic | forecolor backcolor | bullist numlist outdent indent | table link image | code fullscreen | paste',
paste_data_images: true,
});
";
After this you should again be able to past inline HTML images into GLPI KB articles.
TIP: Use the open source Greenshot screenshot tool that supports pasting inline HTML natively.

Compile freedts 1.00 on EL6

Just a note to myself, maybe you will find this usefull as well.

In order to compile freedts-1.00 you need to have the GCC, unixODBC and unixODBC-devel packages installed.

Next download and un-tar the freedts package.
wget ftp://ftp.freetds.org/pub/freetds/stable/freetds-1.00.tar.gz

for some reason the ‘ODBC_INC’ variable isnt set properly in the configure script. This will lead to an ‘sql.h not found’ message when the –with-unixodbc switch is used. the fix for this is:

Locate the sql.h file on your system:
find / -iname sql.h -print

edit the freetds ./configure script and add the variable. Given example is specific for my system. Make sure you alter it accordingly.
ODBC_INC=”/usr/include”

Next configure the compiler
./configure –with-tdsver=7.0 –with-unixodbc=/usr/local –includedir=/usr/include

Make the install using in sequence:
make
make install
make clean

 

Howto: change the notification subject and allow KB images in GLPI version 0.90.3

For version 1.9.2 review: https://sysengineers.wordpress.com/2017/06/27/glpi-9-1-2-fix-inline-images-kb/

 

GLPI released their new version 0.90.3.
With new each release two questions seem to be very persistent. These questions are:

  1. How can we change the default notification prefix: [GLPI ] in the email  subject.
  2. How do we enable images in the KB articles.

In this article you will be able to read my personal  opinion on the matter and how to change this GLPI behavior.

Why do you want to change the GLPI  notification prefix.

The most obvious reason is to allow your customer to quickly identify your companies tickets. The rule of thumb in modern system view design is enabling users to quickly: ‘scan, select. act’ Changing the subject to something intuitive enables your customers to do so.

Another point of interest is the possibility to daisy-chain multiple installations of GLPI. By configuring the notification subjects and schemes correctly you can daisy chain multiple installations allowing cross organization enterprise environments to be set up. This is impossible when all installations identify themselfs as ‘GLPI [key].’

How to alter the code to support your custom prefix in GLPI 0.90

In order to alter the subject prefix in GLPI 0.90,  firstly you need to configure your prefix in the Administration>Entities>[your entity]>notifications>Prefix for notifications. Changing this configuration field will correctly alter the prefix to that of your liking. No further code-hacks are required or advised.

Why do you want images in your KB.

Well this is -in my humble opinion- an no brainer. One images shows more detail then i can describe in a thousand words. Images also help speed up the resolution process, especially during nightly hours. It also allows the engineer to intuitively compare the version of the actual situation with the situation documented. Is it all positive then? no, there are some downsides to consider as well.

An image doesn’t replace the engineers know-how and sometimes you want to explicitly trigger this knowledge by not showing any images. Updated applications might look different, actually slowing down the resolution process. Another more technical downside is web server storage. All images need to be stored somewhere and might needlessly clutter the support-system. My point of view is that you need to decide whats best for your situation. Sadly GLPI doesnt allow you to choose yet, it forces images to be removed. If you do need image support, please apply the code-hack below.

Be aware, This wont enable image export to pdf.

How to enable images in the KB

First we need to enable the INSERT function that enables us to add images using the TinyMCE editor. In order to do this two changes need to be made.

In the inc/html.class.php file on line:3837 and line:3871 comment out ( // ) the lines that reads _html = _html.replace .. See screenshots for more details.

Optionally you can enable the ‘image’ button by adding image to the ‘theme_advanced_buttons2 : ‘ line. See images underneath for more details.

 

The next step is to enable the images to be shown. Without this change the HTMLAWED plugin will add a denied tag to the actual images effectivly telling the browser not to show the image. Additionally the resulting HTML code including the denied: tag will be stored in database also disabling this specific image after the next code modification. Enabling the images afterward requires an search and replace statement in the database. (See comments below).

In the file /lib/htmlawed/htmLawed.php on line 47 add ‘;src: data’ to the end of the line.

Make sure you use an screenshot tool that generates an inline HTML image on the clipboard. Greenshot is an free alternative that does this out of the box.

Enjoy!

Configure unixODBC for use with PHP and MSSQL on Oracle Linux

This short article describes how to configure unixODBC 2.2.11-10.el5 in conjunction with PHP 5.3.3-26. Many forums out there contain articles that describe the absence of php_mssql drivers in the oracle yum repo. There various reason for that; non in which Oracle has a part. No matter what reason you like best, there is a decent alternative by using unixODBC.

To help all the people out that are just looking for a solution I wrote this article. I wont go into depths, ill just describe the major steps with some hints and tips. Happy reading 🙂

The OS version of my virtual box image:

Linux sandboxpinguin 2.6.18-194.0.0.0.3.el5xen #1 SMP Mon Mar 29 18:27:00 EDT 2010 x86_64 x86_64 x86_64 GNU/Linux
  1. Make sure you have the latest version of unixODBC installed. If Yum is configured correctly the following command should do the trick.
     yum update unixODBC
  2. Download the freeDTS driver, this is the driver unixODBC will use to connect to mssql. If wget is available on your production environment (remove it) after running the command:
     wget ftp://ftp.freetds.org/pub/freetds/stable/freetds-stable.tgz

    . Make sure you are in an desired location like your home folder.

  3. Unpack the tar-Gzip ball by running the following command
    tar -xf  ./freetds-stable.tgz
  4. Browse into the unpacked folder and run the configure command
    ./configure --with-tdsver=7.2 --enable-msdblib
  5. If the configure ran without any issues you can link/compile the driver by running the command:
    make

    and then

    make install

    and then

    make clean

    Congratulations, you are now the pride owner of the freeDTS driver 🙂

The next part tend to get a bit fuzzy, feel free to ask questions in the comment and ill try to answer them to the best of my ability.

There are allot of articles available on how to configure the unixODBC DSN correctly. Be adviced: the config is specific for your setup and usually needs to be tweaked. In order to enable you to ill explain the concepts of unixODBC. Ill point out some documentation, commands and stuff. Afterward ill have a short tutorial of the steps i used to configure the odbc connection.

  1. unixODBC is configured properly by using the
    odbcinst

    command.

  2. unixODBC will write into:
    odbc.ini

    files and uses input files to do so;

  3. The connection can be tested with osql commands from bash, but! it will use the hidden .odbc.ini file in your profile instead of the /etc/odbc.ini. PHP and odbcinst use the one in /etc/odbc.ini. If the one in your profile works than make sure it is identical to the one located in /etc/ directory. Below how the osql output will look if configured correctly. (charset isnt relevant in this stage)
    screenshot
  4. Documentation on how to use FreeTDS in conjunction with unixODBC can be found here.
    http://www.freetds.org/userguide/odbcconnattr.htm
  5. Documentation on how to use ODBC can be found here
    http://www.unixodbc.org/odbcinst.html
    (ignore the freetds configuration here and use ad4 to figure the settings out for your setup)

Next ill describe my steps in order to make it work.

Configuring the FreeTDS driver

  1. Create the file /etc/odbcDriver.ini
  2. Insert the following in the file (check the paths)
    [FreeTDS]
    Description     = FreeTDS Driver with protocol v5.0
    Driver          = /usr/local/freetds/lib/libtdsodbc.so
    
  3. Create the file /etc/odbc.ini
  4. Insert the following and tweak this to match your environment
    [ExampleSource]
    Description     = FreeTDS Driver with protocol v5.0
    Driver          = /usr/local/freetds/lib/libtdsodbc.so
    Server          = [SERVERIP]
    Port            = [REMOTE_TSQL_PORT]
    ClientCharset   = UTF-8
    TDS_Version     = 7.1
    Database        = [DATABASENAME]
    Trusted_Connection = Yes      # Required with most MSSQL environments.
    
  5. Register the ODBC driver
     odbcinst -i -d -f /etc/odbcDriver.ini 
  6. Register the data source
     odbcinst -i -s -f /etc/odbc.ini

Finally test your config by using the php odbc functions.

<?php
$sql = "select 1 + 5 as outcome";

$conn = odbc_connect("ExampleSource" , "Username", "Password");
$result = odbc_exec($conn, $sql);
$row = odbc_fetch_array($result);
echo $row['outcome'];

Good luck querying 🙂

No tuples available at this result index in […]

Recently I was creating a simple PHP webpage that required an MSSQL connection for a query. I installed the freetds-0.91-15 driver on my Oracle Linux and configured unixODBC-2.2.11-10.el5 appropriately. All went well and I soon had the first results on my page. My next task was to create a simple enough query that would ‘count’ some database rows. Simple enough, right? Well, at least up to the part where I ran into this error:

No tuples available at this result index in […]

All the posts I found referred to multiple result sets in which ‘odbc_next_result($result);’ should be the resolution. The weird part was, pasting of the echoed $sql into the MSSQL query box would give me the desired effect. One result with an count of the rows. The same SQL in the PHP script would give me the ‘no tuples’ error. I nearly fixed it the ugly way (counting the rows in an php while that would work) when I had an insight.

In the mssql output i noticed NULL fields in the table column that I was counting. So i figured, might counting NULL values somehow trigger the ‘No Tuples’ error im getting?

So this is what I ended up testing:

SELECT COUNT([sdk].[Events].[FirstName]) as Counted FROM [sdk].[Events]
WHERE [sdk].[Events].[PeripheralName] like '%Search%'
AND [sdk].[Events].[EventTime] BETWEEN '1' AND '31'

Which resulted in : Warning: odbc_fetch_array(): No tuples available at this result index in /var/www/db.class.php on line 52

SELECT COUNT([sdk].[Events].[FirstName]) as Counted FROM [sdk].[Events]
WHERE [sdk].[Events].[PeripheralName] like '%Search%'
AND [sdk].[Events].[EventTime] BETWEEN '1' AND '31'
AND [sdk].[Events].[FirstName] is not null

Which resulted in an working count query.

Extract all content to disk from a SPS2007 content DB using PHP

Today I ran into a problem. We needed to migrate a huge amount of data from an old SharePoint 2007 content database without the availability of the MOSS front-end. All i had was the database and a corrupted sharepoint install that wasnt going to help me allot.

To overcome this problem I decided to write a little PHP application that would do this task for me. I allready had WAMP setup on my desktop, so i figured this to be the quickest route. Then i figured, maybe other people face this problem as well. So here it is, the code, and some helpers to get you going.


<?php
/**
* @name           : index.php - MSSql Content connector
* @Author        : Chris Gralike
* @version        :
* @copyright     : WETFYWTDWI - what ever ** you want to do with it, no guarantees 🙂
*  This script ONLY READS the database tables, so dont give it more permissions 🙂
*/

// What to search for in the directory structure.
$search = '';
// Where too put the files
$createdir = './Downloaded';
// What server too connect to.
$ServerName = 'amisnt05.amis.local';
// Database connection parameters.
$connectionInfo = array('Database' => 'MOSS_PROD_WSS_Content_WebApp02',
'UID' => 'php_login',
'PWD' => 'welcome12345678');
// This can be a very long task to complete, so disable the timelimit.
set_time_limit(0);
// Create a connection
$conn = sqlsrv_connect($ServerName, $connectionInfo)
or die( print_r( sqlsrv_errors(), true));

// The SQL statment to query the AllDocs tables.
$tsql = "SELECT dbo.AllDocs.Id,
dbo.AllDocs.SetupPath,
dbo.AllDocs.LeafName,
dbo.AllDocs.DirName,
dbo.AllDocs.SetupPath,
dbo.AllDocs.Extension,
dbo.AllDocs.ExtensionForFile,
dbo.AllDocStreams.Id as StreamId,
dbo.AllDocStreams.Content
FROM dbo.AllDocs
RIGHT OUTER JOIN dbo.AllDocStreams ON dbo.AllDocs.Id = dbo.AllDocStreams.Id
WHERE AllDocs.DirName LIKE '%{$search}%'
AND AllDocs.SetupPath IS NULL
AND AllDocs.Extension != ''
";
// The result set
$result = sqlsrv_query($conn, $tsql);

// Process the results
while($row = sqlsrv_fetch_array($result,  SQLSRV_FETCH_ASSOC)){
// When create is true, then it will create the folders in
// in the foreach
$create = false;
$dirptr = $createdir;

// Find the folders and recreate them starting from the searchstring.
$folders = explode('/', $row['DirName']);
foreach ($folders as $val){
if($val == $search || $create == true || empty($search)){
$create = true;
$dirptr .= '/'.$val;
if(!is_dir($dirptr)){
mkdir($dirptr);
echo "INFO: created $dirptr <br/>";
}else{
echo "WARN: skipping $dirptr allready exists. <br />";
}
}
}

// Recreate the file
$filepath = $dirptr.'/'.$row['LeafName'];
if(!is_file($filepath)){
touch($filepath);
}
if($fp = fopen($filepath,'w')){
fwrite($fp, $row['Content']);
echo "INFO: file {$row['LeafName']} written. <br />";
}else{
echo "ERROR: file {$row['LeafName']} could not be written in $filepath. <br />";
}
fclose($fp);
}
// Close the database connection.
sqlsrv_close($conn);
?>

Simply configure the first vars in the script and run the file. It might take a huge while before you get some output.

TIP: Use the $search to narrow down the query a bit.
It searches the DirName (I.e. Site\DocLib\Folder\SubFolder\)

The output will look like this.

INFO: created ./Downloaded/SearchCenter
INFO: created ./Downloaded/SearchCenter/Pages
INFO: file facetedsearch.aspx written.
WARN: skipping ./Downloaded/SearchCenter allready exists.
WARN: skipping ./Downloaded/SearchCenter/Pages allready exists.
INFO: file resultskeyword.aspx written.

ANY THOUGHTS, OR NEED SOME HELP?
Then please leave a comment 🙂

WARNING!: YOU NEED THE Microsoft MSSQL DRIVER FOR PHP, not the old php equivalent.
here are some tips on where to get it. My version was php 5.3.8

First off, mssql isnt supported out of the box anymore. when using PHP 5.2 and up, you need to get the Microsoft for PHP driver. Check this site for more information : http://sqlsrvphp.codeplex.com/

Its a bit of an hassle ill give you that.
Challenge: I needed 1.5hours to find the correct Lib,Install,Coding info and get it working.

Basically it requires you to download the native client, the drivers and an correct update of the php.ini your wamp instance is using.

Tip: Use <?php phpinfo() ?> to find the right version for your PHP compilation.
Search for : PHP Extension Build : API20090626,TS,VC9

DIFFERENT SHAREPOINT VERSION?!

Be sure to verify the SQL query inside the $tsql=” var and alter it accordingly. The other part should be pretty straight forward.

simple fix for Joomla rss (com_ninjarssyndicator) blank line issue.

Like many we experienced the blank line issue within the Joomla RSS ninja syndicator. The effect of this blank line is that it is not being recognized by rss parsers. To overcome this little issue without needing to hack all the joomla plugin source files in search of this blank line i simply wrote a little PHP script that removes this first line if its there, else it will simply output the rss.

I used this broken company training feed  and fixed it using php. You can view them here.

http://www.amis.nl/index.php?option=com_ninjarsssyndicator&feed_id=7&format=raw
http://technology.amis.nl/blog/xmlfeed.php?id=1

The script to fix it is shown below. Simply alter the urls and paste it inside a php file somewhere on your webserver.

<?php
///////
// Very simple script to clean the blankline from an RSS FEED.
$default = 2; // Default feed id.

if(isset($_GET{'id'})){
   if(is_numeric($_GET{'id'})){
      $index = $_GET{'id'};
   }else{
      $index = $default;
   }
}else{
   $index = $default;
}

$url = 'http://www.domain.ext?option=com_ninjarsssyndicator&feed_id='.$index.'&format=raw';

if($lines = file($url)){
   foreach($lines as $n => $l){
     if(ord($l) != '10'){
       echo "$l";
     }
   }
}
exit;
?>

mod_access.so missing in apache 2.2.19? Check This!

Hi there admins,

Today I spend an hour figuring out why the “Order” directive in apache 2.2.19 resulted in errors.

Knowing that “Order” was previously provided by “mod_access.so” i started my quest in figuring out why that module was missing. What did i find?

Mod_access was renamed or recompiled to “mod_authz_host.so”.
as described here…

http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html

after adding the module again it worked like a bliss 🙂

Howto compile apache 2.2.x?, heres a hint 🙂

./configure --prefix=/u01/proxy/ #Where to install?\
--enable-ssl=shared \
--enable-proxy=shared \
--enable-proxy-connect=shared \
--enable-proxy-ftp=shared \
--enable-proxy-http=shared \
--enable-proxy-ajp=shared \
--enable-proxy-balancer=shared \
--enable-cache=shared \
--enable-file-cache=shared \
--enable-mem-cache=shared \
--enable-disk-cache=shared \
--enable-deflate=shared \
--enable-http=shared \
--enable-dav=shared \
--enable-vhost-alias=shared \
--enable-rewrite=shared \
--enable-so=shared \
--with-ssl=/usr/bin/openssl > ./reviewlog.txt
make >> ./reviewlog.txt
make install >> ./reviewlog.txt
make clean

http://httpd.apache.org/docs/2.2/new_features_2_2.html#module

SOAP to JSON using PHP

For anyone that wants to translate output from a SOAP webservice using WLSD to JSON… Here is an example script that shows you the basics 🙂

This is a working example.

You need at least PHP 5.1 for this example to work!

<?php
// Setup and connect the soap client object
try{
	$sc = @new SoapClient('http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL');
} catch (Exception $e) {
	echo $e->getMessage();
}

// Fetch the uri parameter //
if(isset($_GET{'c'}) && !empty($_GET{'c'})){
	$country{'name'} = addslashes(ucwords($_GET{'c'}));
}else{
	$country{'name'} = 'FALSE';
}

// Query the soap webservice
$result = $sc->CountryISOCode(array('sCountryName' => $country{'name'}));
$result = $sc->FullCountryInfo( array(sCountryISOCode => $result->CountryISOCodeResult));

// Output the Json code
echo json_encode($result->FullCountryInfoResult);


print('<h2>Functions described in wsdl</h2><br\>');
foreach($sc->__getFunctions() as $key => $value){
	echo "$key => $value <br/>";
}

print('<h2>Types described in wsdl</h2><br\>');
foreach($sc->__getTypes() as $key => $value){
	echo "$key => $value <br/>";
}

?>

Goodluck , and happy scripting! 🙂

Draw dots in images using PHP, XMLHttp, Mysql.

A family member asked me if it was possible to use html, php, mysql to mark spots in an image of the human skeleton during an medical anamnesis collection. He wanted this to easily mark the complaint spots of his patients. He also needed to be able to remove marks when they where faulty and wanted this all to be stored in a database for easy reference and backup.

Seeing the complexity of it, I accepted the challenge he laid out for me.

The most complex part of this was the ‘how to remove’ spots from an image without deleting the actual fixed image of the skeleton. The solution I came up with was using an Fixed background image in HTML and use a transparent overlay that I will be updating using PHP and XMLHttp request headers.

The result of this approach was the following.

All that needs to be done during reporting is merging both images together, which is fairly easy using php.

But because I though someone else might use this script as well, I thought sharing it here with the world was a nice option. The application is endless, from damage reporting to Location reporting, and in the finished from its fairly easy to understand and adjust to your needs.

I added the sourcecode for this script to this post. You need to have a mysql database, php with GD enabled, browser that supports XHTMLRequest (all modern browsers). Simply dump the files into the a php html enabled location and make sure you create the required SQL table (usign the .sql script inside the archive) and have a go with it (you might need to alter the mysql user/pass inside the PHP script)….

image_draw-rar.pdf

Use the “save as” option to grab the file from this site. Rename the file to something.zip, unpack and access the srcfiles inside the rar archive… use winrar to unpack.

Let me know what you think, or if you found it usefull 🙂

p.s. I wasnt able to verify the author of the used skeleton image. If you are/know him, let me know if this application is allowed, and how to publish the credits.