summaryrefslogtreecommitdiffstats
path: root/tags/cpp-1.0-incubating-M2-final/sca/runtime/extensions/php/src/tuscany/sca/php/PHPServiceWrapper.cpp
blob: 1b11e660c65fc5e6f9addb11b135b3ee5d9b5fa6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/* $Rev$ $Date$ */


// some strangeness in the build that causes 
// WinSock.h and WinSock2.h to be included leading to redefinitions
#define _WINSOCKAPI_

#include "tuscany/sca/php/PHPServiceWrapper.h"

#include "osoa/sca/ServiceRuntimeException.h"
#include "tuscany/sca/util/Logging.h"
#include "tuscany/sca/util/Utils.h"
#include "tuscany/sca/model/Component.h"
#include "tuscany/sca/model/Composite.h"
#include "tuscany/sca/model/ServiceType.h"
#include "tuscany/sca/model/Interface.h"
#include "tuscany/sca/core/SCARuntime.h"
#include "tuscany/sca/php/model/PHPImplementation.h"

#include <php_embed.h>

using namespace osoa::sca;

namespace tuscany
{
    namespace sca
    {
        namespace php
        {
            // a global!! place to put the response
            // as I can't get the PHP return value
            // processing to work. Need to be
            // removed when the proper PHP SAPI is used
            // The variable is only valid between the PHP engine call and
            // the results processing. It stores the last thing that
            // the script echoed
            string scriptResponse;

            // Global callbacks used by the PHP engine

            // Callback for log messages
            void php_log_message(char *message) 
            { 
                LOGINFO_1(5, "PHP Log (%s)", message); 
            }

            // Callback for unbuffered writes (echo, print etc.)
            int php_ub_write(const char *str, unsigned int str_length TSRMLS_DC)
            {
                LOGINFO_1(5, "PHP Write (%s)", str);
                scriptResponse = str;
                return str_length;
            }

            // Callback for errors 
            void php_error_cb(int type, 
                              const char *error_filename, 
                              const uint error_lineno,
                              const char *format, va_list args)
            {
                char buffer[2048];
                int len;
				
                len = snprintf(buffer, 2048, "Error on line %d: ", error_lineno);
                vsnprintf(buffer + len, (2048 - len), format, args);
                LOGINFO_1(5, "PHP Unformatted Error (%s)", buffer);
                zend_bailout(); 
            }

            // Callback for flush (could be used to do something with the scriptResponse)
            void php_flush(void *server_context) 
            { 
                LOGINFO(5, "Flush");
            }

            // ===========
            // Constructor
            // ===========
            PHPServiceWrapper::PHPServiceWrapper(Service* service)
                : ServiceWrapper(service)
            {
                LOGENTRY(1,"PHPServiceWrapper::constructor");
    
                component = service->getComponent();
                interf = service->getType()->getInterface();
                remotable = interf->isRemotable();                

                 // -----------------------------------------------
                // Get the implementation for the target component
                // -----------------------------------------------
                PHPImplementation* impl = (PHPImplementation*)component->getType();
                if (!impl)
                {
                    string msg = "Component " + component->getName() + " has no implementation defined";
                    throw ServiceNotFoundException(msg.c_str());
                }

                LOGINFO_1(3,"PHPServiceWrapper::getServiceWrapper module %s", impl->getModule().c_str());
                LOGINFO_1(3,"PHPServiceWrapper::getServiceWrapper class %s", impl->getClass().c_str());

                LOGEXIT(1,"PHPServiceWrapper::constructor");
                
            }
            
