Created
October 14, 2018 11:47
-
-
Save serjoscha87/def5510ebaffb8e3b7ad703e4fac0182 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CockpitHelper { | |
public static $_COCKPIT_RESTAPI_TOKEN = null; | |
public static $_COCKPIT_BACKEND_URL = null; | |
public static $_COCKPIT_ADMIN_RESTAPI_TOKEN = null; | |
public static $_ASC = 1; | |
public static $_DESC = -1; | |
/** | |
* | |
* @param String $collectionName | |
* @param Array $filter example : ['published' => 1, 'foo' => 'bar'] | |
* @param int $limit | |
* @param int|String $order possible values CockpitHelper::$_ASC/$_DESC | 1/-1 | "ASC"/"DESC" ("asc"/"desc") | |
* @return Array the results | |
*/ | |
public static function getCollectionEntries($collectionName='News', $filter=[], $limit = 0, $order_by = '_o', $order = null) { | |
if(strtolower(gettype($order))==='string') // allow passing "ASC" and "DESC" (or "asc"/"desc") | |
$order = ['asc' => self::$_ASC, 'desc' => self::$_DESC][strtolower($order)]; // CURRENTLY UNTESTED | |
if(!$order) | |
$order = self::$_ASC; // default when nothing is passed or if a unrecognized string is passed as order param | |
if(is_null($filter)) $filter = []; | |
$filter_processed = ''; | |
foreach($filter as $key => $val) $filter_processed .= "&filter[$key]=$val"; | |
$data = json_decode(file_get_contents(self::$_COCKPIT_BACKEND_URL . '/api/collections/get/'.$collectionName.'?token=' . self::$_COCKPIT_RESTAPI_TOKEN . '&sort[' . $order_by . ']=' . $order . $filter_processed . '&limit='.$limit), true)['entries']; | |
// rewrite links to pdfs or other assets that have been written to the content of an entry to match the correct URL (so for example if the user fills out a textarea with free text ans uses the asset browser to link an pdf -> this array walk will make a useable URL of the links within the user defined content) | |
$data = self::_fixRelativeUrls($data); // TODO/NOTE: THIS IS UNTESTED YET!! | |
return $limit===1 ? $data[0] : $data; | |
} | |
/** | |
* @param String $singletonName | |
* @return Array the results | |
*/ | |
public static function getSingleton($singletonName='SINGLETONNAME') { | |
$data = json_decode(file_get_contents(self::$_COCKPIT_BACKEND_URL . '/api/singletons/get/'.$singletonName.'?token=' . self::$_COCKPIT_RESTAPI_TOKEN), true); | |
$data = self::_fixRelativeUrls($data); // ... untested | |
return $data; | |
} | |
/* | |
* image path helper - this method returns a URL that can be used within an html image tag in order to load images in front end that have been uploaded into cockpit | |
* $use_proxy => if true this function prepend /IMG/ in front of the complete URI which will cause the cockpit helper image proxy route to kick in. | |
* (note that this image proxy route needs to be injected into the cockpit instance by doing >CockpitHelper::injectImageProxyRoute($app)< within | |
* the index.php in order to make it capture requests to /IMG/* ). | |
* With $use_proxy : false => this method just returns the complete path to the image according the backend url. | |
* | |
* See "function injectImageProxyRoute" within the "CockpitHelper" (this) class... | |
*/ | |
public static function getFullAssetPath($path, $use_proxy = false) { | |
return sprintf('%s%s/storage/uploads/%s', ($use_proxy ? '/IMG/' : '') , self::$_COCKPIT_BACKEND_URL, $path); | |
} | |
/* | |
* check validity of the given credentials | |
*/ | |
public static function checkAuth($user, $pass){ | |
$url = self::$_COCKPIT_BACKEND_URL . '/auth/check'; | |
$fields = [ | |
'auth' => [ | |
'user' => $user, | |
'password' => $pass, | |
] | |
]; | |
$data_string = json_encode($fields); | |
$ch = curl_init($url); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
'Content-Type: application/json', | |
'Content-Length: ' . strlen($data_string)) | |
); | |
return json_decode(curl_exec($ch), true); | |
} | |
/** | |
* insert OR update a collection entry | |
* @param string $collection the collection name | |
* @param Array $data the date fields that shall be set to the collection | |
* @param string|null $id ONLY IF A ENTRY SHALL BE UPDATED: the ID of the collection entry that shall be updated. Null if you want to create a new entry | |
* @param string|null $apiKey the apikey for this request or null if the helper apikey shall be used (of course therefor it must be configurated) | |
* @return Array the result | |
*/ | |
public static function saveEntry($collection, $data = [], $id = null, $apiKey=null) { | |
$url = self::$_COCKPIT_BACKEND_URL . '/api/collections/save/' . $collection . '?token=' . ( $apiKey ? $apiKey : self::$_COCKPIT_RESTAPI_TOKEN ); | |
if($id) $data['_id'] = $id; | |
$ch = curl_init($url); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ | |
'data' => $data | |
])); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); | |
return curl_exec($ch); | |
} | |
/* | |
* get a list of collection the user associated to the configured api key has access to | |
*/ | |
public static function getCollections($api_key=null) { | |
if(!$api_key) | |
$api_key = self::$_COCKPIT_RESTAPI_TOKEN; | |
return json_decode(file_get_contents(self::$_COCKPIT_BACKEND_URL . '/api/collections/listCollections?token=' . $api_key), true); | |
} | |
/* | |
* TODO ... just quickly copied this over here after used directly within a php file - untested | |
* | |
* Get user data determined by some filter option that can be passed (because for example collection entries don't contain the user, but only a ID; this method can | |
* be used to get the user info using the ID that comes along with collection entries) | |
* | |
* NOTE: this needs a admin token in order to get the information from cockpit (because this is internal data). Dont use this in JS because it would expose the admin api token | |
* | |
* param (filter): | |
* ['_id' => 123] | |
* oder | |
* ['_mby' => 456] | |
*/ | |
public static function getUserInfo(array $filter) { | |
return json_decode(file_get_contents(self::$_COCKPIT_BACKEND_URL . '/api/cockpit/listUsers?token=' . self::$_COCKPIT_ADMIN_RESTAPI_TOKEN), true); | |
} | |
/* | |
* rewrite links to pdfs or other assets that have been written to the content of an entry to match the correct URL (so for example if the user fills out a textarea with free text ans uses the asset browser to link an pdf -> this array walk will make a useable URL of the links within the user defined content) | |
*/ | |
public static function _fixRelativeUrls(array $data) { | |
array_walk_recursive($data, function(&$item) { | |
if (strpos($item, '/storage/uploads/') !== false) { | |
$item = str_replace('/storage/uploads/', CockpitHelper::$_COCKPIT_BACKEND_URL . '/storage/uploads/', $item); | |
} | |
}); | |
return $data; | |
} | |
/* | |
* Cockpit Image Proxy Method | |
* Purpose: | |
* use php to fetch / proxy / tunnel the image at the given URI behind /IMG/ and just output it. | |
* Reason: On this way we can bypass CORS / foreign origin&host errors. | |
* | |
* Implement this method within the file that binds routes to the lime instance. | |
* It can be done like this: | |
* > | |
* CockpitHelper::injectImageProxyRoute($app); // where $app is the concrete lime instance | |
* < | |
* This will make the image proxy available though requests to /IMG/ | |
* | |
* TODO add more image types (like for example PNGs) | |
*/ | |
public static function injectImageProxyRouteTo(Lime $lime) { | |
$lime->bind('/IMG/*', function($param) { | |
$img_file = $param[':splat'][0]; | |
if(substr($img_file, 0, strlen(CockpitHelper::$_COCKPIT_BACKEND_URL)) !== CockpitHelper::$_COCKPIT_BACKEND_URL) die(); // make sure only images from the defined cockpit installation will be processed | |
$this->response->mime = 'jpg'; | |
$url = isset($img_file) ? $img_file : null; | |
if (!$url) die(); | |
$imgInfo = getimagesize($url); | |
if (stripos($imgInfo['mime'], 'image/jpeg') === false) die(); | |
return readfile($url); | |
}); | |
} | |
/** | |
* Allows to get cockpit data as json using the routes defined here | |
* TODO secure this | |
* @param Lime lime instance | |
*/ | |
public static function injectApiRouteTo(LimeStorms $lime) { | |
// get collection entries | |
$lime->bind('/cockpit/collections/get/:collectionName', function($param) { | |
$this->response->mime = 'json'; | |
return CockpitHelper::getCollectionEntries($param['collectionName']); | |
}); | |
// get singleton data | |
$lime->bind('/cockpit/singletons/get/:singletonName', function($param) { | |
$this->response->mime = 'json'; | |
return CockpitHelper::getSingleton($param['singletonName']); | |
}); | |
// ... more to come | |
} | |
/* | |
* Make cockpit generate a thumbnail and return its URL | |
* TODO params missing; add them: https://getcockpit.com/documentation/api/cockpit | |
* not that this cockpit request will take some time for cockpit will do all the thumbnail stuff. When creating a gallery using this the page may load round about 8-10 seconds when having ~ 20 pictures | |
*/ | |
public static function getThumbnail($assetId_Or_imagePath, $w=null, $h=null) { | |
return file_get_contents(CockpitHelper::$_COCKPIT_BACKEND_URL . '/api/cockpit/image?'. http_build_query([ | |
'src' => $assetId_Or_imagePath, | |
'w' => $w, | |
'h' => $h, | |
// ---- | |
'token' => self::$_COCKPIT_RESTAPI_TOKEN | |
])); | |
} | |
/* | |
* make the cockpit images result being reduced to a very flat array without many other information | |
* this array can directly be used for example to iterate for slider images.. | |
*/ | |
public static function flattenImgsStructure(array $imgs) { | |
array_walk($imgs, function(&$val) { | |
$val = str_replace(CockpitHelper::$_COCKPIT_BACKEND_URL, '', $val['path']); | |
}); | |
return $imgs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment