Merge pull request #13885 from eileenmcnaughton/pp
[civicrm-core.git] / CRM / Admin / Page / APIExplorer.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
0c3a6e64 35 * Api Explorer
6a488035
TO
36 */
37class CRM_Admin_Page_APIExplorer extends CRM_Core_Page {
38
7d16f66d
SL
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
e0ef6999 63 /**
ce064e4f 64 * Run page.
65 *
e0ef6999
EM
66 * @return string
67 */
00be9182 68 public function run() {
2b6e1174
CW
69 CRM_Core_Resources::singleton()
70 ->addScriptFile('civicrm', 'templates/CRM/Admin/Page/APIExplorer.js')
37d79aed 71 ->addScriptFile('civicrm', 'bower_components/google-code-prettify/bin/prettify.min.js', 99)
5b46e216 72 ->addStyleFile('civicrm', 'bower_components/google-code-prettify/bin/prettify.min.css', 99)
8bcc0d86 73 ->addVars('explorer', array('max_joins' => \Civi\API\Api3SelectQuery::MAX_JOINS));
89ee60d5 74
e4176358 75 $this->assign('operators', CRM_Core_DAO::acceptedSQLOperators());
89ee60d5
CW
76
77 // List example directories
7d16f66d 78 // use get_include_path to ensure that extensions are captured.
89ee60d5 79 $examples = array();
7d16f66d
SL
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 }
89ee60d5
CW
89 }
90 }
7d16f66d 91 sort($examples);
89ee60d5
CW
92 $this->assign('examples', $examples);
93
6a488035
TO
94 return parent::run();
95 }
96
6a488035
TO
97 /**
98 * Get user context.
99 *
a6c01b45
CW
100 * @return string
101 * user context.
6a488035 102 */
00be9182 103 public function userContext() {
d5a9020d 104 return 'civicrm/api';
6a488035 105 }
96025800 106
89ee60d5 107 /**
ce064e4f 108 * AJAX callback to fetch examples.
89ee60d5
CW
109 */
110 public static function getExampleFile() {
89ee60d5
CW
111 if (!empty($_GET['entity']) && strpos($_GET['entity'], '.') === FALSE) {
112 $examples = array();
7d16f66d
SL
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[] = array('key' => $item, 'value' => $item);
121 }
122 }
89ee60d5
CW
123 }
124 }
125 CRM_Utils_JSON::output($examples);
126 }
127 if (!empty($_GET['file']) && strpos($_GET['file'], '.') === FALSE) {
7d16f66d
SL
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 }
89ee60d5 136 }
7d16f66d 137 if (!$fileFound) {
89ee60d5
CW
138 echo "Not found.";
139 }
140 CRM_Utils_System::civiExit();
141 }
bc4aa590
CW
142 CRM_Utils_System::permissionDenied();
143 }
144
145 /**
ce064e4f 146 * Ajax callback to display code docs.
bc4aa590
CW
147 */
148 public static function getDoc() {
e80f05b2
CB
149 // Verify the API handler we're talking to is valid.
150 $entities = civicrm_api3('Entity', 'get');
6469e038
CW
151 $entity = CRM_Utils_Array::value('entity', $_GET);
152 if (!empty($entity) && in_array($entity, $entities['values']) && strpos($entity, '.') === FALSE) {
bc4aa590
CW
153 $action = CRM_Utils_Array::value('action', $_GET);
154 $doc = self::getDocblock($entity, $action);
155 $result = array(
156 'doc' => $doc ? self::formatDocBlock($doc[0]) : 'Not found.',
157 'code' => $doc ? $doc[1] : NULL,
cf3a4f07 158 'file' => $doc ? $doc[2] : NULL,
bc4aa590
CW
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 /**
ce064e4f 170 * Get documentation block.
171 *
bc4aa590
CW
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 }
cf3a4f07
CW
181 $file = "api/v3/$entity.php";
182 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
bc4aa590
CW
183 if (!$contents) {
184 // Api does not exist
185 return FALSE;
186 }
187 $docblock = $code = array();
188 // Fetch docblock for the api file
189 if (!$action) {
190 if (preg_match('#/\*\*\n.*?\n \*/\n#s', $contents, $docblock)) {
cf3a4f07 191 return array($docblock[0], NULL, $file);
bc4aa590
CW
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
cf3a4f07
CW
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;
bc4aa590
CW
204 }
205 // If action isn't in this file, try generic
41bd5fcb 206 if (strpos($contents, "function $fnName") === FALSE) {
bc4aa590 207 $fnName = "civicrm_api3_generic_$action";
cf3a4f07
CW
208 $file = "api/v3/Generic/" . ucfirst($action) . '.php';
209 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
bc4aa590 210 if (!$contents) {
cf3a4f07
CW
211 $file = "api/v3/Generic.php";
212 $contents = file_get_contents($file, FILE_USE_INCLUDE_PATH);
bc4aa590
CW
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);
cf3a4f07 218 return array($docblock[1], $code[0], $file);
bc4aa590
CW
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 */
eecd39e1
TO
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
bc4aa590
CW
236 // Get rid of comment stars
237 $text = str_replace(array("\n * ", "\n *\n", "\n */\n", "/**\n"), array("\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 = array();
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) {
fea52a54 264 $text = preg_replace('#<pre></pre>#', "<pre>$block</pre>", $text, 1);
bc4aa590
CW
265 }
266 }
267 return $text;
89ee60d5
CW
268 }
269
6a488035 270}