            // ==========
            // Destructor
            // ==========
            PHPServiceWrapper::~PHPServiceWrapper()
            {
                LOGENTRY(1,"PHPServiceWrapper::destructor");
                LOGEXIT(1,"PHPServiceWrapper::destructor");
            }
            
            
            // ======================================================================
            // invoke: wrapper call to service with setting the component context
            // ======================================================================
            void PHPServiceWrapper::invoke(Operation& operation)
            {
                LOGENTRY(1,"PHPServiceWrapper::invoke");
    
                SCARuntime* runtime = SCARuntime::getInstance();
                runtime->setCurrentComponent(component);
                
                try
                {
                    LOGINFO_1(4, "PHPServiceWrapper::invoke called with operation name: %s", operation.getName().c_str());

                    // create a temporary script which
                    // - includes the named script
                    // - creates a class instance if required
                    // - calls the named method with the provided arguments
                    
                    // get the component type information
                    PHPImplementation* impl = (PHPImplementation*)component->getType();
                    
                    // first create the temporay script and include the module
                    string script = "include '" + impl->getModule() + ".php';";
                    
                    // if we have a class create an instance 
                    string className = impl->getClass();
                    if( &className != NULL && className.size() > 0)
                    {           
                      script += "$anobject = new " + className + "();";
                    }

                    // construct the call to the function
                    script += "$response = ";
                    
                    if( &className != NULL && className.size() > 0)
                    { 
                      script += " $anobject->";
                    }
                    
                    script += operation.getName().c_str(); 
                    script += "(";
                    
                    char tempString [32];

                    // add the parameters to the call
                    for(unsigned int i = 0; i < operation.getNParms(); i++) 
					{
                        const Operation::Parameter& parm = operation.getParameter(i);
    		            switch(parm.getType())
    		            {
    			            case Operation::BOOL: 
    			            {
    				            if( *(bool*)parm.getValue())
                                {
                                    //boolean true
                                    script += "true";
                                }
                                else
                                {
                                    script += "false";
                                }
    				            break;
    			            }
    			            case Operation::SHORT: 
    			            {
                                sprintf ( tempString, "%d", *(short*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::USHORT: 
    			            {
                                sprintf ( tempString, "%d", *(unsigned short*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::LONG: 
    			            {
                                sprintf ( tempString, "%d", *(long*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::ULONG: 
    			            {
                                sprintf ( tempString, "%d", *(unsigned long*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::FLOAT: 
    			            {
                                sprintf ( tempString, "%g", *(float*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::DOUBLE: 
    			            {
                                sprintf ( tempString, "%g", *(double*)parm.getValue() );
                                script += tempString;
                                break;
                            }
    			            case Operation::LONGDOUBLE: 
    			            {
                                sprintf ( tempString, "%g", *(long double*)parm.getValue() );
                                script += tempString;
    				            break;
    			            }
    			            case Operation::CHARS: 
    			            {
                                script += *(char**)parm.getValue();
    				            break;
    			            }
    			            case Operation::STRING: 
    			            {
                                script += (*(string*)parm.getValue()).c_str();
    				            break;
    			            }
                            default: 
                            {
                                throw new ComponentInvocationException("Operation parameter type not supported");
                            }
    		            }
                           
                        if ( ( i + 1 ) < operation.getNParms() )
                        {
                            script += ", ";
                        }
                    }
                    
                    
                    // the closing bracket of the call 
                    script += ");echo $response;return $response;";                  
                 
                    // we now have the temporary script to make the call
                    LOGINFO_1(5, "Executing PHP script \n%s", script.c_str());

                    // load the PHP logging and error callback methods
                    php_embed_module.log_message = php_log_message;
                    php_embed_module.ub_write    = php_ub_write;
                    php_embed_module.flush		 = php_flush;

                    //PHP_EMBED_START_BLOCK(/* argc */ 0, /* argv */ NULL)
                    void ***tsrm_ls; 
                    int status = php_embed_init(0, NULL PTSRMLS_CC);  
                    LOGINFO_1(5, "Engine startup status %d", status);

                    zend_first_try {
                        // set error handler
                        zend_error_cb = php_error_cb;

						// call the dynamically created script
                        //zval retval;
                        zend_eval_string((char *) script.c_str(), 
                                         NULL,//&retval, 
                                         "PHP Component" TSRMLS_CC);
						
                        // get the response 
                        // This doesn't want to work for some reason
                        // so have chaced the last echo that the script 
                        // returns in the global scriptResponse variable
                        // This is a bit of a rubbish way of doing things so 
                        // needs replacing when proper SAPI is used
                        //convert_to_string(&retval);
                        //LOGINFO_1(5, "Script returned %s", Z_STRVAL(retval));
                        //zval_dtor(&retval);

                        //PHP_EMBED_END_BLOCK()
                    } zend_catch {
                        int exit_status = EG(exit_status); 
                        LOGINFO_1(5, "In catch %d", exit_status);
                    } zend_end_try(); 

                    //clean up
                    php_embed_shutdown(TSRMLS_C); 
                    LOGINFO(5, "Engine shutdown");
                   
                    // get the response values
                    LOGINFO_1(5, "Script returned %s", scriptResponse.c_str());

                    switch(operation.getReturnType())
                    {
                        case Operation::BOOL: 
                            {
                                if(scriptResponse == "true")
                                {
                                    *(bool*)operation.getReturnValue() = true;
                                }
                                break;
                            }
                        case Operation::SHORT: 
                            {
                                *(short*)operation.getReturnValue() = (short) strtol(scriptResponse.c_str(), NULL,10);
                                break;
                            }
                        case Operation::LONG: 
                            {
                                *(long*)operation.getReturnValue() =  (long) strtol(scriptResponse.c_str(), NULL,10);
                                break;
                            }
                        case Operation::USHORT: 
                            {
                                *(unsigned short*)operation.getReturnValue() = (unsigned short) strtoul(scriptResponse.c_str(), NULL,10);
                                break;
                            }
                        case Operation::ULONG: 
                            {
                                *(unsigned long*)operation.getReturnValue() = (unsigned long) strtoul(scriptResponse.c_str(), NULL,10);
                                break;
                            }
                        case Operation::FLOAT: 
                            {
                                *(float*)operation.getReturnValue() = (float) strtod(scriptResponse.c_str(), NULL);
                                break;
                            }
                        case Operation::DOUBLE: 
                            {
                                *(double*)operation.getReturnValue() = (double) strtod(scriptResponse.c_str(), NULL);
                                break;
                            }
                        case Operation::LONGDOUBLE: 
                            {
                                *(long double*)operation.getReturnValue() = (long double) strtod(scriptResponse.c_str(), NULL);
                                break;
                            }
                        case Operation::CHARS: 
                            {
                                *(char**)operation.getReturnValue() = (char *)scriptResponse.c_str();
                                break;
                            }
                        case Operation::STRING: 
                            {
                                *(string*)operation.getReturnValue() = scriptResponse;
                                break;
                            }
                        default:;
                    }
                }
                catch (...)
                {
                       runtime->unsetCurrentComponent();
                    throw;
                }
                   runtime->unsetCurrentComponent();
                LOGEXIT(1,"PHPServiceWrapper::invoke");
                
            }
            
            // ======================================================================
            // getServiceWrapper: create a wrapper for the target ComponentService
            // ======================================================================
            PHPServiceWrapper* PHPServiceWrapper::getServiceWrapper(Service* service)
            {            
                LOGENTRY(1,"PHPServiceWrapper::getServiceWrapper");
                PHPServiceWrapper* serviceWrapper = 0;
                
                // ---------------------------------
                // Create an instance of the wrapper
                // ---------------------------------                
                serviceWrapper = new PHPServiceWrapper(service);
                if (!serviceWrapper)
                {
                    string msg = "Could not create new PHPServiceWrapper";
                    LOGERROR(1, msg.c_str());
                    throw ServiceNotFoundException(msg.c_str());
                }                
                
                LOGEXIT(1,"PHPServiceWrapper::getServiceWrapper");
                return serviceWrapper;
            }    

        } // End namespace php        
    } // End namespace sca
} // End namespace tuscany