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