Minor dependency updates
[yaffs-website] / vendor / easyrdf / easyrdf / lib / EasyRdf / Utils.php
1 <?php
2
3 /**
4  * EasyRdf
5  *
6  * LICENSE
7  *
8  * Copyright (c) 2009-2013 Nicholas J Humfrey.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright notice,
15  *    this list of conditions and the following disclaimer in the documentation
16  *    and/or other materials provided with the distribution.
17  * 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
18  *    promote products derived from this software without specific prior
19  *    written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  * @package    EasyRdf
34  * @copyright  Copyright (c) 2009-2013 Nicholas J Humfrey
35  * @license    http://www.opensource.org/licenses/bsd-license.php
36  */
37
38
39 /**
40  * Class containing static utility functions
41  *
42  * @package    EasyRdf
43  * @copyright  Copyright (c) 2009-2013 Nicholas J Humfrey
44  * @license    http://www.opensource.org/licenses/bsd-license.php
45  */
46 class EasyRdf_Utils
47 {
48
49     /**
50      * Convert a string into CamelCase
51      *
52      * A capital letter is inserted for any non-letter (including userscore).
53      * For example:
54      * 'hello world' becomes HelloWorld
55      * 'rss-tag-soup' becomes RssTagSoup
56      * 'FOO//BAR' becomes FooBar
57      *
58      * @param string The input string
59      * @return string The input string converted to CamelCase
60      */
61     public static function camelise($str)
62     {
63         $cc = '';
64         foreach (preg_split('/[\W_]+/', $str) as $part) {
65             $cc .= ucfirst(strtolower($part));
66         }
67         return $cc;
68     }
69
70     /**
71      * Check if something is an associative array
72      *
73      * Note: this method only checks the key of the first value in the array.
74      *
75      * @param mixed $param The variable to check
76      * @return bool true if the variable is an associative array
77      */
78     public static function isAssociativeArray($param)
79     {
80         if (is_array($param)) {
81             $keys = array_keys($param);
82             if ($keys[0] === 0) {
83                 return false;
84             } else {
85                 return true;
86             }
87         } else {
88             return false;
89         }
90     }
91
92     /**
93      * Remove the fragment from a URI (if it has one)
94      *
95      * @param mixed $uri A URI
96      * @return string The same URI with the fragment removed
97      */
98     public static function removeFragmentFromUri($uri)
99     {
100         $pos = strpos($uri, '#');
101         if ($pos === false) {
102             return $uri;
103         } else {
104             return substr($uri, 0, $pos);
105         }
106     }
107
108     /** Return pretty-print view of a resource URI
109      *
110      * This method is mainly intended for internal use and is used by
111      * EasyRdf_Graph and EasyRdf_Sparql_Result to format a resource
112      * for display.
113      *
114      * @param  mixed  $resource An EasyRdf_Resource object or an associative array
115      * @param  string $format   Either 'html' or 'text'
116      * @param  string $color    The colour of the text
117      * @return string
118      */
119     public static function dumpResourceValue($resource, $format = 'html', $color = 'blue')
120     {
121         if (!preg_match('/^#?[-\w]+$/', $color)) {
122             throw new InvalidArgumentException(
123                 "\$color must be a legal color code or name"
124             );
125         }
126
127         if (is_object($resource)) {
128             $resource = strval($resource);
129         } elseif (is_array($resource)) {
130             $resource = $resource['value'];
131         }
132
133         $short = EasyRdf_Namespace::shorten($resource);
134         if ($format == 'html') {
135             $escaped = htmlentities($resource, ENT_QUOTES);
136             if (substr($resource, 0, 2) == '_:') {
137                 $href = '#' . $escaped;
138             } else {
139                 $href = $escaped;
140             }
141             if ($short) {
142                 return "<a href='$href' style='text-decoration:none;color:$color'>$short</a>";
143             } else {
144                 return "<a href='$href' style='text-decoration:none;color:$color'>$escaped</a>";
145             }
146         } else {
147             if ($short) {
148                 return $short;
149             } else {
150                 return $resource;
151             }
152         }
153     }
154
155     /** Return pretty-print view of a literal
156      *
157      * This method is mainly intended for internal use and is used by
158      * EasyRdf_Graph and EasyRdf_Sparql_Result to format a literal
159      * for display.
160      *
161      * @param  mixed  $literal  An EasyRdf_Literal object or an associative array
162      * @param  string $format   Either 'html' or 'text'
163      * @param  string $color    The colour of the text
164      * @return string
165      */
166     public static function dumpLiteralValue($literal, $format = 'html', $color = 'black')
167     {
168         if (!preg_match('/^#?[-\w]+$/', $color)) {
169             throw new InvalidArgumentException(
170                 "\$color must be a legal color code or name"
171             );
172         }
173
174         if (is_object($literal)) {
175             $literal = $literal->toRdfPhp();
176         } elseif (!is_array($literal)) {
177             $literal = array('value' => $literal);
178         }
179
180         $text = '"'.$literal['value'].'"';
181         if (isset($literal['lang'])) {
182             $text .= '@' . $literal['lang'];
183         }
184         if (isset($literal['datatype'])) {
185             $short = EasyRdf_Namespace::shorten($literal['datatype']);
186             if ($short) {
187                 $text .= "^^$short";
188             } else {
189                 $text .= "^^<".$literal['datatype'].">";
190             }
191         }
192
193         if ($format == 'html') {
194             return "<span style='color:$color'>".
195                    htmlentities($text, ENT_COMPAT, "UTF-8").
196                    "</span>";
197         } else {
198             return $text;
199         }
200     }
201
202     /** Clean up and split a mime-type up into its parts
203      *
204      * @param  string $mimeType   A MIME Type, optionally with parameters
205      * @return array  $type, $parameters
206      */
207     public static function parseMimeType($mimeType)
208     {
209         $parts = explode(';', strtolower($mimeType));
210         $type = trim(array_shift($parts));
211         $params = array();
212         foreach ($parts as $part) {
213             if (preg_match('/^\s*(\w+)\s*=\s*(.+?)\s*$/', $part, $matches)) {
214                 $params[$matches[1]] = $matches[2];
215             }
216         }
217         return array($type, $params);
218     }
219
220     /** Execute a command as a pipe
221      *
222      * The proc_open() function is used to open a pipe to a
223      * a command line process, writing $input to STDIN, returning STDOUT
224      * and throwing an exception if anything is written to STDERR or the
225      * process returns non-zero.
226      *
227      * @param  string $command   The command to execute
228      * @param  array  $args      Optional list of arguments to pass to the command
229      * @param  string $input     Optional buffer to send to the command
230      * @param  string $dir       Path to directory to run command in (defaults to /tmp)
231      * @return string The result of the command, printed to STDOUT
232      */
233     public static function execCommandPipe($command, $args = null, $input = null, $dir = null)
234     {
235         $descriptorspec = array(
236             0 => array('pipe', 'r'),
237             1 => array('pipe', 'w'),
238             2 => array('pipe', 'w')
239         );
240
241         // Use the system tmp directory by default
242         if (!$dir) {
243             $dir = sys_get_temp_dir();
244         }
245
246         if (is_array($args)) {
247             $fullCommand = implode(
248                 ' ',
249                 array_map('escapeshellcmd', array_merge(array($command), $args))
250             );
251         } else {
252             $fullCommand = escapeshellcmd($command);
253             if ($args) {
254                 $fullCommand .= ' '.escapeshellcmd($args);
255             }
256         }
257
258         $process = proc_open($fullCommand, $descriptorspec, $pipes, $dir);
259         if (is_resource($process)) {
260             // $pipes now looks like this:
261             // 0 => writeable handle connected to child stdin
262             // 1 => readable handle connected to child stdout
263             // 2 => readable handle connected to child stderr
264
265             if ($input) {
266                 fwrite($pipes[0], $input);
267             }
268             fclose($pipes[0]);
269
270             $output = stream_get_contents($pipes[1]);
271             fclose($pipes[1]);
272             $error = stream_get_contents($pipes[2]);
273             fclose($pipes[2]);
274
275             // It is important that you close any pipes before calling
276             // proc_close in order to avoid a deadlock
277             $returnValue = proc_close($process);
278             if ($returnValue) {
279                 throw new EasyRdf_Exception(
280                     "Error while executing command $command: ".$error
281                 );
282             }
283         } else {
284             throw new EasyRdf_Exception(
285                 "Failed to execute command $command"
286             );
287         }
288
289         return $output;
290     }
291 }