3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 class CRM_Admin_Page_APIExplorer
extends CRM_Core_Page
{
24 * Return unique paths for checking for examples.
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) {
34 unset($pathParts[$partId]);
37 $newRawPath = implode(DIRECTORY_SEPARATOR
, $pathParts);
38 if ($newRawPath != $rawPath) {
39 $paths[$id] = DIRECTORY_SEPARATOR
. $newRawPath;
42 $paths = array_unique($paths);
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
]);
58 $this->assign('operators', CRM_Core_DAO
::acceptedSQLOperators());
60 // List example directories
61 // use get_include_path to ensure that extensions are captured.
63 $paths = self
::uniquePaths();
64 foreach ($paths as $path) {
65 $dir = \CRM_Utils_File
::addTrailingSlash($path) . 'api' . DIRECTORY_SEPARATOR
. 'v3' . DIRECTORY_SEPARATOR
. 'examples';
67 foreach (scandir($dir) as $item) {
68 if ($item && strpos($item, '.') === FALSE && array_search($item, $examples) === FALSE) {
75 $this->assign('examples', $examples);
86 public function userContext() {
91 * AJAX callback to fetch examples.
93 public static function getExampleFile() {
94 if (!empty($_GET['entity']) && strpos($_GET['entity'], '.') === FALSE) {
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'];
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];
108 CRM_Utils_JSON
::output($examples);
110 if (!empty($_GET['file']) && strpos($_GET['file'], '.') === FALSE) {
111 $paths = self
::uniquePaths();
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)) {
117 echo file_get_contents($fileName);
123 CRM_Utils_System
::civiExit();
125 CRM_Utils_System
::permissionDenied();
129 * Ajax callback to display code docs.
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);
139 'doc' => $doc ? self
::formatDocBlock($doc[0]) : 'Not found.',
140 'code' => $doc ?
$doc[1] : NULL,
141 'file' => $doc ?
$doc[2] : NULL,
144 $actions = civicrm_api3($entity, 'getactions');
145 $result['actions'] = CRM_Utils_Array
::makeNonAssociative(array_combine($actions['values'], $actions['values']));
147 CRM_Utils_JSON
::output($result);
149 CRM_Utils_System
::permissionDenied();
153 * Get documentation block.
155 * @param string $entity
156 * @param string|null $action
160 private static function getDocBlock($entity, $action) {
164 $file = "api/v3/$entity.php";
165 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH
);
167 // Api does not exist
170 $docblock = $code = [];
171 // Fetch docblock for the api file
173 if (preg_match('#/\*\*\n.*?\n \*/\n#s', $contents, $docblock)) {
174 return [$docblock[0], NULL, $file];
177 // Fetch block for a specific action
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) {
186 $contents = $actionFileContents;
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
);
194 $file = "api/v3/Generic.php";
195 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH
);
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];
207 * Format a docblock to be a bit more readable
209 * FIXME: APIv4 uses markdown in code docs. Switch to that.
211 * @param string $text
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);
220 // Get rid of comment stars
221 $text = str_replace(["\n * ", "\n *\n", "\n */\n", "/**\n"], ["\n", "\n\n", '', ''], $text);
224 $text = htmlspecialchars($text);
226 // Extract code blocks - save for later to skip html conversion
228 preg_match_all('#(@code|```)(.*?)(@endcode|```)#is', $text, $code);
229 $text = preg_replace('#(@code|```)(.*?)(@endcode|```)#is', '<pre></pre>', $text);
231 // Convert @annotations to titles
232 $text = preg_replace_callback(
233 '#^[ ]*@(\w+)([ ]*)#m',
235 return "<strong>" . ucfirst($matches[1]) . "</strong>" . (empty($matches[2]) ?
'' : ': ');
239 // Preserve indentation
240 $text = str_replace("\n ", "\n ", $text);
243 $text = nl2br($text);
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);