summaryrefslogtreecommitdiffstats
path: root/library/SSRS/Report.php
blob: 71d786ea3584800cf47f92d7d3fd2a86135ea2d4 (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<?php

/**
 * php-ssrs http://www.apache.org/licenses/LICENSE-2.0
 *
 * @author Arron Woods <arron@idealwebsites.co.uk>
 * @link http://code.idealwebsites.co.uk/php-ssrs/
 * @copyright Copyright &copy; 2011 Ideal Websites Ltd
 * @license 
 * @version 0.1
 */

namespace SSRS;

use SoapClient;
use SoapVar;
use SoapHeader;
use SSRS\Soap\NTLM as SoapNTLM;
use SSRS\Object\CatalogItems;
use SSRS\Object\Properties;
use SSRS\Object\ItemDefinition;
use SSRS\Object\Extensions;
use SSRS\Object\ExecutionInfo;
use SSRS\Object\ExecutionParameters;
use SSRS\Object\ReportOutput;
use SSRS\Object\RenderStream;
use SSRS\Report\Exception as ReportException;

class Report {

    public $servicePath = 'ReportService2010.asmx';
    public $executionPath = 'ReportExecution2005.asmx';
    public $options;
    protected $_baseUri;
    protected $_username;
    protected $_passwd;
    protected $_soapService;
    protected $_soapExecution;
    protected $_executionNameSpace = 'http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices';
    protected $_headerExecutionLayout = '<ExecutionHeader xmlns="%s"><ExecutionID>%s</ExecutionID></ExecutionHeader>';
    protected $_sessionId;

    /**
     *
     * @param string $baseUri
     * @param array $options
     */
    public function __construct($baseUri, array $options = array()) {
        $this->setBaseUri($baseUri);

        if (array_key_exists('username', $options)) {
            $this->setUsername($options['username']);
            unset($options['username']);
        }

        if (array_key_exists('password', $options)) {
            $this->setPassword($options['password']);
            unset($options['password']);
        }

        $this->setOptions($options);
    }

    public function setOptions(array $options) {
        $defaults = array(
            'cache_wsdl_path' => null,
            'curl_options' => array(),
            'hijackActionUrls' => false
        );

        $this->options = array_merge($defaults, $options);
    }

    public function setBaseUri($uri) {
        $this->_baseUri = rtrim($uri, '/');
    }

    public function getBaseUri() {
        return $this->_baseUri;
    }

    /**
     * Sets the Soap client class with the Execution Uri so that the connection to the web service can be made.
     * Should be the custom SOAP NTLM class to bypass NTLM security.
     *
     * @param SoapClient $client 
     */
    public function setSoapExecution(SoapClient $client) {
        $this->_soapExecution = $client;
        return $this;
    }

    /**
     * Sets the Soap client class with the Service Uri so that the connection to the web service can be made.
     * Should be the custom SOAP NTLM class to bypass NTLM security.
     *
     * @param SoapClient $client
     */
    public function setSoapService(SoapClient $client) {
        $this->_soapService = $client;
        return $this;
    }

    /**
     * Returns the SOAP client Execution object so that methods of the web service can be run.
     * If the SOAP Execution object is undefined then it will be set.
     *
     * @return SoapClient
     */
    public function getSoapExecution($runInit = true) {
        if ($this->_soapExecution === null) {
            $client = $this->createNTLMClient($this->executionPath, $runInit);
            $this->setSoapExecution($client);
        }

        return $this->_soapExecution;
    }

    /**
     * Returns the SOAP client Service object so that methods of the web service can be run.
     * If the SOAP Service object is undefined then it will be set.
     *
     * @return SoapClient
     */
    public function getSoapService($runInit = true) {
        if ($this->_soapService === null) {
            $client = $this->createNTLMClient($this->servicePath, $runInit);
            $this->setSoapService($client);
        }

        return $this->_soapService;
    }

    /**
     * Sets username property
     *
     * @param string $username
     * @return \SSRS\Report
     */
    public function setUsername($username) {
        $this->_username = (string) $username;
        return $this;
    }

    /**
     * Sets password property
     *
     * @param string $password
     * @return \SSRS\Report
     */
    public function setPassword($password) {
        $this->_passwd = (string) $password;
        return $this;
    }

    /**
     * Returns username property value
     *
     * @return string
     */
    public function getUsername() {
        return $this->_username;
    }

    /**
     * Returns password property value
     * 
     * @return string
     */
    public function getPassword() {
        return $this->_passwd;
    }

    /**
     * Sets Session ID, taken from the LoadReport method under property 'ExecutionID'.
     * Required for later methods to produce report.
     * Adds to the main SOAP header through the SOAP Execution object.
     *
     * @param string $id
     */
    public function setSessionId($id) {
        $client = $this->getSoapExecution();
        $parameters = array(array('name' => 'ExecutionID', 'value' => $id));

        $headerStr = sprintf($this->_headerExecutionLayout, $this->_executionNameSpace, $id);
        $soapVar = new SoapVar($headerStr, XSD_ANYXML, null, null, null);

        $soapHeader = new SoapHeader($this->_executionNameSpace, 'ExecutionHeader', $soapVar);
        $client->__setSoapHeaders(array($soapHeader));

        $this->_sessionId = $id;
        return $this;
    }

    /**
     * Returns a list of all child items from a specified location.
     * Used to show all reports available.
     *
     * @param string $itemPath
     * @param boolean $recursive
     * @return \SSRS\Object\CatalogItems
     */
    public function listChildren($itemPath, $recursive = false) {
        $params = array(
            'ItemPath' => $itemPath,
            'Recursive' => (bool) $recursive
        );

        $result = $this->getSoapService()->ListChildren($params);
        return new CatalogItems($result);
    }

    /**
     * Returns item properties
     * 
     * @param string $path
     * @return \SSRS\Object\Properties
     */
    public function getProperties($itemPath) {
        $params = array(
            'ItemPath' => $itemPath,
        );

        $result = $this->getSoapService()->GetProperties($params);
        return new Properties($result->Values->Property);
    }

    /**
     * Returns item definition details in a XML string.
     * Used to backup report definitions into a XML based RDL file.
     *
     * @param string $itemPath
     * @return \SSRS\Object\ItemDefinition
     */
    public function getItemDefinition($itemPath) {
        $params = array(
            'ItemPath' => $itemPath,
        );
        $result = $this->getSoapService()->GetItemDefinition($params);
        return new ItemDefinition($result);
    }

    /**
     * Returns a list of all render types to output reports to, such as XML, HTML & PDF.
     *
     * @return \SSRS\Object\Extensions
     */
    public function listRenderingExtensions() {
        return new Extensions($this->getSoapExecution()->ListRenderingExtensions());
    }

    /**
     * 
     * @param type $toggleId
     * @return type
     */
    public function toggleItem($toggleId) {
        $params = array(
            'ToggleID' => $toggleId
        );
        return $this->getSoapExecution()->ToggleItem($params);
    }

    public function sort($sortId, $direction, $clear) {
        $params = array(
            'SortItem' => $sortId,
            'Direction' => $direction,
            'Clear' => $clear,
        );
        return $this->getSoapExecution()->Sort($params);
    }

    /**
     * Loads all details relating to a report including all available search parameters
     *
     * @param string $Report
     * @param string $HistoryId
     * @return \SSRS\Object\ExecutionInfo
     */
    public function loadReport($Report, $HistoryId = null) {
        $params = array(
            'Report' => $Report,
            'HistoryID' => $HistoryId
        );

        $result = $this->getSoapExecution()->LoadReport($params);
        return new ExecutionInfo($result);
    }

    /**
     * Get current execution info
     * 
     * @return \SSRS\Object\ExecutionInfo
     */
    public function getExecutionInfo() {
        $result = $this->getSoapExecution()->GetExecutionInfo2();
        return new ExecutionInfo($result);
    }

    /**
     * Sets all search parameters for the report to render.
     * Pass details from 'LoadReport' method to set the search parameters.
     * Requires the Session/Execution ID to be set.
     *
     * @param SSRS\Object\ExecutionParameters $request
     * @param string $id
     * @return SSRS\Object\ExecutionInfo
     */
    public function setExecutionParameters($parameters, $parameterLanguage = 'en-us') {
        $executionParameters = $this->factoryParameters($parameters);

        $this->checkSessionId();

        $options = array(
            'Parameters' => $executionParameters->getParameterArrayForSoapCall(),
            'ParameterLanguage' => $parameterLanguage,
        );

        $result = $this->getSoapExecution()->SetExecutionParameters($options);
        return new ExecutionInfo($result);
    }

    protected function factoryParameters($parameters) {
        if (is_array($parameters)) {
            $parameters = new ExecutionParameters($parameters);
        }

        if (false === $parameters instanceof ExecutionParameters) {
            throw new InvalidArgumentException('Invalid execution parameters argument provided');
        }

        return $parameters;
    }

    /**
     * Renders and outputs report depending on $format variable.
     *
     * @param string $format
     * @param string $PaginationMode
     * @return SSRS\Object\ReportOutput
     */
    public function render($format, $deviceInfo = array(), $PaginationMode = 'Estimate') {
        $this->checkSessionId();

        $deviceInfoDefaults = array();
        if ($this->options['hijackActionUrls']) {
            $deviceInfoDefaults['ReplacementRoot'] = '//php-ssrs//';
        }

        $deviceInfoTree = array('DeviceInfo' => array_merge($deviceInfoDefaults, $deviceInfo));

        $renderParams = array(
            'Format' => $format,
            'DeviceInfo' => $this->renderDeviceInfo($deviceInfoTree),
            'PaginationMode' => $PaginationMode
        );

        $result = $this->getSoapExecution()->Render2($renderParams);
        return new ReportOutput($result, $this->getExecutionInfo());
    }

    /**
     * 
     * @param string $format
     * @param string $streamId
     * @param array $deviceInfo
     * @return \SSRS\Object\RenderStream
     */
    public function renderStream($format, $streamId, $deviceInfo = array()) {
        $this->checkSessionId();
        $deviceInfo = array('DeviceInfo' => array_merge(array('Toolbar' => 'false'), $deviceInfo));

        $renderParams = array(
            'Format' => $format,
            'StreamID' => $streamId,
            'DeviceInfo' => $this->renderDeviceInfo($deviceInfo),
        );

        $result = $this->getSoapExecution()->RenderStream($renderParams);
        return new RenderStream($result);
    }

    /**
     * 
     * @param string $format
     * @param string $streamId
     * @param array $deviceInfo
     * @return \SSRS\Object\RenderStream
     */
    public function getRenderResource($format, $deviceInfo = array()) {
        $this->checkSessionId();

        $deviceInfo = array('DeviceInfo' => $deviceInfo);

        $renderParams = array(
            'Format' => (string) $format,
            'DeviceInfo' => $this->renderDeviceInfo($deviceInfo),
        );

        $result = $this->getSoapExecution()->GetRenderResource($renderParams);
        return new RenderStream($result);
    }

    /**
     * Checks if there is a valid Session ID set.
     *
     */
    public function checkSessionId() {
        if ($this->hasValidSessionId() === false) {
            throw new ReportException('Session ID not set');
        }
    }

    /**
     * Checks to see if the Session ID is not empty and returns boolean value
     * @return bool
     */
    public function hasValidSessionId() {
        return (!empty($this->_sessionId));
    }

    /**
     * Translate deviceInfo array into XML
     * Look out for translation entities
     * @param array $deviceInfo
     */
    public function renderDeviceInfo(array $deviceInfo) {
        $translations = array(
            '_SID_' => $this->_sessionId,
            '_TIME_' => time(),
        );
        return $this->renderXmlOptions($deviceInfo, $translations);
    }

    /**
     * Takes an array of options and converts them to an XML string recursively
     * @param array $options
     * @param array $translations
     * @return string $xml
     */
    public function renderXmlOptions(array $options, $translations = array()) {
        $xml = '';
        foreach ($options AS $key => $value) {
            switch (true) {
                case is_array($value):
                    $value = $this->renderXmlOptions($value, $translations);
                    break;
                case is_bool($value):
                    $value = ($value) ? 'true' : 'false';
                    break;
                default:
                    $value = strtr($value, $translations);
                    $value = htmlentities($value);
            }

            $key = preg_replace('/[^a-z0-9_\-]+/i', '_', $key);
            $xml .= sprintf('<%s>%s</%s>', $key, $value, $key);
        }

        return $xml;
    }

    protected function createNTLMClient($path, $runInit) {
        $options = array(
            'username' => $this->_username,
            'password' => $this->_passwd,
            'cache_wsdl_path' => $this->options['cache_wsdl_path'],
            'curl_options' => $this->options['curl_options'],
        );

        $client = new SoapNTLM($this->_baseUri . '/' . $path, $options);

        if ($runInit) {
            $client->init();
        }

        return $client;
    }

}