Merge pull request #13974 from eileenmcnaughton/array_format7
[civicrm-core.git] / CRM / Admin / Page / APIExplorer.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * Api Explorer
36 */
37 class CRM_Admin_Page_APIExplorer extends CRM_Core_Page {
38
39 /**
40 * Return unique paths for checking for examples.
41 * @return array
42 */
43 private static function uniquePaths() {
44 // Ensure that paths with trailing slashes are properly dealt with
45 $paths = explode(PATH_SEPARATOR, get_include_path());
46 foreach ($paths as $id => $rawPath) {
47 $pathParts = explode(DIRECTORY_SEPARATOR, $rawPath);
48 foreach ($pathParts as $partId => $part) {
49 if (empty($part)) {
50 unset($pathParts[$partId]);
51 }
52 }
53 $newRawPath = implode(DIRECTORY_SEPARATOR, $pathParts);
54 if ($newRawPath != $rawPath) {
55 $paths[$id] = DIRECTORY_SEPARATOR . $newRawPath;
56 }
57 }
58 $paths = array_unique($paths);
59 return $paths;
60 }
61
62
63 /**
64 * Run page.
65 *
66 * @return string
67 */
68 public function run() {
69 CRM_Core_Resources::singleton()
70 ->addScriptFile('civicrm', 'templates/CRM/Admin/Page/APIExplorer.js')
71 ->addScriptFile('civicrm', 'bower_components/google-code-prettify/bin/prettify.min.js', 99)
72 ->addStyleFile('civicrm', 'bower_components/google-code-prettify/bin/prettify.min.css', 99)
73 ->addVars('explorer', ['max_joins' => \Civi\API\Api3SelectQuery::MAX_JOINS]);
74
75 $this->assign('operators', CRM_Core_DAO::acceptedSQLOperators());
76
77 // List example directories
78 // use get_include_path to ensure that extensions are captured.
79 $examples = [];
80 $paths = self::uniquePaths();
81 foreach ($paths as $path) {
82 $dir = \CRM_Utils_File::addTrailingSlash($path) . 'api' . DIRECTORY_SEPARATOR . 'v3' . DIRECTORY_SEPARATOR . 'examples';
83 if (is_dir($dir)) {
84 foreach (scandir($dir) as $item) {
85 if ($item && strpos($item, '.') === FALSE && array_search($item, $examples) === FALSE) {
86 $examples[] = $item;
87 }
88 }
89 }
90 }
91 sort($examples);
92 $this->assign('examples', $examples);
93
94 return parent::run();
95 }
96
97 /**
98 * Get user context.
99 *
100 * @return string
101 * user context.
102 */
103 public function userContext() {
104 return 'civicrm/api';
105 }
106
107 /**
108 * AJAX callback to fetch examples.
109 */
110 public static function getExampleFile() {
111 if (!empty($_GET['entity']) && strpos($_GET['entity'], '.') === FALSE) {
112 $examples = [];
113 $paths = self::uniquePaths();
114 foreach ($paths as $path) {
115 $dir = \CRM_Utils_File::addTrailingSlash($path) . 'api' . DIRECTORY_SEPARATOR . 'v3' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . $_GET['entity'];
116 if (is_dir($dir)) {
117 foreach (scandir($dir) as $item) {
118 $item = str_replace('.php', '', $item);
119 if ($item && strpos($item, '.') === FALSE) {
120 $examples[] = ['key' => $item, 'value' => $item];
121 }
122 }
123 }
124 }
125 CRM_Utils_JSON::output($examples);
126 }
127 if (!empty($_GET['file']) && strpos($_GET['file'], '.') === FALSE) {
128 $paths = self::uniquePaths();
129 $fileFound = FALSE;
130 foreach ($paths as $path) {
131 $fileName = \CRM_Utils_File::addTrailingSlash($path) . 'api' . DIRECTORY_SEPARATOR . 'v3' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . $_GET['file'] . '.php';
132 if (!$fileFound && file_exists($fileName)) {
133 $fileFound = TRUE;
134 echo file_get_contents($fileName);
135 }
136 }
137 if (!$fileFound) {
138 echo "Not found.";
139 }
140 CRM_Utils_System::civiExit();
141 }
142 CRM_Utils_System::permissionDenied();
143 }
144
145 /**
146 * Ajax callback to display code docs.
147 */
148 public static function getDoc() {
149 // Verify the API handler we're talking to is valid.
150 $entities = civicrm_api3('Entity', 'get');
151 $entity = CRM_Utils_Array::value('entity', $_GET);
152 if (!empty($entity) && in_array($entity, $entities['values']) && strpos($entity, '.') === FALSE) {
153 $action = CRM_Utils_Array::value('action', $_GET);
154 $doc = self::getDocblock($entity, $action);
155 $result = [
156 'doc' => $doc ? self::formatDocBlock($doc[0]) : 'Not found.',
157 'code' => $doc ? $doc[1] : NULL,
158 'file' => $doc ? $doc[2] : NULL,
159 ];
160 if (!$action) {
161 $actions = civicrm_api3($entity, 'getactions');
162 $result['actions'] = CRM_Utils_Array::makeNonAssociative(array_combine($actions['values'], $actions['values']));
163 }
164 CRM_Utils_JSON::output($result);
165 }
166 CRM_Utils_System::permissionDenied();
167 }
168
169 /**
170 * Get documentation block.
171 *
172 * @param string $entity
173 * @param string|null $action
174 * @return array|bool
175 * [docblock, code]
176 */
177 private static function getDocBlock($entity, $action) {
178 if (!$entity) {
179 return FALSE;
180 }
181 $file = "api/v3/$entity.php";
182 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
183 if (!$contents) {
184 // Api does not exist
185 return FALSE;
186 }
187 $docblock = $code = [];
188 // Fetch docblock for the api file
189 if (!$action) {
190 if (preg_match('#/\*\*\n.*?\n \*/\n#s', $contents, $docblock)) {
191 return [$docblock[0], NULL, $file];
192 }
193 }
194 // Fetch block for a specific action
195 else {
196 $action = strtolower($action);
197 $fnName = 'civicrm_api3_' . _civicrm_api_get_entity_name_from_camel($entity) . '_' . $action;
198 // Support the alternate "1 file per action" structure
199 $actionFile = "api/v3/$entity/" . ucfirst($action) . '.php';
200 $actionFileContents = file_get_contents("api/v3/$entity/" . ucfirst($action) . '.php', FILE_USE_INCLUDE_PATH);
201 if ($actionFileContents) {
202 $file = $actionFile;
203 $contents = $actionFileContents;
204 }
205 // If action isn't in this file, try generic
206 if (strpos($contents, "function $fnName") === FALSE) {
207 $fnName = "civicrm_api3_generic_$action";
208 $file = "api/v3/Generic/" . ucfirst($action) . '.php';
209 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
210 if (!$contents) {
211 $file = "api/v3/Generic.php";
212 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
213 }
214 }
215 if (preg_match('#(/\*\*(\n \*.*)*\n \*/\n)function[ ]+' . $fnName . '#i', $contents, $docblock)) {
216 // Fetch the code in a separate regex to preserve sanity
217 preg_match("#^function[ ]+$fnName.*?^}#ism", $contents, $code);
218 return [$docblock[1], $code[0], $file];
219 }
220 }
221 }
222
223 /**
224 * Format a docblock to be a bit more readable
225 * Not a proper doc parser... patches welcome :)
226 *
227 * @param string $text
228 * @return string
229 */
230 public static function formatDocBlock($text) {
231 // Normalize #leading spaces.
232 $lines = explode("\n", $text);
233 $lines = preg_replace('/^ +\*/', ' *', $lines);
234 $text = implode("\n", $lines);
235
236 // Get rid of comment stars
237 $text = str_replace(["\n * ", "\n *\n", "\n */\n", "/**\n"], ["\n", "\n\n", '', ''], $text);
238
239 // Format for html
240 $text = htmlspecialchars($text);
241
242 // Extract code blocks - save for later to skip html conversion
243 $code = [];
244 preg_match_all('#@code(.*?)@endcode#is', $text, $code);
245 $text = preg_replace('#@code.*?@endcode#is', '<pre></pre>', $text);
246
247 // Convert @annotations to titles
248 $text = preg_replace_callback(
249 '#^[ ]*@(\w+)([ ]*)#m',
250 function($matches) {
251 return "<strong>" . ucfirst($matches[1]) . "</strong>" . (empty($matches[2]) ? '' : ': ');
252 },
253 $text);
254
255 // Preserve indentation
256 $text = str_replace("\n ", "\n&nbsp;&nbsp;&nbsp;&nbsp;", $text);
257
258 // Convert newlines
259 $text = nl2br($text);
260
261 // Add unformatted code blocks back in
262 if ($code && !empty($code[1])) {
263 foreach ($code[1] as $block) {
264 $text = preg_replace('#<pre></pre>#', "<pre>$block</pre>", $text, 1);
265 }
266 }
267 return $text;
268 }
269
270 }