first commit

This commit is contained in:
Ryan Ariana
2024-05-06 11:04:37 +07:00
commit aee061ddba
7322 changed files with 2918816 additions and 0 deletions

View File

@@ -0,0 +1,219 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteBaseAdminClassUC{
protected static $master_view;
protected static $view;
private static $arrSettings = array();
private static $tempVars = array();
/**
*
* main constructor
*/
public function __construct(){
$this->initView();
}
/**
*
* get path to settings file
* @param $settingsFile
*/
protected static function getSettingsFilePath($settingsFile){
$filepath = self::$path_plugin."settings/$settingsFile.php";
return($filepath);
}
/**
*
* set the view from GET variables
*/
private function initView(){
$defaultView = GlobalsUC::$view_default;
//set view
$viewInput = UniteFunctionsUC::getGetVar("view","",UniteFunctionsUC::SANITIZE_KEY);
$page = UniteFunctionsUC::getGetVar("page","",UniteFunctionsUC::SANITIZE_KEY);
//get the view out of the page
if(!empty($viewInput)){
self::$view = $viewInput;
return(false);
}
//check bottom devider
$deviderPos = strpos($page,"_");
if($deviderPos !== false){
self::$view = substr($page, $deviderPos+1);
return(false);
}
//check middle devider
$deviderPos = strpos($page, "-");
if($deviderPos !== false){
self::$view = substr($page, $deviderPos+1);
return(false);
}
self::$view = $defaultView;
}
/**
*
* set view that will be the master
*/
protected static function setMasterView($masterView){
self::$master_view = $masterView;
}
/**
* scan all plugin paths, maybe find the view there
*/
private static function getPluginViewFilePath($viewFilepath, $view){
if(empty($view))
return($viewFilepath);
$arrViewPaths = GlobalsUC::$arrAdminViewPaths;
if(empty($arrViewPaths))
return($viewFilepath);
foreach($arrViewPaths as $path){
$filepath = $path.$view.".php";
if(file_exists($filepath) == true)
return($filepath);
}
return($viewFilepath);
}
/**
*
* inlcude some view file
*/
protected static function requireView($view){
try{
//require master view file, and
if(!empty(self::$master_view) && !isset(self::$tempVars["is_masterView"]) ){
$masterViewFilepath = GlobalsUC::$pathViews.self::$master_view.".php";
UniteFunctionsUC::validateFilepath($masterViewFilepath,"Master View");
self::$tempVars["is_masterView"] = true;
require $masterViewFilepath;
}
else{ //simple require the view file.
$viewFilepath = GlobalsUC::$pathViews.$view.".php";
$pathViewProvider = GlobalsUC::$pathProviderViews.$view.".php";
//replace thef ile by provider view file if needed
if(file_exists($viewFilepath) == false && file_exists($pathViewProvider) == true)
$viewFilepath = $pathViewProvider;
/**
* check admin view array
*/
if(file_exists($viewFilepath) == false)
$viewFilepath = self::getPluginViewFilePath($viewFilepath, $view);
$viewFilepath = UniteProviderFunctionsUC::applyFilters(UniteCreatorFilters::FILTER_ADMIN_VIEW_FILEPATH, $viewFilepath, $view);
UniteFunctionsUC::validateFilepath($viewFilepath,"View");
require $viewFilepath;
}
}catch (Exception $e){
$view = esc_html($view);
$message = $e->getMessage();
$message = esc_html($message);
echo "<div id='uc_view_error_message'> <br><br>View ($view) Error: <b>".$message."</b>";
if(GlobalsUC::$SHOW_TRACE == true)
dmp($e->getTraceAsString());
echo "</div>";
?>
<script>
jQuery(document).ready(function(){
var htmlError = jQuery("#uc_view_error_message").html();
jQuery("#viewWrapper").append("Duplicating Error Here: <br> <div style='padding-left:20px;padding-right:20px;'>"+htmlError+"</div><br><br>");
});
</script>
<?php
}
}
/**
*
* require settings file, the filename without .php
*/
protected static function requireSettings($settingsFile){
try{
require self::$path_plugin."settings/$settingsFile.php";
}catch (Exception $e){
echo "<br><br>Settings ($settingsFile) Error: <b>".$e->getMessage()."</b>";
dmp($e->getTraceAsString());
}
}
/**
* get view
*/
public static function getView(){
return self::$view;
}
/**
* set view manually
*/
public static function setView($view){
self::$view = $view;
}
}
?>

View File

@@ -0,0 +1,236 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteOutputBaseUC{
protected $arrParams;
protected $arrOriginalParams; //params as they came originally from the database
protected $skipJsOptions = array();
const TYPE_NUMBER = "number";
const TYPE_BOOLEAN = "boolean";
const TYPE_OBJECT = "object";
const TYPE_SIZE = "size";
const VALIDATE_EXISTS = "validate";
const VALIDATE_NUMERIC = "numeric";
const VALIDATE_SIZE = "size";
const FORCE_NUMERIC = "force_numeric";
const FORCE_BOOLEAN = "force_boolean";
const FORCE_SIZE = "force_size";
/**
* add js option to skip
*/
protected function addSkipJsOption($name){
$this->skipJsOptions[$name] = true;
}
/**
* check if some param exists in params array
*/
protected function isParamExists($name){
$exists = array_key_exists($name, $this->arrParams);
return $exists;
}
/**
*
* get some param
*/
protected function getParam($name, $validateMode = null){
if(is_array($this->arrParams) == false)
$this->arrParams = array();
if(array_key_exists($name, $this->arrParams)){
$arrParams = $this->arrParams;
$value = $this->arrParams[$name];
}
else{
if(is_array($this->arrOriginalParams) == false)
$this->arrOriginalParams = array();
$arrParams = $this->arrOriginalParams;
$value = UniteFunctionsUC::getVal($this->arrOriginalParams, $name);
}
switch ($validateMode) {
case self::VALIDATE_EXISTS:
if (array_key_exists($name, $arrParams) == false)
UniteFunctionsUC::throwError("The param: {$name} don't exists");
break;
case self::VALIDATE_NUMERIC:
if (is_numeric($value) == false)
UniteFunctionsUC::throwError("The param: {$name} is not numeric");
break;
case self::VALIDATE_SIZE:
if(strpos($value, "%") === false && is_numeric($value) == false)
UniteFunctionsUC::throwError("The param: {$name} is not size");
break;
case self::FORCE_SIZE:
$isPercent = (strpos($value, "%") !== false);
if($isPercent == false && is_numeric($value) == false)
UniteFunctionsUC::throwError("The param: {$name} is not size");
if($isPercent == false)
$value .= "px";
break;
case self::FORCE_NUMERIC:
$value = floatval($value);
$value = (double) $value;
break;
case self::FORCE_BOOLEAN:
$value = UniteFunctionsUC::strToBool($value);
break;
}
return($value);
}
/**
* rename option (if exists)
*/
protected function renameOption($keySource, $keyDest){
if(array_key_exists($keySource, $this->arrParams)){
$this->arrParams[$keyDest] = $this->arrParams[$keySource];
unset($this->arrParams[$keySource]);
}
}
/**
* build javascript param
*/
protected function buildJsParam($paramName, $validate = null, $type = null){
$output = array("name"=>$paramName, "validate"=>$validate, "type"=>$type);
return($output);
}
/**
* build and get js settings
*/
protected function buildJsParams(){
$arrJsParams = $this->getArrJsOptions();
$jsOutput = "";
$counter = 0;
$tabs = " ";
foreach($arrJsParams as $arrParam){
$name = $arrParam["name"];
$validate = $arrParam["validate"];
$type = $arrParam["type"];
if(array_key_exists($name, $this->skipJsOptions) == true)
continue;
if($this->isParamExists($name)){
$value = $this->getParam($name, $validate);
$putInBrackets = false;
switch($type){
case self::TYPE_NUMBER:
case self::TYPE_BOOLEAN:
case self::TYPE_OBJECT:
break;
case self::TYPE_SIZE:
if(strpos($value, "%") !== 0)
$putInBrackets = true;
break;
default: //string
$putInBrackets = true;
break;
}
if($putInBrackets == true){
$value = str_replace('"','\\"', $value);
$value = '"'.$value.'"';
}
if($counter > 0)
$jsOutput .= ",\n".$tabs;
$jsOutput .= "{$name}:{$value}";
$counter++;
}
}
$jsOutput .= "\n";
return($jsOutput);
}
/**
* get string from position options
*/
protected function getPositionString(){
$position = $this->getParam("position");
$wrapperStyle = "";
switch($position){
case "default":
break;
case "center":
default:
$wrapperStyle .= "margin:0px auto;";
break;
case "left":
$wrapperStyle .= "float:left;";
break;
case "right":
$wrapperStyle .= "float:right;";
break;
}
//add left / right margin
if($position != "center"){
$marginLeft = $this->getParam("margin_left", self::FORCE_NUMERIC);
$marginRight = $this->getParam("margin_right", self::FORCE_NUMERIC);
if($marginLeft != 0)
$wrapperStyle .= "margin-left:{$marginLeft}px;";
if($marginRight != 0)
$wrapperStyle .= "margin-right:{$marginRight}px;";
}
//add top / bottom margin
$marginTop = $this->getParam("margin_top", self::FORCE_NUMERIC);
$marginBottom = $this->getParam("margin_bottom", self::FORCE_NUMERIC);
if($marginTop != 0)
$wrapperStyle .= "margin-top:{$marginTop}px;";
if($marginBottom != 0)
$wrapperStyle .= "margin-bottom:{$marginBottom}px;";
return($wrapperStyle);
}
}
?>

View File

@@ -0,0 +1,267 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteCssParserUC{
private $cssContent;
public function __construct(){
}
/**
*
* init the parser, set css content
*/
public function initContent($cssContent){
$this->cssContent = $cssContent;
}
/**
*
* get array of slide classes, between two sections.
*/
public function getArrClasses($startText = "",$endText=""){
$content = $this->cssContent;
//trim from top
if(!empty($startText)){
$posStart = strpos($content, $startText);
if($posStart !== false)
$content = substr($content, $posStart,strlen($content)-$posStart);
}
//trim from bottom
if(!empty($endText)){
$posEnd = strpos($content, $endText);
if($posEnd !== false)
$content = substr($content,0,$posEnd);
}
//get styles
$lines = explode("\n",$content);
$arrClasses = array();
foreach($lines as $key=>$line){
$line = trim($line);
if(strpos($line, "{") === false)
continue;
//skip unnessasary links
if(strpos($line, ".caption a") !== false)
continue;
if(strpos($line, ".tp-caption a") !== false)
continue;
//get style out of the line
$class = str_replace("{", "", $line);
$class = trim($class);
//skip captions like this: .tp-caption.imageclass img
if(strpos($class," ") !== false)
continue;
//skip captions like this: .tp-caption.imageclass:hover, :before, :after
if(strpos($class,":") !== false)
continue;
$class = str_replace(".caption.", ".", $class);
$class = str_replace(".tp-caption.", ".", $class);
$class = str_replace(".", "", $class);
$class = trim($class);
$arrWords = explode(" ", $class);
$class = $arrWords[count($arrWords)-1];
$class = trim($class);
$arrClasses[] = $class;
}
sort($arrClasses);
return($arrClasses);
}
public static function parseCssToArray($css){
while(strpos($css, '/*') !== false){
if(strpos($css, '*/') === false) return false;
$start = strpos($css, '/*');
$end = strpos($css, '*/') + 2;
$css = str_replace(substr($css, $start, $end - $start), '', $css);
}
preg_match_all( '/(?ims)([a-z0-9\s\.\:#_\-@]+)\{([^\}]*)\}/', $css, $arr);
$result = array();
foreach ($arr[0] as $i => $x){
$selector = trim($arr[1][$i]);
if(strpos($selector, '{') !== false || strpos($selector, '}') !== false) return false;
$rules = explode(';', trim($arr[2][$i]));
$result[$selector] = array();
foreach ($rules as $strRule){
if (!empty($strRule)){
$rule = explode(":", $strRule);
if(strpos($rule[0], '{') !== false || strpos($rule[0], '}') !== false || strpos($rule[1], '{') !== false || strpos($rule[1], '}') !== false) return false;
//put back everything but not $rule[0];
$key = trim($rule[0]);
unset($rule[0]);
$values = implode(':', $rule);
$result[$selector][trim($key)] = trim(str_replace("'", '"', $values));
}
}
}
return($result);
}
public static function parseDbArrayToCss($cssArray, $nl = "\n\r"){
$css = '';
foreach($cssArray as $id => $attr){
$params = $attr['params'];
$styles = json_decode($params);
if(empty($styles))
$styles = json_decode($params);
if(!empty($styles))
$styles = (array)$styles;
$css.= $attr['handle']." {".$nl;
if(is_array($styles)){
foreach($styles as $name => $style){
$css.= $name.':'.$style.";".$nl;
}
}
$css.= "}".$nl.$nl;
//add hover
$setting = json_decode($attr['settings'], true);
if(@$setting['hover'] == 'true'){
$hover = json_decode($attr['hover'], true);
if(is_array($hover)){
$css.= $attr['handle'].":hover {".$nl;
foreach($hover as $name => $style){
$css.= $name.':'.$style.";".$nl;
}
$css.= "}".$nl.$nl;
}
}
}
return $css;
}
public static function parseArrayToCss($cssArray, $nl = "\n\r"){
$css = '';
foreach($cssArray as $id => $attr){
$styles = (array)$attr['params'];
$css.= $attr['handle']." {".$nl;
if(is_array($styles) && !empty($styles)){
foreach($styles as $name => $style){
if($name == 'background-color' && strpos($style, 'rgba') !== false){ //rgb && rgba
$rgb = explode(',', str_replace('rgba', 'rgb', $style));
unset($rgb[count($rgb)-1]);
$rgb = implode(',', $rgb).')';
$css.= $name.':'.$rgb.";".$nl;
}
$css.= $name.':'.$style.";".$nl;
}
}
$css.= "}".$nl.$nl;
//add hover
$setting = (array)$attr['settings'];
if(@$setting['hover'] == 'true'){
$hover = (array)$attr['hover'];
if(is_array($hover)){
$css.= $attr['handle'].":hover {".$nl;
foreach($hover as $name => $style){
if($name == 'background-color' && strpos($style, 'rgba') !== false){ //rgb && rgba
$rgb = explode(',', str_replace('rgba', 'rgb', $style));
unset($rgb[count($rgb)-1]);
$rgb = implode(',', $rgb).')';
$css.= $name.':'.$rgb.";".$nl;
}
$css.= $name.':'.$style.";".$nl;
}
$css.= "}".$nl.$nl;
}
}
}
return $css;
}
public static function parseStaticArrayToCss($cssArray, $nl = "\n"){
$css = '';
foreach($cssArray as $class => $styles){
$css.= $class." {".$nl;
if(is_array($styles) && !empty($styles)){
foreach($styles as $name => $style){
$css.= $name.':'.$style.";".$nl;
}
}
$css.= "}".$nl.$nl;
}
return $css;
}
public static function parseDbArrayToArray($cssArray, $handle = false){
if(!is_array($cssArray) || empty($cssArray)) return false;
foreach($cssArray as $key => $css){
if($handle != false){
if($cssArray[$key]['handle'] == '.tp-caption.'.$handle){
$cssArray[$key]['params'] = json_decode($css['params']);
$cssArray[$key]['hover'] = json_decode($css['hover']);
$cssArray[$key]['settings'] = json_decode($css['settings']);
return $cssArray[$key];
}else{
unset($cssArray[$key]);
}
}else{
$cssArray[$key]['params'] = json_decode($css['params']);
$cssArray[$key]['hover'] = json_decode($css['hover']);
$cssArray[$key]['settings'] = json_decode($css['settings']);
}
}
return $cssArray;
}
public static function compress_css($buffer){
/* remove comments */
$buffer = preg_replace("!/\*[^*]*\*+([^/][^*]*\*+)*/!", "", $buffer) ;
/* remove tabs, spaces, newlines, etc. */
$arr = array("\r\n", "\r", "\n", "\t", " ", " ", " ");
$rep = array("", "", "", "", " ", " ", " ");
$buffer = str_replace($arr, $rep, $buffer);
/* remove whitespaces around {}:, */
$buffer = preg_replace("/\s*([\{\}:,])\s*/", "$1", $buffer);
/* remove last ; */
$buffer = str_replace(';}', "}", $buffer);
return $buffer;
}
}
?>

View File

@@ -0,0 +1,609 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteCreatorDB{
const ISNULL = "dbisnull";
private $pdb;
private $lastRowID;
public static $arrTableTitles;
/**
*
* constructor - set database object
*/
public function __construct(){
$this->pdb = new UniteProviderDBUC();
}
/**
*
* throw error
*/
private function throwError($message,$code=-1){
UniteFunctionsUC::throwError($message,$code);
}
/**
* get the original db object
*/
public function getPDB(){
return($this->pdb->getDBObject());
}
/**
* validate for errors
* @param unknown_type $prefix
*/
private function checkForErrors($prefix = ""){
$message = $this->pdb->getErrorMsg();
if(!$message)
return(false);
if(!empty($prefix))
$message = $prefix." ".$message;
$errorNum = $this->pdb->getErrorNum();
$this->throwError($message, $errorNum);
}
/**
* return if table exists
*/
public function isTableExists($table){
try{
$this->fetchSql("select * from $table limit 1", true);
}catch(Exception $e){
return(false);
}
return(true);
}
/**
*
* insert variables to some table
*/
public function insert($tableName,$arrItems){
$strFields = "";
$strValues = "";
foreach($arrItems as $field=>$value){
$value = "'".$this->escape($value)."'";
if($field == "id") continue;
if($strFields != "") $strFields .= ",";
if($strValues != "") $strValues .= ",";
$strFields .= $field;
$strValues .= $value;
}
$insertQuery = "insert into $tableName($strFields) values($strValues)";
$this->runSql($insertQuery,"insert");
$this->lastRowID = $this->pdb->insertid();
return($this->lastRowID);
}
/**
*
* get last insert id
*/
public function getLastInsertID(){
$this->lastRowID = $this->pdb->insertid();
return($this->lastRowID);
}
/**
*
* delete rows
*/
public function delete($table,$where){
UniteFunctionsUC::validateNotEmpty($table,"table name");
UniteFunctionsUC::validateNotEmpty($where,"where");
if(is_array($where))
$where = $this->getWhereString($where);
$query = "delete from $table where $where";
$success = $this->runSql($query, "delete error");
return($success);
}
/**
* delete multiple items from table by id
* Enter description here ...
*/
public function deleteMultipleByID($table, $arrItems){
foreach($arrItems as $key=>$itemID)
$arrItems[$key] = (int)$itemID;
$strItemsIDs = implode(",", $arrItems);
$this->delete($table,"id in($strItemsIDs)");
}
/**
* get category id with "all" option
*/
public function getWhereCatIDWithAll($catID){
$arrWhere = array();
if(is_numeric($catID))
$catID = (int)$catID;
if($catID === null)
$catID = "all";
//get catID where
if($catID === "all"){
$arrWhere = array();
}
else if(is_numeric($catID)){
$catID = (int)$catID;
$arrWhere[] = "catid=$catID";
}
else{ //multiple - array of id's
if(is_array($catID) == false)
UniteFunctionsUC::throwError("catIDs could be array or number");
$strCats = implode(",", $catID);
$strCats = $this->escape($strCats); //for any case
$arrWhere[] = "catid in($strCats)";
}
return($arrWhere);
}
/**
*
* get where string from where array
*/
private function getWhereString($where){
$where_format = null;
foreach ( $where as $key=>$value ) {
if($value == self::ISNULL){
$wheres[] = "($key = '' or $key is null)";
continue;
}
if($key == self::ISNULL || is_numeric($key)){
$wheres[] = $value;
continue;
}
// array('sign',values);
$sign = "=";
$isEscape = true;
if(is_array($value)){
$sign = $value[0];
$value = $value[1];
}
if(is_numeric($value) == false){
$value = $this->escape($value);
$value = "'$value'";
}
$wheres[] = "$key $sign {$value}";
}
$strWhere = implode( ' AND ', $wheres );
return($strWhere);
}
/**
*
* insert variables to some table
*/
public function update($tableName,$arrData,$where){
UniteFunctionsUC::validateNotEmpty($tableName,"table cannot be empty");
UniteFunctionsUC::validateNotEmpty($where,"where cannot be empty");
UniteFunctionsUC::validateNotEmpty($arrData,"data cannot be empty");
if(is_array($where))
$where = $this->getWhereString($where);
$strFields = "";
foreach($arrData as $field=>$value){
$value = "'".$this->escape($value)."'";
if($strFields != "") $strFields .= ",";
$strFields .= "$field=$value";
}
$updateQuery = "update $tableName set $strFields where $where";
$numRows = $this->runSql($updateQuery, "update error");
return($numRows);
}
/**
*
* run some sql query
*/
public function runSql($query){
$response = $this->pdb->query($query);
$this->checkForErrors("Regular query error");
return($response);
}
/**
*
* fetch rows from sql query
*/
public function fetchSql($query, $supressErrors = false){
$rows = $this->pdb->fetchSql($query, $supressErrors);
$this->checkForErrors("fetch");
$rows = UniteFunctionsUC::convertStdClassToArray($rows);
return($rows);
}
/**
*
* get row wp emulator
*/
public function get_row($query = null){
$rows = $this->pdb->fetchSql($query);
$this->checkForErrors("get_row");
if(count($rows) == 1)
$result = $rows[0];
else
$result = $rows;
return($result);
}
/**
* get "where" query part
*/
private function getQueryPart_where($where = ""){
if($where){
if(is_array($where))
$where = $this->getWhereString($where);
$where = " where $where";
}
return($where);
}
/**
* create fetch query
*/
private function createFetchQuery($tableName, $fields=null, $where="", $orderField="", $groupByField="", $sqlAddon=""){
if(empty($fields)){
$fields = "*";
}else{
if(is_array($fields))
$fields = implode(",", $fields);
}
$query = "select $fields from $tableName";
$where = $this->getQueryPart_where($where);
if(!empty($where))
$query .= $where;
if($orderField){
$orderField = $this->escape($orderField);
$query .= " order by $orderField";
}
if($groupByField){
$groupByField = $this->escape($groupByField);
$query .= " group by $groupByField";
}
if($sqlAddon)
$query .= " ".$sqlAddon;
return($query);
}
/**
*
* get data array from the database
*
*/
public function fetch($tableName, $where="", $orderField="", $groupByField="", $sqlAddon=""){
$query = $this->createFetchQuery($tableName, null, $where, $orderField, $groupByField, $sqlAddon);
$rows = $this->fetchSql($query);
return($rows);
}
/**
* get total rows
*/
public function getTotalRows($tableName, $where=""){
$where = $this->getQueryPart_where($where);
$query = "select count(*) as numrows from $tableName".$where;
$response = $this->fetchSql($query);
$totalRows = $response[0]["numrows"];
return($totalRows);
}
/**
* fetch records by id's
*/
public function fetchByIDs($table, $arrIDs){
if(is_string($arrIDs))
$strIDs = $arrIDs;
else
$strIDs = implode(",", $arrIDs);
$sql = "select * from {$table} where id in({$strIDs})";
$arrRecords = $this->fetchSql($sql);
return($arrRecords);
}
/**
* update objects ordering
* using (ordering, id fields, and ID's array)
*/
public function updateRecordsOrdering($table, $arrIDs){
$arrRecords = $this->fetchByIDs($table, $arrIDs);
//get items assoc
$arrRecords = UniteFunctionsUC::arrayToAssoc($arrRecords,"id");
$order = 0;
foreach($arrIDs as $recordID){
$order++;
$arrRecord = UniteFunctionsUC::getVal($arrRecords, $recordID);
if(!empty($arrRecord) && $arrRecord["ordering"] == $order)
continue;
$arrUpdate = array();
$arrUpdate["ordering"] = $order;
$this->update($table, $arrUpdate, array("id"=>$recordID));
}
}
/**
*
* get data array from the database
* pagingOptions - page, inpage
*/
public function fetchPage($tableName, $pagingOptions, $where="", $orderField="", $groupByField="", $sqlAddon=""){
$page = UniteFunctionsUC::getVal($pagingOptions, "page");
$rowsInPage = UniteFunctionsUC::getVal($pagingOptions, "inpage");
//valdiate and sanitize
UniteFunctionsUC::validateNumeric($page);
UniteFunctionsUC::validateNumeric($rowsInPage);
UniteFunctionsUC::validateNotEmpty($rowsInPage);
if($page < 1)
$page = 1;
//get total
$totalRows = $this->getTotalRows($tableName, $where);
$numPages = $pages = ceil($totalRows / $rowsInPage);
//build query
$offset = ($page - 1) * $rowsInPage;
$query = $this->createFetchQuery($tableName, null, $where, $orderField, $groupByField, $sqlAddon);
$query .= " limit $rowsInPage offset $offset";
$rows = $this->fetchSql($query);
//output response
$response = array();
$response["total"] = $totalRows;
$response["page"] = $page;
$response["num_pages"] = $numPages;
$response["inpage"] = $rowsInPage;
$response["rows"] = $rows;
return($response);
}
/**
* fields could be array or string comma saparated
*/
public function fetchFields($tableName, $fields, $where="", $orderField="", $groupByField="", $sqlAddon=""){
$query = $this->createFetchQuery($tableName, $fields, $where, $orderField, $groupByField, $sqlAddon);
$rows = $this->fetchSql($query);
return($rows);
}
/**
*
* fetch only one item. if not found - throw error
*/
public function fetchSingle($tableName,$where="",$orderField="",$groupByField="",$sqlAddon=""){
$errorEmpty = "";
if(is_array($tableName)){
$arguments = $tableName;
$tableName = UniteFunctionsUC::getVal($arguments, "tableName");
$where = UniteFunctionsUC::getVal($arguments, "where");
$orderField = UniteFunctionsUC::getVal($arguments, "orderField");
$groupByField = UniteFunctionsUC::getVal($arguments, "groupByField");
$sqlAddon = UniteFunctionsUC::getVal($arguments, "sqlAddon");
$errorEmpty = UniteFunctionsUC::getVal($arguments, "errorEmpty");
}
if(empty($errorEmpty)){
$tableTitle = UniteFunctionsUC::getVal(self::$arrTableTitles, $tableName, __("Record", "unlimited-elements-for-elementor"));
$errorEmpty = $tableTitle." ".__("not found", "unlimited-elements-for-elementor");
}
$response = $this->fetch($tableName, $where, $orderField, $groupByField, $sqlAddon);
if(empty($response)){
$this->throwError($errorEmpty);
}
$record = $response[0];
return($record);
}
/**
*
* get max order from categories list
*/
public function getMaxOrder($table, $field = "ordering"){
$query = "select MAX($field) as maxorder from {$table}";
$rows = $this->fetchSql($query);
$maxOrder = 0;
if(count($rows)>0)
$maxOrder = $rows[0]["maxorder"];
if(!is_numeric($maxOrder))
$maxOrder = 0;
return($maxOrder);
}
/**
* update layout in db
*/
public function createObjectInDB($table, $arrInsert){
$maxOrder = $this->getMaxOrder($table);
$arrInsert["ordering"] = $maxOrder+1;
$id = $this->insert($table, $arrInsert);
return($id);
}
/**
*
* escape data to avoid sql errors and injections.
*/
public function escape($string){
$newString = $this->pdb->escape($string);
return($newString);
}
/**
* get sql addon type for quest string
*/
public function getSqlAddonType($addonType, $dbfield = "addontype"){
if(is_array($addonType)){
$arrSql = array();
foreach($addonType as $singleType)
$arrSql[] = $this->getSqlAddonType($singleType, $dbfield);
$sql = "(".implode(" or ", $arrSql).")";
return($sql);
}
if($addonType == GlobalsUC::ADDON_TYPE_REGULAR_ADDON || $addonType == GlobalsUC::ADDON_TYPE_LAYOUT_GENERAL)
$addonType = null;
$addonType = $this->escape($addonType);
if(empty($addonType)){
$where = "({$dbfield}='' or {$dbfield} is null)";
}else
$where = "{$dbfield}='{$addonType}'";
return($where);
}
}
?>

View File

@@ -0,0 +1,25 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteElementsBaseUC{
protected $db;
protected $imageView;
public function __construct(){
$this->db = new UniteCreatorDB();
$this->imageView = new UniteImageViewUC();
}
}
?>

View File

@@ -0,0 +1,130 @@
<?php
class UEExchangeRateAPIClient{
const BASE_URL = "https://v6.exchangerate-api.com/v6";
private $apiKey;
private $cacheTime = 0; // in seconds
/**
* Create a new client instance.
*
* @param string $apiKey
*
* @return void
*/
public function __construct($apiKey){
$this->apiKey = $apiKey;
}
/**
* Set the cache time.
*
* @param int $seconds
*
* @return void
*/
public function setCacheTime($seconds){
$this->cacheTime = $seconds;
}
/**
* Get a list of rates for the given currency (ISO 4217).
*
* @param string $currency
*
* @return array
* @throws Exception
*/
public function getRates($currency){
try{
$currency = urlencode($currency);
$response = $this->get("/latest/$currency");
$rates = array();
foreach($response["conversion_rates"] as $code => $rate){
$rates[] = UEExchangeRateAPIRate::transform(array(
'code' => $code,
'rate' => $rate,
));
}
return $rates;
}catch(UEHttpResponseException $exception){
if($exception->getResponse()->status() === 404)
throw new Exception("Invalid currency.");
throw $exception;
}
}
/**
* Make a GET request to the API.
*
* @param $endpoint
* @param $params
*
* @return array
* @throws Exception
*/
private function get($endpoint, $params = array()){
return $this->request(UEHttpRequest::METHOD_GET, $endpoint, $params);
}
/**
* Make a request to the API.
*
* @param string $method
* @param string $endpoint
* @param array $params
*
* @return array
* @throws Exception
*/
private function request($method, $endpoint, $params = array()){
$url = self::BASE_URL . "/" . $this->apiKey . $endpoint;
$query = ($method === UEHttpRequest::METHOD_GET) ? $params : array();
$body = ($method !== UEHttpRequest::METHOD_GET) ? $params : array();
$request = UEHttp::make();
$request->asJson();
$request->acceptJson();
$request->cacheTime($this->cacheTime);
$request->withQuery($query);
$request->withBody($body);
$request->validateResponse(function($response){
$data = $response->json();
if($data["result"] !== "success")
$this->throwError($data["error-type"]);
});
$response = $request->request($method, $url);
$data = $response->json();
return $data;
}
/**
* Thrown an exception with the given message.
*
* @param string $message
*
* @return void
* @throws Exception
*/
private function throwError($message){
UniteFunctionsUC::throwError("ExchangeRate API Error: $message");
}
}

View File

@@ -0,0 +1,6 @@
<?php
require_once __DIR__ . "/client.class.php";
require_once __DIR__ . "/model.class.php";
require_once __DIR__ . "/rate.class.php";

View File

@@ -0,0 +1,66 @@
<?php
abstract class UEExchangeRateAPIModel{
private $attributes;
/**
* Create a new class instance.
*
* @param array $attributes
*
* @return void
*/
private function __construct($attributes){
$this->attributes = $attributes;
}
/**
* Transform list of items into models.
*
* @param array $items
*
* @return array
*/
public static function transformAll($items){
$data = array();
foreach($items as $attributes){
$data[] = self::transform($attributes);
}
return $data;
}
/**
* Transform attributes into a model.
*
* @param array $attributes
*
* @return static
*/
public static function transform($attributes){
$model = new static($attributes);
return $model;
}
/**
* Get the attribute value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
protected function getAttribute($key, $fallback = null){
$value = UniteFunctionsUC::getVal($this->attributes, $key, $fallback);
return $value;
}
}

View File

@@ -0,0 +1,925 @@
<?php
class UEExchangeRateAPIRate extends UEExchangeRateAPIModel{
/**
* Get the identifier.
*
* @return string
*/
public function getId(){
$id = $this->getCode();
$id = strtolower($id);
return $id;
}
/**
* Get the code.
*
* @return string
*/
public function getCode(){
$code = $this->getAttribute("code");
return $code;
}
/**
* Get the name.
*
* @return string
*/
public function getName(){
$name = $this->getInfo("name", $this->getCode());
return $name;
}
/**
* Get the symbol.
*
* @return string
*/
public function getSymbol(){
$symbol = $this->getInfo("symbol", $this->getCode());
return $symbol;
}
/**
* Get the flag URL.
*
* @return string
*/
public function getFlagUrl(){
$country = $this->getCountry();
$country = strtolower($country);
$url = "https://flagcdn.com/" . $country . ".svg";
return $url;
}
/**
* Get the rate.
*
* @param int $precision
*
* @return float
*/
public function getRate($precision = 2){
$rate = $this->getAttribute("rate");
$rate = number_format($rate, $precision, ".", "");
return $rate;
}
/**
* Get the info.
*
* @param string $field
* @param string $code
*
* @return string
*/
private function getInfo($field, $code){
$info = array(
"USD" => array(
"name" => "United States Dollar",
"symbol" => "$",
"country" => "US",
),
"AED" => array(
"name" => "United Arab Emirates Dirham",
"symbol" => "د.إ",
"country" => "AE",
),
"AFN" => array(
"name" => "Afghan Afghani",
"symbol" => "؋",
"country" => "AF",
),
"ALL" => array(
"name" => "Albanian Lek",
"symbol" => "L",
"country" => "AL",
),
"AMD" => array(
"name" => "Armenian Dram",
"symbol" => "֏",
"country" => "AM",
),
"ANG" => array(
"name" => "Netherlands Antillean Guilder",
"symbol" => "ƒ",
"country" => "NL",
),
"AOA" => array(
"name" => "Angolan Kwanza",
"symbol" => "Kz",
"country" => "AO",
),
"ARS" => array(
"name" => "Argentine Peso",
"symbol" => "$",
"country" => "AR",
),
"AUD" => array(
"name" => "Australian Dollar",
"symbol" => "$",
"country" => "AU",
),
"AWG" => array(
"name" => "Aruban Florin",
"symbol" => "ƒ",
"country" => "AW",
),
"AZN" => array(
"name" => "Azerbaijani Manat",
"symbol" => "",
"country" => "AZ",
),
"BAM" => array(
"name" => "Bosnia-Herzegovina Convertible Mark",
"symbol" => "KM",
"country" => "BA",
),
"BBD" => array(
"name" => "Barbadian Dollar",
"symbol" => "$",
"country" => "BB",
),
"BDT" => array(
"name" => "Bangladeshi Taka",
"symbol" => "",
"country" => "BD",
),
"BGN" => array(
"name" => "Bulgarian Lev",
"symbol" => "лв",
"country" => "BG",
),
"BHD" => array(
"name" => "Bahraini Dinar",
"symbol" => "ب.د",
"country" => "BH",
),
"BIF" => array(
"name" => "Burundian Franc",
"symbol" => "Fr",
"country" => "BI",
),
"BMD" => array(
"name" => "Bermudian Dollar",
"symbol" => "$",
"country" => "BM",
),
"BND" => array(
"name" => "Brunei Dollar",
"symbol" => "$",
"country" => "BN",
),
"BOB" => array(
"name" => "Bolivian Boliviano",
"symbol" => "Bs.",
"country" => "BO",
),
"BRL" => array(
"name" => "Brazilian Real",
"symbol" => "R$",
"country" => "BR",
),
"BSD" => array(
"name" => "Bahamian Dollar",
"symbol" => "$",
"country" => "BS",
),
"BTN" => array(
"name" => "Bhutanese Ngultrum",
"symbol" => "Nu.",
"country" => "BT",
),
"BWP" => array(
"name" => "Botswanan Pula",
"symbol" => "P",
"country" => "BW",
),
"BYN" => array(
"name" => "Belarusian Ruble",
"symbol" => "Br",
"country" => "BY",
),
"BZD" => array(
"name" => "Belize Dollar",
"symbol" => "BZ$",
"country" => "BZ",
),
"CAD" => array(
"name" => "Canadian Dollar",
"symbol" => "$",
"country" => "CA",
),
"CDF" => array(
"name" => "Congolese Franc",
"symbol" => "Fr",
"country" => "CD",
),
"CHF" => array(
"name" => "Swiss Franc",
"symbol" => "Fr",
"country" => "CH",
),
"CLP" => array(
"name" => "Chilean Peso",
"symbol" => "$",
"country" => "CL",
),
"CNY" => array(
"name" => "Chinese Yuan",
"symbol" => "¥",
"country" => "CN",
),
"COP" => array(
"name" => "Colombian Peso",
"symbol" => "$",
"country" => "CO",
),
"CRC" => array(
"name" => "Costa Rican Colón",
"symbol" => "",
"country" => "CR",
),
"CUP" => array(
"name" => "Cuban Peso",
"symbol" => "$",
"country" => "CU",
),
"CVE" => array(
"name" => "Cape Verdean Escudo",
"symbol" => "$",
"country" => "CV",
),
"CZK" => array(
"name" => "Czech Republic Koruna",
"symbol" => "",
"country" => "CZ",
),
"DJF" => array(
"name" => "Djiboutian Franc",
"symbol" => "Fdj",
"country" => "DJ",
),
"DKK" => array(
"name" => "Danish Krone",
"symbol" => "kr",
"country" => "DK",
),
"DOP" => array(
"name" => "Dominican Peso",
"symbol" => "RD$",
"country" => "DO",
),
"DZD" => array(
"name" => "Algerian Dinar",
"symbol" => "دج",
"country" => "DZ",
),
"EGP" => array(
"name" => "Egyptian Pound",
"symbol" => "",
"country" => "EG",
),
"ERN" => array(
"name" => "Eritrean Nakfa",
"symbol" => "Nfk",
"country" => "ER",
),
"ETB" => array(
"name" => "Ethiopian Birr",
"symbol" => "Br",
"country" => "ET",
),
"EUR" => array(
"name" => "Euro",
"symbol" => "",
"country" => "EU",
),
"FJD" => array(
"name" => "Fijian Dollar",
"symbol" => "$",
"country" => "FJ",
),
"FKP" => array(
"name" => "Falkland Islands Pound",
"symbol" => "£",
"country" => "FK",
),
"FOK" => array(
"name" => "Faroese Króna",
"symbol" => "kr",
"country" => "FO",
),
"GBP" => array(
"name" => "British Pound Sterling",
"symbol" => "£",
"country" => "GB",
),
"GEL" => array(
"name" => "Georgian Lari",
"symbol" => "",
"country" => "GE",
),
"GGP" => array(
"name" => "Guernsey Pound",
"symbol" => "£",
"country" => "GG",
),
"GHS" => array(
"name" => "Ghanaian Cedi",
"symbol" => "",
"country" => "GH",
),
"GIP" => array(
"name" => "Gibraltar Pound",
"symbol" => "£",
"country" => "GI",
),
"GMD" => array(
"name" => "Gambian Dalasi",
"symbol" => "D",
"country" => "GM",
),
"GNF" => array(
"name" => "Guinean Franc",
"symbol" => "Fr",
"country" => "GN",
),
"GTQ" => array(
"name" => "Guatemalan Quetzal",
"symbol" => "Q",
"country" => "GT",
),
"GYD" => array(
"name" => "Guyanese Dollar",
"symbol" => "$",
"country" => "GY",
),
"HKD" => array(
"name" => "Hong Kong Dollar",
"symbol" => "$",
"country" => "HK",
),
"HNL" => array(
"name" => "Honduran Lempira",
"symbol" => "L",
"country" => "HN",
),
"HRK" => array(
"name" => "Croatian Kuna",
"symbol" => "kn",
"country" => "HR",
),
"HTG" => array(
"name" => "Haitian Gourde",
"symbol" => "G",
"country" => "HT",
),
"HUF" => array(
"name" => "Hungarian Forint",
"symbol" => "Ft",
"country" => "HU",
),
"IDR" => array(
"name" => "Indonesian Rupiah",
"symbol" => "Rp",
"country" => "ID",
),
"ILS" => array(
"name" => "Israeli New Shekel",
"symbol" => "",
"country" => "IL",
),
"IMP" => array(
"name" => "Isle of Man Pound",
"symbol" => "£",
"country" => "IM",
),
"INR" => array(
"name" => "Indian Rupee",
"symbol" => "",
"country" => "IN",
),
"IQD" => array(
"name" => "Iraqi Dinar",
"symbol" => "ع.د",
"country" => "IQ",
),
"IRR" => array(
"name" => "Iranian Rial",
"symbol" => "",
"country" => "IR",
),
"ISK" => array(
"name" => "Icelandic Króna",
"symbol" => "kr",
"country" => "IS",
),
"JEP" => array(
"name" => "Jersey Pound",
"symbol" => "£",
"country" => "JE",
),
"JMD" => array(
"name" => "Jamaican Dollar",
"symbol" => "J$",
"country" => "JM",
),
"JOD" => array(
"name" => "Jordanian Dinar",
"symbol" => "د.ا",
"country" => "JO",
),
"JPY" => array(
"name" => "Japanese Yen",
"symbol" => "¥",
"country" => "JP",
),
"KES" => array(
"name" => "Kenyan Shilling",
"symbol" => "KSh",
"country" => "KE",
),
"KGS" => array(
"name" => "Kyrgystani Som",
"symbol" => "с",
"country" => "KG",
),
"KHR" => array(
"name" => "Cambodian Riel",
"symbol" => "",
"country" => "KH",
),
"KID" => array(
"name" => "Kiribati Dollar",
"symbol" => "$",
"country" => "KI",
),
"KMF" => array(
"name" => "Comorian Franc",
"symbol" => "Fr",
"country" => "KM",
),
"KRW" => array(
"name" => "South Korean Won",
"symbol" => "",
"country" => "KR",
),
"KWD" => array(
"name" => "Kuwaiti Dinar",
"symbol" => "د.ك",
"country" => "KW",
),
"KYD" => array(
"name" => "Cayman Islands Dollar",
"symbol" => "$",
"country" => "KY",
),
"KZT" => array(
"name" => "Kazakhstani Tenge",
"symbol" => "",
"country" => "KZ",
),
"LAK" => array(
"name" => "Laotian Kip",
"symbol" => "",
"country" => "LA",
),
"LBP" => array(
"name" => "Lebanese Pound",
"symbol" => "ل.ل",
"country" => "LB",
),
"LKR" => array(
"name" => "Sri Lankan Rupee",
"symbol" => "",
"country" => "LK",
),
"LRD" => array(
"name" => "Liberian Dollar",
"symbol" => "$",
"country" => "LR",
),
"LSL" => array(
"name" => "Lesotho Loti",
"symbol" => "L",
"country" => "LS",
),
"LYD" => array(
"name" => "Libyan Dinar",
"symbol" => "ل.د",
"country" => "LY",
),
"MAD" => array(
"name" => "Moroccan Dirham",
"symbol" => "د.م.",
"country" => "MA",
),
"MDL" => array(
"name" => "Moldovan Leu",
"symbol" => "L",
"country" => "MD",
),
"MGA" => array(
"name" => "Malagasy Ariary",
"symbol" => "Ar",
"country" => "MG",
),
"MKD" => array(
"name" => "Macedonian Denar",
"symbol" => "ден",
"country" => "MK",
),
"MMK" => array(
"name" => "Myanmar Kyat",
"symbol" => "K",
"country" => "MM",
),
"MNT" => array(
"name" => "Mongolian Tugrik",
"symbol" => "",
"country" => "MN",
),
"MOP" => array(
"name" => "Macanese Pataca",
"symbol" => "MOP$",
"country" => "MO",
),
"MRU" => array(
"name" => "Mauritanian Ouguiya",
"symbol" => "UM",
"country" => "MR",
),
"MUR" => array(
"name" => "Mauritian Rupee",
"symbol" => "",
"country" => "MU",
),
"MVR" => array(
"name" => "Maldivian Rufiyaa",
"symbol" => "Rf",
"country" => "MV",
),
"MWK" => array(
"name" => "Malawian Kwacha",
"symbol" => "MK",
"country" => "MW",
),
"MXN" => array(
"name" => "Mexican Peso",
"symbol" => "$",
"country" => "MX",
),
"MYR" => array(
"name" => "Malaysian Ringgit",
"symbol" => "RM",
"country" => "MY",
),
"MZN" => array(
"name" => "Mozambican Metical",
"symbol" => "MT",
"country" => "MZ",
),
"NAD" => array(
"name" => "Namibian Dollar",
"symbol" => "$",
"country" => "NA",
),
"NGN" => array(
"name" => "Nigerian Naira",
"symbol" => "",
"country" => "NG",
),
"NIO" => array(
"name" => "Nicaraguan Córdoba",
"symbol" => "C$",
"country" => "NI",
),
"NOK" => array(
"name" => "Norwegian Krone",
"symbol" => "kr",
"country" => "NO",
),
"NPR" => array(
"name" => "Nepalese Rupee",
"symbol" => "",
"country" => "NP",
),
"NZD" => array(
"name" => "New Zealand Dollar",
"symbol" => "$",
"country" => "NZ",
),
"OMR" => array(
"name" => "Omani Rial",
"symbol" => "ر.ع.",
"country" => "OM",
),
"PAB" => array(
"name" => "Panamanian Balboa",
"symbol" => "B/.",
"country" => "PA",
),
"PEN" => array(
"name" => "Peruvian Nuevo Sol",
"symbol" => "S/.",
"country" => "PE",
),
"PGK" => array(
"name" => "Papua New Guinean Kina",
"symbol" => "K",
"country" => "PG",
),
"PHP" => array(
"name" => "Philippine Peso",
"symbol" => "",
"country" => "PH",
),
"PKR" => array(
"name" => "Pakistani Rupee",
"symbol" => "",
"country" => "PK",
),
"PLN" => array(
"name" => "Polish Złoty",
"symbol" => "",
"country" => "PL",
),
"PYG" => array(
"name" => "Paraguayan Guarani",
"symbol" => "",
"country" => "PY",
),
"QAR" => array(
"name" => "Qatari Riyal",
"symbol" => "ر.ق",
"country" => "QA",
),
"RON" => array(
"name" => "Romanian Leu",
"symbol" => "lei",
"country" => "RO",
),
"RSD" => array(
"name" => "Serbian Dinar",
"symbol" => "дин.",
"country" => "RS",
),
"RUB" => array(
"name" => "Russian Ruble",
"symbol" => "",
"country" => "RU",
),
"RWF" => array(
"name" => "Rwandan Franc",
"symbol" => "Fr",
"country" => "RW",
),
"SAR" => array(
"name" => "Saudi Riyal",
"symbol" => "ر.س",
"country" => "SA",
),
"SBD" => array(
"name" => "Solomon Islands Dollar",
"symbol" => "$",
"country" => "SB",
),
"SCR" => array(
"name" => "Seychellois Rupee",
"symbol" => "",
"country" => "SC",
),
"SDG" => array(
"name" => "Sudanese Pound",
"symbol" => "ج.س.",
"country" => "SD",
),
"SEK" => array(
"name" => "Swedish Krona",
"symbol" => "kr",
"country" => "SE",
),
"SGD" => array(
"name" => "Singapore Dollar",
"symbol" => "$",
"country" => "SG",
),
"SHP" => array(
"name" => "Saint Helena Pound",
"symbol" => "£",
"country" => "SH",
),
"SLE" => array(
"name" => "Sierra Leonean Leone",
"symbol" => "Le",
"country" => "SL",
),
"SLL" => array(
"name" => "Sierra Leonean Leone",
"symbol" => "Le",
"country" => "SL",
),
"SOS" => array(
"name" => "Somali Shilling",
"symbol" => "Sh.So.",
"country" => "SO",
),
"SRD" => array(
"name" => "Surinamese Dollar",
"symbol" => "$",
"country" => "SR",
),
"SSP" => array(
"name" => "South Sudanese Pound",
"symbol" => "£",
"country" => "SS",
),
"STN" => array(
"name" => "São Tomé and Príncipe Dobra",
"symbol" => "Db",
"country" => "ST",
),
"SYP" => array(
"name" => "Syrian Pound",
"symbol" => "£",
"country" => "SY",
),
"SZL" => array(
"name" => "Swazi Lilangeni",
"symbol" => "L",
"country" => "SZ",
),
"THB" => array(
"name" => "Thai Baht",
"symbol" => "฿",
"country" => "TH",
),
"TJS" => array(
"name" => "Tajikistani Somoni",
"symbol" => "ЅМ",
"country" => "TJ",
),
"TMT" => array(
"name" => "Turkmenistani Manat",
"symbol" => "T",
"country" => "TM",
),
"TND" => array(
"name" => "Tunisian Dinar",
"symbol" => "د.ت",
"country" => "TN",
),
"TOP" => array(
"name" => "Tongan Pa'anga",
"symbol" => "T$",
"country" => "TO",
),
"TRY" => array(
"name" => "Turkish Lira",
"symbol" => "",
"country" => "TR",
),
"TTD" => array(
"name" => "Trinidad and Tobago Dollar",
"symbol" => "TT$",
"country" => "TT",
),
"TVD" => array(
"name" => "Tuvaluan Dollar",
"symbol" => "$",
"country" => "TV",
),
"TWD" => array(
"name" => "New Taiwan Dollar",
"symbol" => "NT$",
"country" => "TW",
),
"TZS" => array(
"name" => "Tanzanian Shilling",
"symbol" => "TSh",
"country" => "TZ",
),
"UAH" => array(
"name" => "Ukrainian Hryvnia",
"symbol" => "",
"country" => "UA",
),
"UGX" => array(
"name" => "Ugandan Shilling",
"symbol" => "USh",
"country" => "UG",
),
"UYU" => array(
"name" => "Uruguayan Peso",
"symbol" => "$",
"country" => "UY",
),
"UZS" => array(
"name" => "Uzbekistan Som",
"symbol" => "лв",
"country" => "UZ",
),
"VES" => array(
"name" => "Venezuelan Bolívar",
"symbol" => "Bs.S",
"country" => "VE",
),
"VND" => array(
"name" => "Vietnamese Dong",
"symbol" => "",
"country" => "VN",
),
"VUV" => array(
"name" => "Vanuatu Vatu",
"symbol" => "VT",
"country" => "VU",
),
"WST" => array(
"name" => "Samoan Tala",
"symbol" => "WS$",
"country" => "WS",
),
"XAF" => array(
"name" => "Central African CFA Franc",
"symbol" => "FCFA",
"country" => "CM",
),
"XCD" => array(
"name" => "East Caribbean Dollar",
"symbol" => "$",
"country" => "AG",
),
"XDR" => array(
"name" => "International Monetary Fund (IMF) Special Drawing Rights",
"symbol" => "XDR",
"country" => "",
),
"XOF" => array(
"name" => "West African CFA Franc",
"symbol" => "CFA",
"country" => "BJ",
),
"XPF" => array(
"name" => "CFP Franc",
"symbol" => "Fr",
"country" => "PF",
),
"YER" => array(
"name" => "Yemeni Rial",
"symbol" => "",
"country" => "YE",
),
"ZAR" => array(
"name" => "South African Rand",
"symbol" => "R",
"country" => "ZA",
),
"ZMW" => array(
"name" => "Zambian Kwacha",
"symbol" => "ZK",
"country" => "ZM",
),
"ZWL" => array(
"name" => "Zimbabwean Dollar",
"symbol" => "Z$",
"country" => "ZW",
),
);
$fields = UniteFunctionsUC::getVal($info, $code, array());
$value = UniteFunctionsUC::getVal($fields, $field, "");
return $value;
}
/**
* Get the country.
*
* @return string
*/
private function getCountry(){
$country = $this->getInfo("country", $this->getCode());
return $country;
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
//---------------------------------------------------------------------------------------------------------------------
if(!function_exists("dmp")){
function dmp($str){
echo "<div align='left' style='direction:ltr;color:black;'>";
echo "<pre>";
print_r($str);
echo "</pre>";
echo "</div>";
}
}
if(!function_exists("dmpGet")){
function dmpGet($str){
$html = "";
$html .= "<div align='left' style='direction:ltr;color:black;'>";
$html .= "<pre>";
$html .= print_r($str, true);
$html .= "</pre>";
$html .= "</div>";
return($html);
}
}

View File

@@ -0,0 +1,120 @@
<?php
class UEGoogleAPICalendarEvent extends UEGoogleAPIModel{
/**
* Get the identifier.
*
* @return int
*/
public function getId(){
$id = $this->getAttribute("id");
return $id;
}
/**
* Get the title.
*
* @return string
*/
public function getTitle(){
$title = $this->getAttribute("summary");
return $title;
}
/**
* Get the description.
*
* @param bool $asHtml
*
* @return string|null
*/
public function getDescription($asHtml = false){
$description = $this->getAttribute("description");
if($asHtml === true)
$description = nl2br($description);
return $description;
}
/**
* Get the location.
*
* @return string|null
*/
public function getLocation(){
$location = $this->getAttribute("location");
return $location;
}
/**
* Get the URL.
*
* @return string
*/
public function getUrl(){
$url = $this->getAttribute("htmlLink");
return $url;
}
/**
* Get the start date.
*
* @param string $format
*
* @return string
*/
public function getStartDate($format){
$start = $this->getAttribute("start");
$date = $this->getDate($start, $format);
return $date;
}
/**
* Get the end date.
*
* @param string $format
*
* @return string
*/
public function getEndDate($format){
$end = $this->getAttribute("end");
$date = $this->getDate($end, $format);
return $date;
}
/**
* Get the date.
*
* @param object $time
* @param string $format
*
* @return string
*/
private function getDate($time, $format){
$date = UniteFunctionsUC::getVal($time, "date", null);
$dateTime = UniteFunctionsUC::getVal($time, "dateTime", null);
$date = $date ?: $dateTime;
$time = strtotime($date);
$date = date($format, $time);
return $date;
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* https://developers.google.com/calendar/api/v3/reference
*/
class UEGoogleAPICalendarService extends UEGoogleAPIClient{
/**
* Get the events.
*
* @param string $calendarId
* @param array $params
*
* @return UEGoogleAPICalendarEvent[]
*/
public function getEvents($calendarId, $params = array()){
$calendarId = urlencode($calendarId);
$params["timeZone"] = wp_timezone_string();
$response = $this->get("/calendars/$calendarId/events", $params);
$response = UEGoogleAPICalendarEvent::transformAll($response["items"]);
return $response;
}
/**
* Get the base URL for the API.
*
* @return string
*/
protected function getBaseUrl(){
return "https://www.googleapis.com/calendar/v3";
}
}

View File

@@ -0,0 +1,181 @@
<?php
abstract class UEGoogleAPIClient{
const PARAM_QUERY = "__query__";
private $accessToken;
private $apiKey;
private $cacheTime = 0; // in seconds
/**
* Set the access token.
*
* @param string $token
*
* @return void
*/
public function setAccessToken($token){
$this->accessToken = $token;
}
/**
* Set the API key.
*
* @param string $key
*
* @return void
*/
public function setApiKey($key){
$this->apiKey = $key;
}
/**
* Set the cache time.
*
* @param int $seconds
*
* @return void
*/
public function setCacheTime($seconds){
$this->cacheTime = $seconds;
}
/**
* Get the base URL for the API.
*
* @return string
*/
abstract protected function getBaseUrl();
/**
* Make a GET request to the API.
*
* @param $endpoint
* @param $params
*
* @return array
* @throws Exception
*/
protected function get($endpoint, $params = array()){
return $this->request(UEHttpRequest::METHOD_GET, $endpoint, $params);
}
/**
* Make a PUT request to the API.
*
* @param $endpoint
* @param $params
*
* @return array
* @throws Exception
*/
protected function put($endpoint, $params = array()){
return $this->request(UEHttpRequest::METHOD_PUT, $endpoint, $params);
}
/**
* Make a POST request to the API.
*
* @param $endpoint
* @param $params
*
* @return array
* @throws Exception
*/
protected function post($endpoint, $params = array()){
return $this->request(UEHttpRequest::METHOD_POST, $endpoint, $params);
}
/**
* Make a request to the API.
*
* @param string $method
* @param string $endpoint
* @param array $params
*
* @return array
* @throws Exception
*/
private function request($method, $endpoint, $params = array()){
$url = $this->getBaseUrl() . $endpoint;
$query = ($method === UEHttpRequest::METHOD_GET) ? $params : array();
$body = ($method !== UEHttpRequest::METHOD_GET) ? $params : array();
if(empty($params[self::PARAM_QUERY]) === false){
$query = array_merge($query, $params[self::PARAM_QUERY]);
unset($params[self::PARAM_QUERY]);
}
$query = array_merge($query, $this->getAuthParams());
$request = UEHttp::make();
$request->asJson();
$request->acceptJson();
$request->cacheTime($this->cacheTime);
$request->withQuery($query);
$request->withBody($body);
$request->validateResponse(function($response){
$data = $response->json();
if(empty($data["error"]) === false){
$error = $data["error"];
$message = $error["message"];
$status = isset($error["status"]) ? $error["status"] : $error["code"];
$this->throwError("$message ($status)");
}elseif(empty($data["error_message"]) === false){
$message = $data["error_message"];
$status = isset($data["status"]) ? $data["status"] : $data["code"];
$this->throwError("$message ($status)");
}
});
$response = $request->request($method, $url);
$data = $response->json();
return $data;
}
/**
* Get parameters for the authorization.
*
* @return array
* @throws Exception
*/
private function getAuthParams(){
if(empty($this->accessToken) === false)
return array("access_token" => $this->accessToken);
if(empty($this->apiKey) === false)
return array("key" => $this->apiKey);
$this->throwError("Either an access token or an API key must be specified.");
}
/**
* Thrown an exception with the given message.
*
* @param string $message
*
* @return void
* @throws Exception
*/
private function throwError($message){
UniteFunctionsUC::throwError("Google API Error: $message");
}
}

View File

@@ -0,0 +1,341 @@
<?php
class UEGoogleAPIHelper{
const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
const SCOPE_CALENDAR_EVENTS = "https://www.googleapis.com/auth/calendar.events.readonly";
const SCOPE_SHEETS_ALL = "https://www.googleapis.com/auth/spreadsheets";
const SCOPE_USER_EMAIL = "https://www.googleapis.com/auth/userinfo.email";
const SCOPE_YOUTUBE = "https://www.googleapis.com/auth/youtube.readonly";
private static $credentials = array();
/**
* Get the API key.
*
* @return string
*/
public static function getApiKey(){
$apiKey = HelperProviderCoreUC_EL::getGeneralSetting("google_api_key");
return $apiKey;
}
/**
* Get the access token.
*
* @return string
*/
public static function getAccessToken(){
$credentials = self::getCredentials();
$accessToken = UniteFunctionsUC::getVal($credentials, "access_token");
return $accessToken;
}
/**
* Get the fresh access token.
*
* @return string
* @throws Exception
*/
public static function getFreshAccessToken(){
if(self::isAccessTokenExpired() === true)
self::refreshAccessToken();
$accessToken = self::getAccessToken();
return $accessToken;
}
/**
* Get the user's email address.
*
* @return string
*/
public static function getUserEmail(){
$credentials = self::getCredentials();
$user = UniteFunctionsUC::getVal($credentials, "user", array());
$email = UniteFunctionsUC::getVal($user, "email");
return $email;
}
/**
* Get the authorization URL.
*
* @return string
*/
public static function getAuthUrl(){
$returnUrl = HelperUC::getUrlAjax("save_google_connect_data");
$returnUrl = UniteFunctionsUC::encodeContent($returnUrl);
$params = array(
"client_id" => GlobalsUnlimitedElements::GOOGLE_CONNECTION_CLIENTID,
"redirect_uri" => GlobalsUnlimitedElements::GOOGLE_CONNECTION_URL,
"scope" => implode(" ", self::getScopes()),
"access_type" => "offline",
"prompt" => "consent select_account",
"response_type" => "code",
"include_granted_scopes" => "true",
"state" => $returnUrl,
);
$url = self::AUTH_URL . "?" . http_build_query($params);
return $url;
}
/**
* Get the revoke URL.
*
* @return string
*/
public static function getRevokeUrl(){
$returnUrl = HelperUC::getUrlAjax("remove_google_connect_data");
$returnUrl = UniteFunctionsUC::encodeContent($returnUrl);
$params = array(
"revoke_token" => self::getAccessToken(),
"state" => $returnUrl,
);
$url = GlobalsUnlimitedElements::GOOGLE_CONNECTION_URL . "?" . http_build_query($params);
return $url;
}
/**
* Save the credentials.
*
* @param array $data
*
* @return void
* @throws Exception
*/
public static function saveCredentials($data){
$accessToken = UniteFunctionsUC::getVal($data, "access_token");
$refreshToken = UniteFunctionsUC::getVal($data, "refresh_token");
$expiresAt = UniteFunctionsUC::getVal($data, "expires_at", 0);
$scopes = UniteFunctionsUC::getVal($data, "scopes", array());
$user = UniteFunctionsUC::getVal($data, "user", array());
UniteFunctionsUC::validateNotEmpty($accessToken, "access_token");
UniteFunctionsUC::validateNotEmpty($refreshToken, "refresh_token");
UniteFunctionsUC::validateNotEmpty($expiresAt, "expires_at");
UniteFunctionsUC::validateNotEmpty($scopes, "scopes");
UniteFunctionsUC::validateNotEmpty($user, "user");
self::validateScopes($scopes);
$credentials = array(
"access_token" => $accessToken,
"refresh_token" => $refreshToken,
"expires_at" => $expiresAt,
"scopes" => $scopes,
"user" => $user,
);
self::setCredentials($credentials);
}
/**
* Remove the credentials.
*
* @return void
*/
public static function removeCredentials(){
self::setCredentials(array());
}
/**
* Redirect to settings.
*
* @param array $params
*
* @return void
*/
public static function redirectToSettings($params = array()){
$params = http_build_query($params) . "#tab=integrations";
$url = HelperUC::getViewUrl(GlobalsUnlimitedElements::VIEW_SETTINGS_ELEMENTOR, $params);
UniteFunctionsUC::redirectToUrl($url);
}
/**
* Get the scopes.
*
* @return array
*/
private static function getScopes(){
$scopes = array(
self::SCOPE_SHEETS_ALL,
self::SCOPE_USER_EMAIL,
);
if(GlobalsUnlimitedElements::$enableGoogleCalendarScopes === true)
$scopes[] = self::SCOPE_CALENDAR_EVENTS;
if(GlobalsUnlimitedElements::$enableGoogleYoutubeScopes === true)
$scopes[] = self::SCOPE_YOUTUBE;
return $scopes;
}
/**
* Validate the scopes.
*
* @param array $scopes
*
* @return void
* @throws Exception
*/
private static function validateScopes($scopes){
$requestedScopes = self::getScopes();
$grantedScopes = array_intersect($requestedScopes, $scopes);
if(count($grantedScopes) !== count($requestedScopes))
UniteFunctionsUC::throwError("Required permissions are missing. Please grant all requested permissions.");
}
/**
* Get the credentials.
*
* @return array
*/
private static function getCredentials(){
if(empty(self::$credentials) === true)
self::$credentials = HelperProviderUC::getGoogleConnectCredentials();
return self::$credentials;
}
/**
* Set the credentials.
*
* @param array $credentials
*
* @return void
*/
private static function setCredentials($credentials){
self::$credentials = $credentials;
HelperProviderUC::saveGoogleConnectCredentials(self::$credentials);
}
/**
* Merge the credentials.
*
* @param array $credentials
*
* @return void
*/
private static function mergeCredentials($credentials){
$credentials = array_merge(self::getCredentials(), $credentials);
self::setCredentials($credentials);
}
/**
* Get the refresh token.
*
* @return string
*/
private static function getRefreshToken(){
$credentials = self::getCredentials();
$refreshToken = UniteFunctionsUC::getVal($credentials, "refresh_token");
return $refreshToken;
}
/**
* Get the expiration time.
*
* @return int
*/
private static function getExpirationTime(){
$credentials = self::getCredentials();
$expirationTime = UniteFunctionsUC::getVal($credentials, "expires_at", 0);
return $expirationTime;
}
/**
* Determine if the access token is expired.
*
* @return bool
*/
private static function isAccessTokenExpired(){
$accessToken = self::getAccessToken();
$expirationTime = self::getExpirationTime();
if(empty($accessToken) === true)
return true;
// Check if the token expires in the next 30 seconds
if($expirationTime - 30 < time())
return true;
return false;
}
/**
* Refresh the access token.
*
* @return void
* @throws Exception
*/
private static function refreshAccessToken(){
$refreshToken = self::getRefreshToken();
if(empty($refreshToken) === true)
UniteFunctionsUC::throwError("Refresh token is missing.");
$request = UEHttp::make();
$request->acceptJson();
$response = $request->get(GlobalsUnlimitedElements::GOOGLE_CONNECTION_URL, array("refresh_token" => $refreshToken));
$data = $response->json();
if(isset($data["error"]) === true)
UniteFunctionsUC::throwError("Unable to refresh the access token: {$data["error"]}");
$accessToken = UniteFunctionsUC::getVal($data, "access_token");
$expiresAt = UniteFunctionsUC::getVal($data, "expires_at", 0);
$scopes = UniteFunctionsUC::getVal($data, "scopes", array());
UniteFunctionsUC::validateNotEmpty($accessToken, "access_token");
UniteFunctionsUC::validateNotEmpty($expiresAt, "expires_at");
UniteFunctionsUC::validateNotEmpty($scopes, "scopes");
self::validateScopes($scopes);
$credentials = array(
"access_token" => $accessToken,
"expires_at" => $expiresAt,
"scopes" => $scopes,
);
self::mergeCredentials($credentials);
}
}

View File

@@ -0,0 +1,20 @@
<?php
require_once __DIR__ . "/helper.class.php";
require_once __DIR__ . "/client.class.php";
require_once __DIR__ . "/model.class.php";
require_once __DIR__ . "/calendar/calendar_event.class.php";
require_once __DIR__ . "/calendar/calendar_service.class.php";
require_once __DIR__ . "/places/place_review.class.php";
require_once __DIR__ . "/places/place.class.php";
require_once __DIR__ . "/places/places_services.class.php";
require_once __DIR__ . "/sheets/sheet_values.class.php";
require_once __DIR__ . "/sheets/sheet.class.php";
require_once __DIR__ . "/sheets/spreadsheet.class.php";
require_once __DIR__ . "/sheets/sheets_service.class.php";
require_once __DIR__ . "/youtube/playlist_item.class.php";
require_once __DIR__ . "/youtube/youtube_service.class.php";

View File

@@ -0,0 +1,66 @@
<?php
abstract class UEGoogleAPIModel{
private $attributes;
/**
* Create a new class instance.
*
* @param array $attributes
*
* @return void
*/
private function __construct($attributes){
$this->attributes = $attributes;
}
/**
* Transform list of items into models.
*
* @param array $items
*
* @return array
*/
public static function transformAll($items){
$data = array();
foreach($items as $attributes){
$data[] = self::transform($attributes);
}
return $data;
}
/**
* Transform attributes into a model.
*
* @param array $attributes
*
* @return static
*/
public static function transform($attributes){
$model = new static($attributes);
return $model;
}
/**
* Get the attribute value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
protected function getAttribute($key, $fallback = null){
$value = UniteFunctionsUC::getVal($this->attributes, $key, $fallback);
return $value;
}
}

View File

@@ -0,0 +1,18 @@
<?php
class UEGoogleAPIPlace extends UEGoogleAPIModel{
/**
* Get the reviews.
*
* @return UEGoogleAPIPlaceReview[]
*/
public function getReviews(){
$reviews = $this->getAttribute("reviews", array());
$reviews = UEGoogleAPIPlaceReview::transformAll($reviews);
return $reviews;
}
}

View File

@@ -0,0 +1,97 @@
<?php
class UEGoogleAPIPlaceReview extends UEGoogleAPIModel{
/**
* Get the identifier.
*
* @return int
*/
public function getId(){
$id = $this->getTime();
return $id;
}
/**
* Get the text.
*
* @param bool $asHtml
*
* @return string
*/
public function getText($asHtml = false){
$text = $this->getAttribute("text");
if($asHtml === true)
$text = nl2br($text);
return $text;
}
/**
* Get the rating.
*
* @return int
*/
public function getRating(){
$rating = $this->getAttribute("rating");
return $rating;
}
/**
* Get the date.
*
* @param string $format
*
* @return string
*/
public function getDate($format){
$time = $this->getTime();
$date = date($format, $time);
return $date;
}
/**
* Get the author name.
*
* @return string
*/
public function getAuthorName(){
$name = $this->getAttribute("author_name");
return $name;
}
/**
* Get the author photo URL.
*
* @return string|null
*/
public function getAuthorPhotoUrl(){
$url = $this->getAttribute("profile_photo_url");
return $url;
}
/**
* Get the time.
*
* @return int
*/
private function getTime(){
$time = $this->getAttribute("time");
return $time;
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* @link https://developers.google.com/maps/documentation/places/web-service/overview
*/
class UEGoogleAPIPlacesService extends UEGoogleAPIClient{
/**
* Get the place details.
*
* @param string $placeId
* @param array $params
*
* @return UEGoogleAPIPlace
*/
public function getDetails($placeId, $params = array()){
$params["place_id"] = $placeId;
$response = $this->get("/details/json", $params);
$response = UEGoogleAPIPlace::transform($response["result"]);
return $response;
}
/**
* Get the base URL for the API.
*
* @return string
*/
protected function getBaseUrl(){
return "https://maps.googleapis.com/maps/api/place";
}
}

View File

@@ -0,0 +1,45 @@
<?php
class UEGoogleAPISheet extends UEGoogleAPIModel{
/**
* Get the identifier.
*
* @return int
*/
public function getId(){
$id = $this->getPropertyValue("sheetId");
return $id;
}
/**
* Get the title.
*
* @return string
*/
public function getTitle(){
$title = $this->getPropertyValue("title");
return $title;
}
/**
* Get the property value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
private function getPropertyValue($key, $fallback = null){
$properties = $this->getAttribute("properties");
$value = UniteFunctionsUC::getVal($properties, $key, $fallback);
return $value;
}
}

View File

@@ -0,0 +1,17 @@
<?php
class UEGoogleAPISheetValues extends UEGoogleAPIModel{
/**
* Get the values.
*
* @return array
*/
public function getValues(){
$values = $this->getAttribute("values", array());
return $values;
}
}

View File

@@ -0,0 +1,181 @@
<?php
/**
* @link https://developers.google.com/sheets/api/reference/rest
*/
class UEGoogleAPISheetsService extends UEGoogleAPIClient{
/**
* Get the spreadsheet.
*
* @param string $spreadsheetId
* @param array $params
*
* @return UEGoogleAPISpreadsheet
*/
public function getSpreadsheet($spreadsheetId, $params = array()){
$response = $this->get("/$spreadsheetId", $params);
$response = UEGoogleAPISpreadsheet::transform($response);
return $response;
}
/**
* Get the spreadsheet values.
*
* @param string $spreadsheetId
* @param string $range
* @param array $params
*
* @return UEGoogleAPISheetValues
*/
public function getSpreadsheetValues($spreadsheetId, $range, $params = array()){
$range = urlencode($range);
$response = $this->get("/$spreadsheetId/values/$range", $params);
$response = UEGoogleAPISheetValues::transform($response);
return $response;
}
/**
* Batch update the spreadsheet.
*
* @param string $spreadsheetId
* @param array $requests
*
* @return void
*/
public function batchUpdateSpreadsheet($spreadsheetId, $requests){
$this->post("/$spreadsheetId:batchUpdate", array(
"requests" => $requests,
));
}
/**
* Get the insert dimension request.
*
* @param int $sheetId
* @param int $startIndex
* @param int $endIndex
*
* @return array
*/
public function getInsertDimensionRequest($sheetId, $startIndex, $endIndex){
$request = array(
"insertDimension" => array(
"range" => array(
"sheetId" => $sheetId,
"startIndex" => $startIndex,
"endIndex" => $endIndex,
"dimension" => "ROWS",
),
),
);
return $request;
}
/**
* Get the update cells request.
*
* @param int $sheetId
* @param int $startIndex
* @param int $endIndex
* @param array $rows
*
* @return array
*/
public function getUpdateCellsRequest($sheetId, $startIndex, $endIndex, $rows){
$request = array(
"updateCells" => array(
"range" => array(
"sheetId" => $sheetId,
"startRowIndex" => $startIndex,
"endRowIndex" => $endIndex,
),
"rows" => $rows,
"fields" => "*",
),
);
return $request;
}
/**
* Prepare the row data.
*
* @param array $values
*
* @return array
*/
public function prepareRowData($values){
$data = array(
"values" => $values,
);
return $data;
}
/**
* Prepare the cell data.
*
* @param mixed $value
*
* @return array
*/
public function prepareCellData($value){
if(is_numeric($value) === true)
$type = "numberValue";
elseif(is_bool($value) === true)
$type = "boolValue";
else{
$type = "stringValue";
$value = (string)$value;
}
$data = array(
"userEnteredValue" => array(
$type => $value,
),
);
return $data;
}
/**
* Apply the bold formatting for the cell.
*
* @param array $cell
*
* @return array
*/
public function applyBoldFormatting($cell){
$cell["userEnteredFormat"] = array(
"textFormat" => array(
"bold" => true,
),
);
return $cell;
}
/**
* Get the base URL for the API.
*
* @return string
*/
protected function getBaseUrl(){
return "https://sheets.googleapis.com/v4/spreadsheets";
}
}

View File

@@ -0,0 +1,30 @@
<?php
class UEGoogleAPISpreadsheet extends UEGoogleAPIModel{
/**
* Get the identifier.
*
* @return string
*/
public function getId(){
$id = $this->getAttribute("spreadsheetId");
return $id;
}
/**
* Get the sheets.
*
* @return UEGoogleAPISheet[]
*/
public function getSheets(){
$sheets = $this->getAttribute("sheets");
$sheets = UEGoogleAPISheet::transformAll($sheets);
return $sheets;
}
}

View File

@@ -0,0 +1,156 @@
<?php
class UEGoogleAPIPlaylistItem extends UEGoogleAPIModel{
const IMAGE_SIZE_DEFAULT = "default";
const IMAGE_SIZE_MEDIUM = "medium";
const IMAGE_SIZE_HIGH = "high";
const IMAGE_SIZE_MAX = "maxres";
/**
* Get the identifier.
*
* @return string
*/
public function getId(){
$id = $this->getAttribute("id");
return $id;
}
/**
* Get the title.
*
* @return string
*/
public function getTitle(){
$title = $this->getSnippetValue("title");
return $title;
}
/**
* Get the description.
*
* @param bool $asHtml
*
* @return string
*/
public function getDescription($asHtml = false){
$description = $this->getSnippetValue("description");
if($asHtml === true)
$description = nl2br($description);
return $description;
}
/**
* Get the date.
*
* @param string $format
*
* @return string
*/
public function getDate($format){
$date = $this->getSnippetValue("publishedAt");
$time = strtotime($date);
$date = date($format, $time);
return $date;
}
/**
* Get the image URL.
*
* @param string $size
*
* @return string
*/
public function getImageUrl($size){
$images = $this->getSnippetValue("thumbnails");
$image = UniteFunctionsUC::getVal($images, $size, array());
$url = UniteFunctionsUC::getVal($image, "url");
return $url;
}
/**
* Get the video identifier.
*
* @return string
*/
public function getVideoId(){
$id = $this->getDetailsValue("videoId");
return $id;
}
/**
* Get the video date.
*
* @param string $format
*
* @return string
*/
public function getVideoDate($format){
$date = $this->getDetailsValue("videoPublishedAt");
$time = strtotime($date);
$date = date($format, $time);
return $date;
}
/**
* Get the video URL.
*
* @return string
*/
public function getVideoUrl(){
$id = $this->getVideoId();
$url = "https://youtube.com/watch?v=$id";
return $url;
}
/**
* Get the snippet value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
private function getSnippetValue($key, $fallback = null){
$snippet = $this->getAttribute("snippet");
$value = UniteFunctionsUC::getVal($snippet, $key, $fallback);
return $value;
}
/**
* Get the details value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
private function getDetailsValue($key, $fallback = null){
$details = $this->getAttribute("contentDetails");
$value = UniteFunctionsUC::getVal($details, $key, $fallback);
return $value;
}
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* @link https://developers.google.com/youtube/v3/docs
*/
class UEGoogleAPIYouTubeService extends UEGoogleAPIClient{
/**
* Get the playlist items.
*
* @param string $playlistId
* @param array $params
*
* @return UEGoogleAPIPlaylistItem[]
*/
public function getPlaylistItems($playlistId, $params = array()){
$params["playlistId"] = $playlistId;
$params["part"] = "snippet,contentDetails";
$response = $this->get("/playlistItems", $params);
$response = UEGoogleAPIPlaylistItem::transformAll($response["items"]);
return $response;
}
/**
* Get the base URL for the API.
*
* @return string
*/
protected function getBaseUrl(){
return "https://www.googleapis.com/youtube/v3";
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteHelperBaseUC extends HtmlOutputBaseUC{
/**
*
* echo json ajax response
*/
public static function ajaxResponse($success,$message,$arrData = null){
$response = array();
$response["success"] = $success;
$response["message"] = $message;
if(!empty($arrData)){
if(gettype($arrData) == "string")
$arrData = array("data"=>$arrData);
$response = array_merge($response,$arrData);
}
$json = json_encode($response);
// clean the buffier,
// but return the content if exists for showing the warnings
if(ob_get_length() > 0) {
$content = ob_get_contents();
ob_end_clean();
echo $content;
}
$isJsonOutput = UniteFunctionsUC::getGetVar("json","",UniteFunctionsUC::SANITIZE_KEY);
$isJsonOutput = UniteFunctionsUC::strToBool($isJsonOutput);
if($isJsonOutput == true)
header('Content-Type: application/json');
echo UniteProviderFunctionsUC::escCombinedHtml($json);
exit();
}
/**
*
* echo json ajax response, without message, only data
*/
public static function ajaxResponseData($arrData){
if(gettype($arrData) == "string")
$arrData = array("data"=>$arrData);
self::ajaxResponse(true,"",$arrData);
}
/**
*
* echo json ajax response
*/
public static function ajaxResponseError($message,$arrData = null){
self::ajaxResponse(false,$message,$arrData,true);
}
/**
* echo ajax success response
*/
public static function ajaxResponseSuccess($message,$arrData = null){
self::ajaxResponse(true,$message,$arrData,true);
}
/**
* echo ajax success response
*/
public static function ajaxResponseSuccessRedirect($message,$url){
$arrData = array("is_redirect"=>true,"redirect_url"=>$url);
self::ajaxResponse(true,$message,$arrData,true);
}
}
?>

View File

@@ -0,0 +1,20 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class HtmlOutputBaseUC{
const BR = "\n";
const BR2 = "\n\n";
const TAB = " ";
const TAB2 = " ";
const TAB3 = " ";
const TAB4 = " ";
const TAB5 = " ";
const TAB6 = " ";
}

View File

@@ -0,0 +1,15 @@
<?php
abstract class UEHttp{
/**
* Create a new request instance.
*
* @return UEHttpRequest
*/
public static function make(){
return new UEHttpRequest();
}
}

View File

@@ -0,0 +1,7 @@
<?php
abstract class UEHttpException extends Exception{
//
}

View File

@@ -0,0 +1,32 @@
<?php
class UEHttpRequestException extends UEHttpException{
private $request;
/**
* Create a new class instance.
*
* @param string $message
* @param UEHttpRequest $request
*
* @return void
*/
public function __construct($message, $request){
$this->request = $request;
parent::__construct($message);
}
/**
* Get the request instance.
*
* @return UEHttpRequest
*/
public function getRequest(){
return $this->request;
}
}

View File

@@ -0,0 +1,32 @@
<?php
class UEHttpResponseException extends UEHttpException{
private $response;
/**
* Create a new class instance.
*
* @param string $message
* @param UEHttpResponse $response
*
* @return void
*/
public function __construct($message, $response){
$this->response = $response;
parent::__construct($message, $response->status());
}
/**
* Get the response instance.
*
* @return UEHttpResponse
*/
public function getResponse(){
return $this->response;
}
}

View File

@@ -0,0 +1,9 @@
<?php
require_once __DIR__ . "/exceptions/exception.class.php";
require_once __DIR__ . "/exceptions/request_exception.class.php";
require_once __DIR__ . "/exceptions/response_exception.class.php";
require_once __DIR__ . "/response.class.php";
require_once __DIR__ . "/request.class.php";
require_once __DIR__ . "/client.class.php";

View File

@@ -0,0 +1,357 @@
<?php
class UEHttpRequest{
const CACHE_KEY = "ue_http_request";
const BODY_FORMAT_FORM = "form";
const BODY_FORMAT_JSON = "json";
const BODY_FORMAT_MULTIPART = "multipart";
const METHOD_GET = "GET";
const METHOD_PUT = "PUT";
const METHOD_POST = "POST";
const REQUEST_TIMEOUT = 120;
private $debug = false;
private $cacheTime = 0;
private $bodyFormat;
private $headers = array();
private $query = array();
private $body = array();
private $validateResponse;
/**
* Enable the debug mode.
*
* @param bool $debug
*
* @return $this
*/
public function debug($debug = true){
$this->debug = $debug;
return $this;
}
/**
* Set the cache time.
*
* @param int $seconds
*
* @return $this
*/
public function cacheTime($seconds){
$this->cacheTime = $seconds;
return $this;
}
/**
* Indicate the request contains form parameters.
*
* @return $this
*/
public function asForm(){
return $this->bodyFormat(self::BODY_FORMAT_FORM)->contentType("application/x-www-form-urlencoded");
}
/**
* Indicate the request contains JSON.
*
* @return $this
*/
public function asJson(){
return $this->bodyFormat(self::BODY_FORMAT_JSON)->contentType("application/json");
}
/**
* Indicate the request contains multipart parameters.
*
* @return $this
*/
public function asMultipart(){
return $this->bodyFormat(self::BODY_FORMAT_MULTIPART)->contentType("multipart/form-data");
}
/**
* Indicate that JSON should be returned by the server.
*
* @return $this
*/
public function acceptJson(){
return $this->accept("application/json");
}
/**
* Add the given headers to the request.
*
* @param array $headers
*
* @return $this
*/
public function withHeaders($headers){
$this->headers = array_merge($this->headers, $headers);
return $this;
}
/**
* Add the given parameters to the request query.
*
* @param array $query
*
* @return $this
*/
public function withQuery($query){
$this->query = array_merge($this->query, $query);
return $this;
}
/**
* Add the given parameters to the request body.
*
* @param array $body
*
* @return $this
*/
public function withBody($body){
$this->body = array_merge($this->body, $body);
return $this;
}
/**
* Set the validation function of the response.
*
* @param callable $callback
*
* @return $this
*/
public function validateResponse($callback){
$this->validateResponse = $callback;
return $this;
}
/**
* Make a GET request to the server.
*
* @param string $url
* @param array $query
*
* @return UEHttpResponse
* @throws UEHttpException
*/
public function get($url, $query = array()){
return $this->withQuery($query)->request(self::METHOD_GET, $url);
}
/**
* Make a POST request to the server.
*
* @param string $url
* @param array $body
*
* @return UEHttpResponse
* @throws UEHttpException
*/
public function post($url, $body = array()){
return $this->withBody($body)->request(self::METHOD_POST, $url);
}
/**
* Make a request to the server.
*
* @param string $method
* @param string $url
*
* @return UEHttpResponse
* @throws UEHttpException
*/
public function request($method, $url){
$headers = $this->headers;
$query = $this->query;
$body = $this->prepareBody($method);
$url = $this->prepareUrl($url, $query);
if($this->isDebug() === true){
dmp("Request data:");
dmp($url);
dmp($headers);
dmp($query);
dmp($body);
}
$cacheKey = $this->prepareCacheKey($url);
$cacheTime = $this->prepareCacheTime($method);
$requestResponse = UniteProviderFunctionsUC::rememberTransient($cacheKey, $cacheTime, function() use ($url, $method, $headers, $body){
$wpResponse = wp_remote_request($url, array(
"method" => $method,
"headers" => $headers,
"body" => $body,
"timeout" => self::REQUEST_TIMEOUT,
"sslverify" => false,
));
if(is_wp_error($wpResponse) === true)
throw new UEHttpRequestException($wpResponse->get_error_message(), $this);
$requestResponse = array(
"status" => wp_remote_retrieve_response_code($wpResponse),
"headers" => wp_remote_retrieve_headers($wpResponse)->getAll(),
"body" => wp_remote_retrieve_body($wpResponse),
);
if($this->isDebug() === true){
dmp("Fetched response:");
dmp($requestResponse);
}
if(is_callable($this->validateResponse) === true){
$response = new UEHttpResponse($requestResponse);
$validResponse = call_user_func($this->validateResponse, $response);
if($validResponse === false)
throw new UEHttpResponseException("Response validation failed.", $response);
}
return $requestResponse;
});
if($this->isDebug() === true){
dmp("Cached response:");
dmp($requestResponse);
}
return new UEHttpResponse($requestResponse);
}
/**
* Determine if the debug mode is enabled.
*
* @return bool
*/
private function isDebug(){
return $this->debug === true;
}
/**
* Set the body format of the request.
*
* @param string $format
*
* @return $this
*/
private function bodyFormat($format){
$this->bodyFormat = $format;
return $this;
}
/**
* Indicate the content type that should be returned by the server.
*
* @param string $type
*
* @return $this
*/
private function accept($type){
return $this->withHeaders(["Accept" => $type]);
}
/**
* Set the content type of the request.
*
* @param string $type
*
* @return $this
*/
private function contentType($type){
return $this->withHeaders(["Content-Type" => $type]);
}
/**
* Prepare the given URL for the request.
*
* @param string $url
* @param array $query
*
* @return string
*/
private function prepareUrl($url, $query){
$url .= strpos($url, "?") === false ? "?" : "&";
$url .= http_build_query($query);
return $url;
}
/**
* Prepare the body for the request.
*
* @param string $method
*
* @return array|string|null
*/
private function prepareBody($method){
if($method === self::METHOD_GET)
return null;
switch($this->bodyFormat){
case self::BODY_FORMAT_JSON:
return json_encode($this->body);
}
return $this->body;
}
/**
* Prepare the cache key for the request.
*
* @param string $url
*
* @return string
*/
private function prepareCacheKey($url){
return self::CACHE_KEY . ":" . md5($url);
}
/**
* Prepare the cache time for the request.
*
* @param string $method
*
* @return int
*/
private function prepareCacheTime($method){
return ($method === self::METHOD_GET) ? $this->cacheTime : 0;
}
}

View File

@@ -0,0 +1,69 @@
<?php
class UEHttpResponse{
private $status;
private $headers;
private $body;
/**
* Create a new class instance.
*
* @param array $data
*
* @return void
*/
public function __construct($data){
$this->status = UniteFunctionsUC::getVal($data, "status", 0);
$this->headers = UniteFunctionsUC::getVal($data, "headers", array());
$this->body = UniteFunctionsUC::getVal($data, "body");
}
/**
* Get the status code of the response.
*
* @return int
*/
public function status(){
return $this->status;
}
/**
* Get the headers of the response.
*
* @return array
*/
public function headers(){
return $this->headers;
}
/**
* Get the raw body of the response.
*
* @return string
*/
public function body(){
return $this->body;
}
/**
* Get the JSON decoded body of the response.
*
* @return mixed
* @throws UEHttpResponseException
*/
public function json(){
$data = json_decode($this->body(), true);
if($data === null)
throw new UEHttpResponseException("Unable to parse the JSON body.", $this);
return $data;
}
}

View File

@@ -0,0 +1,598 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteImageViewUC{
private $pathCache;
private $pathImages;
private $urlImages;
private $filename = null;
private $maxWidth = null;
private $maxHeight = null;
private $type = null;
private $effect = null;
private $effect_arg1 = null;
private $effect_arg2 = null;
const EFFECT_BW = "bw";
const EFFECT_BRIGHTNESS = "bright";
const EFFECT_CONTRAST = "contrast";
const EFFECT_EDGE = "edge";
const EFFECT_EMBOSS = "emboss";
const EFFECT_BLUR = "blur";
const EFFECT_BLUR3 = "blur3";
const EFFECT_MEAN = "mean";
const EFFECT_SMOOTH = "smooth";
const EFFECT_DARK = "dark";
const TYPE_EXACT = "exact";
const TYPE_EXACT_TOP = "exacttop";
private $jpg_quality;
public function __construct(){
$this->jpg_quality = GlobalsUC::DEFAULT_JPG_QUALITY;
}
/**
*
* throw error
*/
private function throwError($message,$code=null){
UniteFunctionsUC::throwError($message,$code);
}
/**
*
* validate type
* @param unknown_type $type
*/
private function validateType($type){
switch($type){
case self::TYPE_EXACT:
case self::TYPE_EXACT_TOP:
break;
default:
$this->throwError("Wrong image type: ".$type);
break;
}
}
/**
*
* get filename for thumbnail save / retrieve
*/
private function getThumbFilename(){
$info = pathInfo($this->filename);
//add dirname as postfix (if exists)
$postfix = "";
$dirname = UniteFunctionsUC::getVal($info, "dirname");
if($dirname == ".")
$dirname = null;
if(!empty($dirname))
$postfix = str_replace("/", "-", $dirname);
$ext = $info["extension"];
$name = $info["filename"];
$width = ceil($this->maxWidth);
$height = ceil($this->maxHeight);
$thumbFilename = $name."_".$width."x".$height;
$this->type = trim($this->type);
if(!empty($this->type))
$thumbFilename .= "_" . $this->type;
if(!empty($this->effect)){
$thumbFilename .= "_e" . $this->effect;
if(!empty($this->effect_arg1)){
$thumbFilename .= "x" . $this->effect_arg1;
}
}
//add postfix
if(!empty($postfix))
$thumbFilename .= "_".$postfix;
$thumbFilename .= ".".$ext;
return($thumbFilename);
}
/**
* get thumbnail fielpath by parameters.
*/
private function getThumbFilepath(){
$filename = $this->getThumbFilename();
$filepath = $this->pathCache .$filename;
return($filepath);
}
/**
* ouptput emtpy image code
*/
private function outputEmptyImageCode(){
echo "empty image";
exit();
}
/**
* outputs image and exit
*
*/
private function outputImage($filepath){
$info = UniteFunctionsUC::getPathInfo($filepath);
$ext = $info["extension"];
$ext = strtolower($ext);
if($ext == "jpg")
$ext = "jpeg";
$numExpires = 31536000; //one year
$strExpires = @date('D, d M Y H:i:s',time()+$numExpires);
$contents = file_get_contents($filepath);
$filesize = strlen($contents);
/*header("Last-Modified: $strModified GMT");*/
header("Expires: $strExpires GMT");
header("Cache-Control: public");
header("Content-Type: image/$ext");
header("Content-Length: $filesize");
echo UniteProviderFunctionsUC::escCombinedHtml($contents);
exit();
}
//------------------------------------------------------------------------------------------
// get src image from filepath according the image type
private function getGdSrcImage($filepath,$type){
// create the image
$src_img = false;
switch($type){
case IMAGETYPE_JPEG:
$src_img = @imagecreatefromjpeg($filepath);
break;
case IMAGETYPE_PNG:
$src_img = @imagecreatefrompng($filepath);
break;
case IMAGETYPE_GIF:
$src_img = @imagecreatefromgif($filepath);
break;
case IMAGETYPE_BMP:
$src_img = @imagecreatefromwbmp($filepath);
break;
case IMAGETYPE_WEBP:
$src_img = @imagecreatefromwebp($filepath);
break;
default:
$this->throwError("wrong image format <b>$type</b> , can't resize");
break;
}
if($src_img == false){
$this->throwError("Can't resize image");
}
return($src_img);
}
//------------------------------------------------------------------------------------------
// save gd image to some filepath. return if success or not
private function saveGdImage($dst_img,$filepath,$type){
$successSaving = false;
switch($type){
case IMAGETYPE_JPEG:
$successSaving = imagejpeg($dst_img,$filepath,$this->jpg_quality);
break;
case IMAGETYPE_PNG:
$successSaving = imagepng($dst_img,$filepath);
break;
case IMAGETYPE_GIF:
$successSaving = imagegif($dst_img,$filepath);
break;
case IMAGETYPE_BMP:
$successSaving = imagewbmp($dst_img,$filepath);
break;
}
return($successSaving);
}
//------------------------------------------------------------------------------------------
// crop image to specifix height and width , and save it to new path
private function cropImageSaveNew($filepath,$filepathNew){
$imgInfo = getimagesize($filepath);
$imgType = $imgInfo[2];
$src_img = $this->getGdSrcImage($filepath,$imgType);
$width = imageSX($src_img);
$height = imageSY($src_img);
//crop the image from the top
$startx = 0;
$starty = 0;
//find precrop width and height:
$percent = $this->maxWidth / $width;
$newWidth = $this->maxWidth;
$newHeight = ceil($percent * $height);
if($this->type == "exact"){ //crop the image from the middle
$startx = 0;
$starty = ($newHeight-$this->maxHeight)/2 / $percent;
}
if($newHeight < $this->maxHeight){ //by width
$percent = $this->maxHeight / $height;
$newHeight = $this->maxHeight;
$newWidth = ceil($percent * $width);
if($this->type == "exact"){ //crop the image from the middle
$startx = ($newWidth - $this->maxWidth) /2 / $percent; //the startx is related to big image
$starty = 0;
}
}
//resize the picture:
$tmp_img = ImageCreateTrueColor($newWidth,$newHeight);
$this->handleTransparency($tmp_img,$imgType,$newWidth,$newHeight);
imagecopyresampled($tmp_img,$src_img,0,0,$startx,$starty,$newWidth,$newHeight,$width,$height);
$this->handleImageEffects($tmp_img);
//crop the picture:
$dst_img = ImageCreateTrueColor($this->maxWidth,$this->maxHeight);
$this->handleTransparency($dst_img,$imgType,$this->maxWidth,$this->maxHeight);
imagecopy($dst_img, $tmp_img, 0, 0, 0, 0, $newWidth, $newHeight);
//save the picture
$is_saved = $this->saveGdImage($dst_img,$filepathNew,$imgType);
imagedestroy($dst_img);
imagedestroy($src_img);
imagedestroy($tmp_img);
return($is_saved);
}
//------------------------------------------------------------------------------------------
// if the images are png or gif - handle image transparency
private function handleTransparency(&$dst_img,$imgType,$newWidth,$newHeight){
//handle transparency:
if($imgType == IMAGETYPE_PNG || $imgType == IMAGETYPE_GIF){
imagealphablending($dst_img, false);
imagesavealpha($dst_img,true);
$transparent = imagecolorallocatealpha($dst_img, 255, 255, 255, 127);
imagefilledrectangle($dst_img, 0, 0, $newWidth, $newHeight, $transparent);
}
}
//------------------------------------------------------------------------------------------
// handle image effects
private function handleImageEffects(&$imgHandle){
if(empty($this->effect))
return(false);
switch($this->effect){
case self::EFFECT_BW:
if(defined("IMG_FILTER_GRAYSCALE"))
imagefilter($imgHandle,IMG_FILTER_GRAYSCALE);
break;
case self::EFFECT_BRIGHTNESS:
if(defined("IMG_FILTER_BRIGHTNESS")){
if(!is_numeric($this->effect_arg1))
$this->effect_arg1 = 50; //set default value
UniteFunctionsUC::validateNumeric($this->effect_arg1,"'ea1' argument");
imagefilter($imgHandle,IMG_FILTER_BRIGHTNESS,$this->effect_arg1);
}
break;
case self::EFFECT_DARK:
if(defined("IMG_FILTER_BRIGHTNESS")){
if(!is_numeric($this->effect_arg1))
$this->effect_arg1 = -50; //set default value
UniteFunctionsUC::validateNumeric($this->effect_arg1,"'ea1' argument");
imagefilter($imgHandle,IMG_FILTER_BRIGHTNESS,$this->effect_arg1);
}
break;
case self::EFFECT_CONTRAST:
if(defined("IMG_FILTER_CONTRAST")){
if(!is_numeric($this->effect_arg1))
$this->effect_arg1 = -5; //set default value
imagefilter($imgHandle,IMG_FILTER_CONTRAST,$this->effect_arg1);
}
break;
case self::EFFECT_EDGE:
if(defined("IMG_FILTER_EDGEDETECT"))
imagefilter($imgHandle,IMG_FILTER_EDGEDETECT);
break;
case self::EFFECT_EMBOSS:
if(defined("IMG_FILTER_EMBOSS"))
imagefilter($imgHandle,IMG_FILTER_EMBOSS);
break;
case self::EFFECT_BLUR:
$this->effect_Blur($imgHandle,5);
/*
if(defined("IMG_FILTER_GAUSSIAN_BLUR"))
imagefilter($imgHandle,IMG_FILTER_GAUSSIAN_BLUR);
*/
break;
case self::EFFECT_MEAN:
if(defined("IMG_FILTER_MEAN_REMOVAL"))
imagefilter($imgHandle,IMG_FILTER_MEAN_REMOVAL);
break;
case self::EFFECT_SMOOTH:
if(defined("IMG_FILTER_SMOOTH")){
if(!is_numeric($this->effect_arg1))
$this->effect_arg1 = 15; //set default value
imagefilter($imgHandle,IMG_FILTER_SMOOTH,$this->effect_arg1);
}
break;
case self::EFFECT_BLUR3:
$this->effect_Blur($imgHandle,5);
break;
default:
$this->throwError("Effect not supported: <b>".$this->effect."</b>");
break;
}
}
private function effect_Blur(&$gdimg, $radius=0.5) {
// Taken from Torstein Hרnsi's phpUnsharpMask (see phpthumb.unsharp.php)
$radius = round(max(0, min($radius, 50)) * 2);
if (!$radius) {
return false;
}
$w = ImageSX($gdimg);
$h = ImageSY($gdimg);
if ($imgBlur = ImageCreateTrueColor($w, $h)) {
// Gaussian blur matrix:
// 1 2 1
// 2 4 2
// 1 2 1
// Move copies of the image around one pixel at the time and merge them with weight
// according to the matrix. The same matrix is simply repeated for higher radii.
for ($i = 0; $i < $radius; $i++) {
ImageCopy ($imgBlur, $gdimg, 0, 0, 1, 1, $w - 1, $h - 1); // up left
ImageCopyMerge($imgBlur, $gdimg, 1, 1, 0, 0, $w, $h, 50.00000); // down right
ImageCopyMerge($imgBlur, $gdimg, 0, 1, 1, 0, $w - 1, $h, 33.33333); // down left
ImageCopyMerge($imgBlur, $gdimg, 1, 0, 0, 1, $w, $h - 1, 25.00000); // up right
ImageCopyMerge($imgBlur, $gdimg, 0, 0, 1, 0, $w - 1, $h, 33.33333); // left
ImageCopyMerge($imgBlur, $gdimg, 1, 0, 0, 0, $w, $h, 25.00000); // right
ImageCopyMerge($imgBlur, $gdimg, 0, 0, 0, 1, $w, $h - 1, 20.00000); // up
ImageCopyMerge($imgBlur, $gdimg, 0, 1, 0, 0, $w, $h, 16.666667); // down
ImageCopyMerge($imgBlur, $gdimg, 0, 0, 0, 0, $w, $h, 50.000000); // center
ImageCopy ($gdimg, $imgBlur, 0, 0, 0, 0, $w, $h);
}
return true;
}
return false;
}
//------------------------------------------------------------------------------------------
// resize image and save it to new path
private function resizeImageSaveNew($filepath,$filepathNew){
$imgInfo = getimagesize($filepath);
$imgType = $imgInfo[2];
$src_img = $this->getGdSrcImage($filepath,$imgType);
$width = imageSX($src_img);
$height = imageSY($src_img);
$newWidth = $width;
$newHeight = $height;
//find new width
if($height > $this->maxHeight){
$procent = $this->maxHeight / $height;
$newWidth = ceil($width * $procent);
$newHeight = $this->maxHeight;
}
//if the new width is grater than max width, find new height, and remain the width.
if($newWidth > $this->maxWidth){
$procent = $this->maxWidth / $newWidth;
$newHeight = ceil($newHeight * $procent);
$newWidth = $this->maxWidth;
}
//if the image don't need to be resized, just copy it from source to destanation.
if($newWidth == $width && $newHeight == $height && empty($this->effect)){
$success = copy($filepath,$filepathNew);
if($success == false)
$this->throwError("can't copy the image from one path to another");
}
else{ //else create the resized image, and save it to new path:
$dst_img = ImageCreateTrueColor($newWidth,$newHeight);
$this->handleTransparency($dst_img,$imgType,$newWidth,$newHeight);
//copy the new resampled image:
imagecopyresampled($dst_img,$src_img,0,0,0,0,$newWidth,$newHeight,$width,$height);
$this->handleImageEffects($dst_img);
$is_saved = $this->saveGdImage($dst_img,$filepathNew,$imgType);
imagedestroy($dst_img);
}
imagedestroy($src_img);
return(true);
}
/**
*
* set image effect
*/
public function setEffect($effect,$arg1 = ""){
$this->effect = $effect;
$this->effect_arg1 = $arg1;
}
/**
*
* set jpg quality output
*/
public function setJPGQuality($quality){
$this->jpg_quality = $quality;
}
/**
* make thumbnail from the image, and save to some path
* return new path
*/
public function makeThumb($filepathImage, $pathThumbs, $maxWidth=-1, $maxHeight=-1, $type=""){
//validate input
UniteFunctionsUC::validateFilepath($filepathImage, "image not found");
UniteFunctionsUC::validateDir($pathThumbs, "Thumbs folder don't exists.");
if($type == self::TYPE_EXACT || $type == self::TYPE_EXACT_TOP){
if($maxHeight == -1)
$this->throwError("image with exact type must have height!");
if($maxWidth == -1)
$this->throwError("image with exact type must have width!");
}
//get filename
$info = UniteFunctionsUC::getPathInfo($filepathImage);
$filename = UniteFunctionsUC::getVal($info, "basename");
UniteFunctionsUC::validateNotEmpty($filename, "image filename not given");
//if gd library doesn't exists - output normal image without resizing.
if(function_exists("gd_info") == false)
$this->throwError("php must support GD Library");
if($maxWidth == -1 && $maxHeight == -1)
$this->throwError("Wrong thumb size");
if($maxWidth == -1)
$maxWidth = 1000000;
if($maxHeight == -1)
$maxHeight = 100000;
$this->filename = $filename;
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;
$this->type = $type;
$this->pathCache = $pathThumbs;
$filenameThumb = $this->getThumbFilename();
$filepathNew = $this->pathCache.$filenameThumb;
if(file_exists($filepathNew))
return($filenameThumb);
if($type == self::TYPE_EXACT || $type == self::TYPE_EXACT_TOP){
$isSaved = $this->cropImageSaveNew($filepathImage, $filepathNew);
}
else
$isSaved = $this->resizeImageSaveNew($filepathImage, $filepathNew);
if($isSaved)
return($filenameThumb);
else
return("");
}
/**
* convert png data to png
*/
public function convertPngDataToPng($strPngData){
$strPngData = str_replace("data:image/png;base64,", "", $strPngData);
$strPng = base64_decode($strPngData);
return($strPng);
}
/**
* convert png data to png
*/
public function convertJPGDataToJPG($strJpgData){
$strJpgData = str_replace("data:image/jpeg;base64,", "", $strJpgData);
$strJpg = base64_decode($strJpgData);
return($strJpg);
}
/**
* convert png to jpg
* quality from 0 - compression to 70 - quality
*/
public function png2jpg($filepathPNG, $filepathJPGOutput, $quality = 70) {
$image = imagecreatefrompng($filepathPNG);
imagejpeg($image, $filepathJPGOutput, $quality);
imagedestroy($image);
}
/**
* convert png string to jpg
*/
public function strPngToStrJpg($strPng, $quality = 70){
$image = imagecreatefromstring($strPng);
if(empty($image))
UniteFunctionsUC::throwError("can't convert image");
ob_start();
imagejpeg($image, null, $quality);
$strJpg = ob_get_contents();
ob_end_clean();
imagedestroy($image);
return($strJpg);
}
}
?>

View File

@@ -0,0 +1,53 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
$folderIncludes = dirname(__FILE__)."/";
$folderCreatorIncludes = $folderIncludes."../";
$folderProvider = $folderIncludes."../../provider/";
//include provider classes
require_once $folderIncludes . 'functions.php';
require_once $folderIncludes . 'functions.class.php';
require_once $folderIncludes . 'html_output_base.class.php';
require_once $folderProvider."include_provider.php";
require_once $folderIncludes . 'http/includes.php';
require_once $folderIncludes . 'db.class.php';
require_once $folderIncludes . 'params_manager.class.php';
require_once $folderIncludes . 'settings.class.php';
require_once $folderIncludes . 'cssparser.class.php';
require_once $folderIncludes . 'settings_advances.class.php';
require_once $folderIncludes . 'settings_output.class.php';
require_once $folderProvider . 'provider_settings_output.class.php';
require_once $folderCreatorIncludes . 'unitecreator_settings_output.class.php';
require_once $folderIncludes . 'settings_output_wide.class.php';
require_once $folderIncludes . 'settings_output_inline.class.php';
require_once $folderIncludes . 'settings_output_sidebar.class.php';
require_once $folderIncludes . 'image_proccess.class.php';
require_once $folderIncludes . 'zip.class.php';
require_once $folderIncludes . 'base_admin.class.php';
require_once $folderIncludes . 'elements_base.class.php';
require_once $folderIncludes . 'base_output.class.php';
require_once $folderIncludes . 'helper_base.class.php';
require_once $folderIncludes . 'table.class.php';
require_once $folderIncludes . 'font_manager.class.php';
require_once $folderIncludes . 'shapes.class.php';
require_once $folderIncludes . 'services.class.php';
//include composer - twig
$isTwigExists = interface_exists("Twig\\Loader\\LoaderInterface");
if($isTwigExists == false){
require $folderIncludes."../../vendor/autoload.php";
}

View File

@@ -0,0 +1,503 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class HelperInstaUC{
const RENEW_DELAY_SIX_HOURS = 21600;
const KEY_RENEW_BLOCKED = "unlimited_elements_instagram_renew_blocked";
private static $instaCheckRunOnce = false;
/**
* get instagram access data
*/
public static function getInstagramSavedAccessData(){
$settings = HelperProviderCoreUC_EL::getGeneralSettingsValues();
$arrData = array();
$arrData["access_token"] = UniteFunctionsUC::getVal($settings, "instagram_access_token");
$arrData["user_id"] = UniteFunctionsUC::getVal($settings, "instagram_user_id");
$arrData["username"] = UniteFunctionsUC::getVal($settings, "instagram_username");
$arrData["expires"] = UniteFunctionsUC::getVal($settings, "instagram_expires");
return($arrData);
}
/**
* return if access token exists in settings
*/
public static function isAccessTokenExists(){
$arrData = self::getInstagramSavedAccessData();
$token = UniteFunctionsUC::getVal($arrData, "access_token");
$isExists = !empty($token);
return($isExists);
}
/**
* redirect to general settings
*/
public static function redirectToGeneralSettings(){
$urlRedirect = HelperUC::getViewUrl(GlobalsUnlimitedElements::VIEW_SETTINGS_ELEMENTOR,"#tab=instagram");
UniteFunctionsUC::redirectToUrl($urlRedirect);
exit();
}
/**
* save connect data, from ajax function
* redirect to general settings
*/
public static function saveInstagramConnectDataAjax($data, $noUser = false, $redirect = true){
$accessToken = UniteFunctionsUC::getVal($data, "access_token");
$userID = UniteFunctionsUC::getVal($data, "user_id");
$username = UniteFunctionsUC::getVal($data, "username");
$expiresIn = UniteFunctionsUC::getVal($data, "expires");
UniteFunctionsUC::validateNumeric($expiresIn, "expires in ");
$expiresAt = time()+$expiresIn;
$expireDate = UniteFunctionsUC::timestamp2Date($expiresAt);
UniteFunctionsUC::validateNotEmpty($accessToken,"instagram access token");
if($noUser == false){
UniteFunctionsUC::validateNotEmpty($userID,"instagram user id");
UniteFunctionsUC::validateNotEmpty($userID,"instagram username");
}
$arrUpdate = array();
$arrUpdate["instagram_access_token"] = $accessToken;
$arrUpdate["instagram_expires"] = $expiresAt;
if($noUser == false){
$arrUpdate["instagram_user_id"] = $userID;
$arrUpdate["instagram_username"] = $username;
}
HelperUC::$operations->updateUnlimitedElementsGeneralSettings($arrUpdate);
if($redirect == true)
self::redirectToGeneralSettings();
}
/**
* get expires html
*/
public static function getHTMLExpires($expiresAt){
if(empty($expiresAt))
return("");
$stamp = time();
$expiresIn = $expiresAt - $stamp;
$expireDays = $expiresIn / 60 / 60 / 24;
$expireDays = ceil($expireDays);
if($expireDays < 0){
$expireDays *= -1;
$html = "<span class='unite-color-red'>".__("The token has expired ","unlimited-elements-for-elementor").$expireDays.__(" ago","unlimited-elements-for-elementor")."</span>";
}else{
$html = __("The token will expire in ","unlimited-elements-for-elementor").$expireDays .__(" days. Don't worry, it should auto renew.","unlimited-elements-for-elementor");
}
//add renew link
$htmlLink = null;
if($expireDays < 60){
$linkRenew = HelperUC::getUrlAjax("renew_instagram_access_token");
$htmlLink = HelperHtmlUC::getHtmlLink($linkRenew, "renew access token");
}
if(!empty($htmlLink))
$html .= " ".$htmlLink;
return($html);
}
/**
* put connect with instagram button to general settings
*/
public static function putConnectWithInstagramButton(){
$urlAuthorize = InstagramAPIOfficialUC::URL_AUTHORIZE;
$clientID = InstagramAPIOfficialUC::APP_CLIENT_ID;
$urlConnect = InstagramAPIOfficialUC::URL_APP_CONNECT;
$urlReturn = HelperUC::getUrlAjax("save_instagram_connect_data");
$urlReturn = UniteFunctionsUC::encodeContent($urlReturn);
$urlConnect = "{$urlAuthorize}?client_id={$clientID}&scope=user_profile,user_media&response_type=code&redirect_uri={$urlConnect}&state=$urlReturn";
$buttonText = __("Connect With Instagram", "unlimited-elements-for-elementor");
$htmlButton = HelperHtmlUC::getHtmlLink($urlConnect, "", "", "uc-button-connect-instagram");
//put access data as well
$data = self::getInstagramSavedAccessData();
$accessToken = UniteFunctionsUC::getVal($data, "access_token");
$expiresAt = UniteFunctionsUC::getVal($data, "expires");
if(!empty($accessToken)){
$username = UniteFunctionsUC::getVal($data, "username");
$expiresHTML = self::getHTMLExpires($expiresAt);
$urlTestView = HelperUC::getViewUrl("instagram-test");
$linkTest = HelperHtmlUC::getHtmlLink($urlTestView, "Test Instagram Data");
$text = __("The instagram access token are already set up", "unlimited-elements-for-elementor");
if(!empty($username))
$text .= __(" for user: ", "unlimited-elements-for-elementor")."<b>$username</b>";
?>
<div id="uc_instagram_reconnect_message" class="instagram-reconnect-message">
<?php echo $text?>
<a id="uc_button_delete_insta_data" href="javascript:void(0)" class="unite-button-secondary"> <?php _e("Clear Access Data","unlimited-elements-for-elementor")?></a>
<br>
&nbsp;<?php echo $linkTest?>
</div>
<div id="uc_instagram_connect_button_wrapper" class="uc-instagram-connect-button-wrapper" style="display:none">
<?php echo $htmlButton?>
</div>
<br>
<div class="uc-instagram-message-expire"><?php echo $expiresHTML?></div>
<?php
}else{
//put error message
if(GlobalsUnlimitedElements::$enableInstagramErrorMessage == true){
?>
<div class="instagram-error-message">
Our app is currently restricted to access the Instagram API due to recent requirements in Facebook's policies.
<br>
Our team is actively working to find solution to restore the functionality.
<br>
We appreciate your patience and understanding during this time.
</div>
<?php
}
echo $htmlButton;
}
?>
<br><br>
<?php
}
/**
* renew the access token
* redirect to settings later
*/
public static function renewAccessToken(){
$accessData = self::getInstagramSavedAccessData();
$accessToken = UniteFunctionsUC::getVal($accessData, "access_token");
if(empty($accessToken))
return(false);
//get new access token
$objAPI = new InstagramAPIOfficialUC();
$response = $objAPI->renewToken($accessToken);
$data = array();
$data["access_token"] = UniteFunctionsUC::getVal($response, "access_token");
$data["expires"] = UniteFunctionsUC::getVal($response, "expires_in");
self::saveInstagramConnectDataAjax($data, true, false);
return(true);
}
/**
* check and renew access token if needed
*/
public static function checkRenewAccessToken(){
$accessData = self::getInstagramSavedAccessData();
$accessToken = UniteFunctionsUC::getVal($accessData, "access_token");
if(empty($accessToken))
return(false);
$expires = UniteFunctionsUC::getVal($accessData, "expires");
if(empty($expires))
return(false);
if(is_numeric($expires) == false)
return(false);
//$strTime = UniteFunctionsUC::timestamp2DateTime($expires);
$currentStamp = time();
$diff = $expires - $currentStamp;
$month = 60*60*24*30;
if($diff > $month)
return(false);
$isRenewed = false;
try{
$isRenewed = self::renewAccessToken();
}catch(Exception $e){}
return($isRenewed);
}
/**
* check transient once a day
*/
public static function checkRenewAccessToken_onceInAWhile(){
if(self::$instaCheckRunOnce == true)
return(false);
self::$instaCheckRunOnce = true;
$value = UniteProviderFunctionsUC::getTransient(self::KEY_RENEW_BLOCKED);
if(!empty($value))
return(false);
UniteProviderFunctionsUC::setTransient(self::KEY_RENEW_BLOCKED, true, self::RENEW_DELAY_SIX_HOURS);
set_transient(self::KEY_RENEW_BLOCKED, true, self::RENEW_DELAY_SIX_HOURS);
$isRenewed = self::checkRenewAccessToken();
}
/**
* convert title to handle
*/
public static function convertTitleToHandle($title, $removeNonAscii = true){
$handle = strtolower($title);
$handle = str_replace(array("<22>", "<22>"), "a", $handle);
$handle = str_replace(array("<22>", "<22>"), "a", $handle);
$handle = str_replace(array("<22>", "<22>"), "o", $handle);
if($removeNonAscii == true){
// Remove any character that is not alphanumeric, white-space, or a hyphen
$handle = preg_replace("/[^a-z0-9\s\_]/i", " ", $handle);
}
// Replace multiple instances of white-space with a single space
$handle = preg_replace("/\s\s+/", " ", $handle);
// Replace all spaces with underscores
$handle = preg_replace("/\s/", "_", $handle);
// Replace multiple underscore with a single underscore
$handle = preg_replace("/\_\_+/", "_", $handle);
// Remove leading and trailing underscores
$handle = trim($handle, "_");
return($handle);
}
/**
* convert number to textual representation
*/
public static function convertNumberToText($num){
if(empty($num))
$num = 0;
$x = round($num);
$x_number_format = number_format($x);
if($x < 10000)
return($x_number_format);
$x_array = explode(',', $x_number_format);
$x_parts = array('k', 'm', 'b', 't');
$x_count_parts = count($x_array) - 1;
$x_display = $x_array[0];
$x_display .= $x_parts[$x_count_parts - 1];
return $x_display;
}
/**
* validate instagram user
*/
public static function validateInstance($user, $instance="user"){
UniteFunctionsUC::validateNotEmpty($user,"instagram $instance");
if(preg_match('/^[a-zA-Z0-9._]+$/', $user) == false)
UniteFunctionsUC::throwError("The instagram $instance is incorrect");
}
/**
* sanitize insta user
*/
public static function sanitizeUser($user){
$user = str_replace("@","",$user);
return($user);
}
/**
* sanitize insta user
*/
public static function sanitizeTag($tag){
$tag = str_replace("#","", $tag);
return($tag);
}
/**
* containing - cotnain the txtopen adn txtclose or not
*/
public static function getTextPart($contents, $txtOpen, $txtClose, $containing = false, $numTimes = 1){
$pos1 = strpos($contents,$txtOpen);
if($numTimes>1) {
for($i=1;$i<$numTimes;$i++){
$pos1 = strpos($contents,$txtOpen,$pos1+1);
}
}
if($pos1 === FALSE)
return(false);
if($containing == false)
$pos1 += strlen($txtOpen);
$pos2 = strpos($contents,$txtClose,$pos1);
if($pos2 === false)
return(false);
if($containing == true)
$pos2 += strlen($txtClose);
$trans = substr($contents,$pos1,$pos2-$pos1);
$trans = trim($trans);
return($trans);
}
/**
* convert stamp to date
*/
public static function stampToDate($stamp){
if(is_numeric($stamp) == false)
return("");
$dateText = date("d F Y, H:i", $stamp);
return($dateText);
}
/**
* get time sinse the event
*/
public static function getTimeSince($time_stamp){
$time_difference = strtotime('now') - $time_stamp;
//year
if ($time_difference >= 60 * 60 * 24 * 365.242199)
return self::get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'y');
//month
if ($time_difference >= 60 * 60 * 24 * 30.4368499)
return self::get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'mon');
//week
if ($time_difference >= 60 * 60 * 24 * 7)
return self::get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'w');
//day
if ($time_difference >= 60 * 60 * 24)
return self::get_time_ago_string($time_stamp, 60 * 60 * 24, 'd');
//hour
if($time_difference >= 60 * 60)
return self::get_time_ago_string($time_stamp, 60 * 60, 'h');
//minute
return self::get_time_ago_string($time_stamp, 60, 'min');
}
/**
* get time ago string
*/
private static function get_time_ago_string($time_stamp, $divisor, $time_unit){
$time_difference = strtotime("now") - $time_stamp;
$time_units = floor($time_difference / $divisor);
settype($time_units, 'string');
if ($time_units === '0')
return '1' . $time_unit;
return $time_units . $time_unit;
}
}

View File

@@ -0,0 +1,11 @@
<?php
$pathBase = dirname(__FILE__) . "/";
require_once $pathBase . 'instagram_api_official.class.php';
require_once $pathBase . 'obj_items.class.php';
require_once $pathBase . 'obj_item.class.php';
require_once $pathBase . 'obj_user.class.php';
require_once $pathBase . 'obj_comments.class.php';
require_once $pathBase . 'obj_comment.class.php';
require_once $pathBase . 'helper.class.php';

View File

@@ -0,0 +1,363 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class InstagramAPIOfficialUC{
const URL_REFRESH = "https://graph.instagram.com/refresh_access_token";
const URL_AUTHORIZE = "https://api.instagram.com/oauth/authorize";
const APP_CLIENT_ID = "301063367606985";
const URL_APP_CONNECT = "https://unlimited-elements.com/instagram-connect/connect.php";
private $accessToken;
private $userID;
private $limit = 30;
private $maxItems = 30;
const CACHE_RESPONSE = true;
const DEBUG_SERVER_REQUEST = false;
/**
* throw error
*/
private function throwError($message){
UniteFunctionsUC::throwError("Instagram API Error: $message");
}
/**
* call api
*/
private function serverRequest($url, $cacheSeconds = null){
$this->validateRequestCredentials($url);
$request = UEHttp::make();
$request->debug(self::DEBUG_SERVER_REQUEST);
$request->acceptJson();
$request->cacheTime($this->shouldCacheRequest() === true ? $cacheSeconds : 0);
$request->withHeaders(array(
"Accept-Charset" => "utf-8;q=0.7,*;q=0.7",
"User-Agent" => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
));
$request->validateResponse(function($response){
$data = $response->json();
if(isset($data["error"]) === true){
$message = UniteFunctionsUC::getVal($data["error"], "message");
if(GlobalsUC::$is_admin === false)
$message = null;
if(empty($message) === true)
$message = "Oops! Something went wrong, please try again later.";
$this->throwError($message);
}
});
$response = $request->get($url);
$data = $response->json();
return $data;
}
/**
* validate request credentials
*/
private function validateRequestCredentials($url){
$info = parse_url($url);
$query = UniteFunctionsUC::getVal($info, "query");
parse_str($query, $params);
if(isset($params["access_token"]) === false)
$this->throwError("Access token not found.");
}
/**
* should cache request
*/
private function shouldCacheRequest(){
if(self::CACHE_RESPONSE === false)
return false;
$withoutCache = UniteFunctionsUC::getGetVar("ucnocache", "", UniteFunctionsUC::SANITIZE_TEXT_FIELD);
$withoutCache = UniteFunctionsUC::strToBool($withoutCache);
if(UniteFunctionsWPUC::isCurrentUserHasPermissions() === false)
$withoutCache = false;
return $withoutCache === false;
}
/**
* get request url for graph api
*/
private function getUrlRequest($type, $fields){
$userID = $this->userID;
$accessToken = $this->accessToken;
$baseURL = "https://graph.instagram.com/";
switch($type){
case "user":
$urlRequest = "{$baseURL}{$userID}?fields={$fields}";
break;
case "media":
$limit = $this->limit;
$urlRequest = "{$baseURL}{$userID}/media?limit={$limit}&fields={$fields}";
break;
default:
$this->throwError("Wrong request type \"$type\".");
}
$since = "";
$urlRequest .= "&access_token={$accessToken}&since=";
return $urlRequest;
}
/**
* request new graph
*/
private function requestGraphNew($type, $fields){
$urlRequest = $this->getUrlRequest($type, $fields);
$arrData = $this->serverRequest($urlRequest);
return($arrData);
}
/**
* request for user
* Enter description here ...
*/
private function requestUser(){
$fields = array(
"id",
"media_count",
"username",
"account_type",
);
$strFields = implode(",", $fields);
$response = $this->requestGraphNew("user", $strFields);
return($response);
}
/**
* request for media
*/
private function requestMedia(){
$fields = "media_url,thumbnail_url,caption,id,media_type,timestamp,username,permalink,children{media_url,id,media_type,timestamp,permalink,thumbnail_url}";
$data = array();
$count = 2;
$urlNext = $this->getUrlRequest("media", $fields);
$arrDataCombined = array();
$maxRequest = 3;
do{
$response = $this->serverRequest($urlNext);
$data = UniteFunctionsUC::getVal($response, "data");
if(empty($data))
$data = array();
if(!empty($data))
$arrDataCombined = array_merge($arrDataCombined, $data);
$numItems = count($arrDataCombined);
if($numItems >= $this->maxItems)
return($arrDataCombined);
$paging = UniteFunctionsUC::getVal($response, "paging");
$urlNext = UniteFunctionsUC::getVal($paging, "next");
$maxRequest--;
if($maxRequest <= 0)
$urlNext = null;
if($numItems >= $this->maxItems) //for insurance
$urlNext = null;
}while(!empty($urlNext));
return($arrDataCombined);
}
/**
* init the access data
*/
private function initAccessData(){
$arrData = HelperInstaUC::getInstagramSavedAccessData();
$this->accessToken = UniteFunctionsUC::getVal($arrData, "access_token");
$this->userID = UniteFunctionsUC::getVal($arrData, "user_id");
if(empty($this->accessToken) || empty($this->userID))
UniteFunctionsUC::throwError("Wrong access data");
}
/**
* get images from user
*/
private function getUserData_new($user, $lastID = null, $userID = null){
$user = HelperInstaUC::sanitizeUser($user);
HelperInstaUC::validateInstance($user, "user");
$this->initAccessData();
$arrUserData = $this->requestUser();
$arrItemsData = $this->requestMedia();
$objItems = new InstaObjUserUCItemsUC();
$objItems->initOfficialAPI($arrItemsData, $arrUserData);
return($objItems);
}
/**
* renew the token
*/
public function renewToken($currentToken){
$request = UEHttp::make();
$request->acceptJson();
$response = $request->get(self::URL_REFRESH, array(
"grant_type" => "ig_refresh_token",
"access_token" => $currentToken,
));
$data = $response->json();
$newAccessToken = UniteFunctionsUC::getVal($data, "access_token");
if(empty($newAccessToken) === true)
$this->throwError("Unable to refresh the access token.");
return $data;
}
private function ____END_NEW_REQUEST______(){}
/**
* convert items to simple array
*/
private function convertItemsToSimpleArray($objItems, $maxItems = null){
if($maxItems !== null){
$maxItems = (int)$maxItems;
if($maxItems < 1)
$maxItems = null;
}
$arrItems = $objItems->getItems();
$arrItemsData = array();
foreach($arrItems as $index=>$item){
if($maxItems && $index >= $maxItems)
break;
$data = $item->getDataSimple();
$arrItemsData[] = $data;
}
return($arrItemsData);
}
/**
* get items data uf it's user or tag
*/
public function getItemsData($mixed, $lastID=null, $userID = null, $maxItems = null){
$type = "";
if(strpos($mixed,"@") === 0)
$type = "user";
else
if(strpos($mixed,"#") === 0)
$type = "tag";
if(empty($type)){
$type = "user";
$mixed .= "@".$mixed;
}
try{
if(empty($type))
UniteFunctionsUC::throwError("Wrong type, should be user or tag");
switch($type){
case "user":
//$objItems = $this->getUserData($mixed, $lastID, $userID);
$objItems = $this->getUserData_new($mixed, $lastID, $userID);
break;
case "tag":
$objItems = $this->getTagData($mixed, $lastID, $userID);
break;
}
$arrItems = $this->convertItemsToSimpleArray($objItems, $maxItems);
}catch(Exception $e){
throw $e;
}
//renew here
HelperInstaUC::checkRenewAccessToken_onceInAWhile();
$pageData = $objItems->getArrPageData();
$response = array();
$response["main"] = $pageData;
$response["items"] = $arrItems;
return($response);
}
}

View File

@@ -0,0 +1,113 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class InstaObjCommentUC{
public $commentID;
public $createdDateStamp;
public $createdDate;
public $text;
public $fromUser;
public $username;
/**
* print all globals variables
*/
public function printVars(){
$vars = get_object_vars($this);
dmp($vars);
exit();
}
/**
* get text
*/
public function getText(){
$this->text = UniteProviderFunctionsIG::convertEmoji($this->text);
return($this->text);
}
/**
* get username
*/
public function getUsername(){
return($this->username);
}
/**
* init comment by array
*/
public function init($comment){
//get date
$this->createdDateStamp = UniteFunctionsUC::getVal($comment, "created_time");
$this->createdDate = HelperInstaUC::stampToDate($this->createdDateStamp);
//get text
$this->text = UniteFunctionsUC::getVal($comment, "text");
//get from user
$fromUser = UniteFunctionsUC::getVal($comment, "from");
$this->fromUser = new InstaObjUserUC();
$this->fromUser->init($fromUser);
//get id
$this->commentID = UniteFunctionsUC::getVal($comment, "id");
}
/**
* init by data
*/
public function initByData($text, $username){
$this->username = $username;
$this->text = $text;
}
/**
* init by new API
*/
public function initNewAPI($data){
if(isset($data["node"]))
$data = $data["node"];
$this->commentID = UniteFunctionsUC::getVal($data, "id");
$dataUser = UniteFunctionsUC::getVal($data, "owner");
if(empty($dataUser))
$dataUser = UniteFunctionsUC::getVal($data, "user");
$this->fromUser = new InstaObjUserUC();
$this->fromUser->initByComment($dataUser);
$this->username = $dataUser["username"];
$this->text = UniteFunctionsUC::getVal($data, "text");
$this->createdDateStamp = $data["created_at"];
}
}

View File

@@ -0,0 +1,109 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
/**
* instagram comments list class
*/
class InstaObjCommentsUC{
private $arrComments = array();
/**
* get comments array
*/
public function getArrComments(){
return($this->arrComments);
}
/**
* get comments array from data
*/
private function getArrCommentsFromData($data){
$arrData = @$data["graphql"]["shortcode_media"]["edge_media_to_comment"]["edges"];
if(empty($arrData))
$arrData = @$data["edge_media_to_comment"]["edges"];
if(empty($arrData))
$arrData = @$data["media"]["comments"]["nodes"];
return($arrData);
}
/**
* get caption from data
*/
private function getCaptionFromData($data){
$caption = @$data["graphql"]["shortcode_media"]["edge_media_to_caption"]["edges"][0]["node"]["text"];
if(empty($caption))
$caption = @$data["edge_media_to_caption"]["edges"][0]["node"]["text"];
return($caption);
}
/**
* get username from data
*/
private function getUsernameFromData($data){
$username = @$data["owner"]["username"];
if(empty($username))
$username = @$data["graphql"]["shortcode_media"]["owner"]["username"];
if(!empty($username))
$username = "@".$username;
return($username);
}
/**
* init comments by data from instagram server
*/
public function initByData($data){
$arrDataComments = $this->getArrCommentsFromData($data);
//create first comment
$caption = $this->getCaptionFromData($data);
$username = $this->getUsernameFromData($data);
if(!empty($caption)){
$objComment = new InstaObjCommentUC();
$objComment->initByData($caption, $username);
$this->arrComments[] = $objComment;
}
if(empty($arrDataComments) && empty($caption))
return(false);
foreach($arrDataComments as $comment){
$objComment = new InstaObjCommentUC();
$objComment->initNewAPI($comment);
$this->arrComments[] = $objComment;
}
return($this->arrComments);
}
}

View File

@@ -0,0 +1,682 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class InstaObjItemUC{
const TYPE_VIDEO = "video";
const TYPE_IMAGE = "image";
const TYPE_ALBOM = "albom";
const IMAGE_LOW = "low_resolution";
const IMAGE_STANDARD = "standard_resolution";
const IMAGE_THUMB = "thumbnail";
const VIDEO_STANDART = "standard_resolution";
const VIDEO_LOWRES = "low_resolution";
const VIDEO_LOWBENDWIDTH = "low_bandwidth";
public $isInited = false;
private $item;
public $code;
public $locationName;
public $arrImages;
public $arrVideos;
public $urlVideo;
public $videoViews;
public $canViewComments = false;
public $numComments;
public $arrComments = array();
public $objComments;
public $urlAltMedia;
public $hasCaption = false;
public $captionText = "";
public $captionTextProcessed = null;
public $objCaption;
public $link;
public $numLikes;
public $arrLikesUsers = array();
public $createdDateStamp;
public $createdDateText;
public $type;
public $id;
public $itemUser;
public $itemUserID;
/**
* validate if the item is inited
*/
private function validateInited(){
if($this->isInited == false)
UniteFunctionsUC::throwError("The item is not inited");
}
/**
* get image standart resolution
*/
public function getImageStandart(){
$url = $this->arrImages[self::IMAGE_STANDARD]["url"];
return($url);
}
/**
* get video standart
*/
public function getVideoStandart(){
if(!isset($this->arrVideos[self::VIDEO_STANDART]))
return("");
$url = $this->arrVideos[self::VIDEO_STANDART]["url"];
return($url);
}
/**
* get link
*/
public function getLink(){
return($this->link);
}
/**
* process caption text
*/
private function processText($text){
$text = preg_replace('/#(\w+)/', '<a href="https://instagram.com/explore/tags/$1" target="_blank">#$1</a>', $text);
$text = preg_replace('/@(\w+)/', '<a href="https://instagram.com/$1" target="_blank">@$1</a>', $text);
return($text);
}
/**
* get caption text
*/
public function getCaptionText(){
if(empty($this->captionText))
return($this->captionText);
if(empty($this->captionTextProcessed))
$this->captionTextProcessed = $this->processText($this->captionText);
return($this->captionTextProcessed);
}
/**
* get num likes
*/
public function getNumLikes(){
return($this->numLikes);
}
/**
* num comments
*/
public function getNumComments(){
return($this->numComments);
}
/**
* get num comments textual
*/
public function getNumCommentsText(){
$numComments = HelperInstaUC::convertNumberToText($this->numComments);
return($numComments);
}
/**
* get num likes textual
*/
public function getNumLikesText(){
$numLikes = HelperInstaUC::convertNumberToText($this->numLikes);
return($numLikes);
}
/**
* get numer of video views text
*/
public function getNumVideoViewsText(){
$numViews = HelperInstaUC::convertNumberToText($this->videoViews);
return($numViews);
}
/**
* get comments array
*/
public function getArrComments(){
if(!empty($this->arrComments))
return($this->arrComments);
if(empty($this->objComments))
return(array());
$arrComments = $this->objComments->getArrComments();
return($arrComments);
}
/**
* get likes array
*/
public function getArrLikes(){
return($this->arrLikesUsers);
}
/**
* get url image low
*/
public function getImageLow(){
$url = $this->arrImages[self::IMAGE_LOW]["url"];
return($url);
}
/**
* get caption text
*/
public function getCaption(){
if($this->hasCaption == false)
return("");
$text = $this->captionText;
return($text);
}
/**
* get location
*/
public function getLocation(){
$location = $this->locationName;
return($location);
}
/**
* return if the item is video
*/
public function isVideo(){
if($this->type == "video")
return(true);
else
return(false);
}
/**
* get the id
*/
public function getID(){
return($this->id);
}
/**
* get the code
*/
public function getCode(){
return($this->code);
}
/**
* get time passed till now
*/
public function getTimePassedText(){
$timeSinse = HelperInstaUC::getTimeSince($this->createdDateStamp);
return($timeSinse);
}
/**
* get simple data
*/
public function getDataSimple(){
$isVideo = $this->isVideo();
$class = "";
if($isVideo == true)
$class = "uc-video-item";
$arr = array();
$arr["thumb"] = $this->getImageLow();
$arr["image"] = $this->getImageStandart();
$arr["caption"] = $this->getCaption();
$arr["num_likes"] = $this->getNumLikesText();
$arr["num_comments"] = $this->getNumCommentsText();
$arr["link"] = $this->getLink();
$arr["isvideo"] = $isVideo;
$arr["video_class"] = $class;
$arr["num_video_views"] = $this->getNumVideoViewsText();
$arr["url_video"] = $this->urlVideo;
$arr["date_stamp"] = $this->createdDateStamp;
$arr["date"] = $this->createdDateText;
$arr["time_passed"] = $this->getTimePassedText();
return($arr);
}
/**
* get item value
*/
private function getVal($field){
$value = UniteFunctionsUC::getVal($this->item, $field);
unset($this->item[$field]);
return($value);
}
/**
* parse comments
*/
private function parseComments(){
$comments = $this->getVal("comments");
$this->numComments = UniteFunctionsUC::getVal($comments, "count");
$commentsData = UniteFunctionsUC::getVal($comments, "data");
if(empty($commentsData))
return(false);
if(is_array($commentsData) == false)
return(false);
//get all comments
foreach($commentsData as $comment){
$objComment = new InstaObjCommentUC();
$objComment->init($comment);
$this->arrComments[] = $objComment;
}
}
/**
* parse likes
*/
private function parseLikes(){
$likes = $this->getVal("likes");
//get num likes
$numLikes = UniteFunctionsUC::getVal($likes, "count");
if(empty($numLikes))
$numLikes = 0;
$this->numLikes = $numLikes;
//get likes users
$likesData = UniteFunctionsUC::getVal($likes, "data");
if(empty($likesData))
return(false);
if(is_array($likesData) == false)
return(false);
foreach($likesData as $likeUser){
$user = new InstaObjUserUC();
$user->init($likeUser);
$this->arrLikesUsers[] = $user;
}
}
/**
* parse user
*/
private function parseUser(){
$user = $this->getVal("user");
if(empty($user))
return(false);
$this->itemUser = new InstaObjUserUC();
$this->itemUser->init($user);
}
/**
* parse video type
*/
private function parseVideoRelated(){
$this->videoViews = $this->getVal("video_views");
$this->arrVideos = $this->getVal("videos");
}
/**
* parse the caption
*/
private function parseCaption(){
$caption = $this->getVal("caption");
if(empty($caption))
return(false);
$this->hasCaption = true;
$this->objCaption = new InstaObjCommentUC();
$this->objCaption->init($caption);
$this->captionText = $this->objCaption->text;
}
/**
* init by api response
*/
public function init($item){
//unset some vars
unset($item["can_delete_comments"]);
$this->item = $item;
//code
$this->code = $this->getVal("code");
//location
$arrLocation = $this->getVal("location");
$this->locationName = UniteFunctionsUC::getVal($arrLocation, "name");
//get images
$this->arrImages = $this->getVal("images");
//get comments
$canViewComments = $this->getVal("can_view_comments");
$this->canViewComments = UniteFunctionsUC::strToBool($canViewComments);
if($this->canViewComments == true)
$this->parseComments();
//get alt media
$this->urlAltMedia = $this->getVal("alt_media_url");
//get caption
$this->parseCaption();
//link
$this->link = $this->getVal("link");
//likes
$this->parseLikes();
//created date
$this->createdDateStamp = $this->getVal("created_time");
$this->createdDateText = HelperInstaUC::stampToDate($this->createdDateStamp);
//get type
$this->type = $this->getVal("type");
switch($this->type){
case "image":
break;
case "video":
$this->parseVideoRelated();
break;
default:
throw new Error("Wrong item type: $this->type");
break;
}
//id
$this->id = $this->getVal("id");
//user
$this->parseUser();
if(!empty($this->item))
UniteFunctionsUC::throwError("There something else need to be parsed");
$this->isInited = true;
}
/**
* init is video
*/
private function initNew_isVideo($item){
$isVideo = UniteFunctionsUC::getVal($item, "is_video");
$isVideo = UniteFunctionsUC::strToBool($isVideo);
$mediaType = UniteFunctionsUC::getVal($item, "media_type");
if($isVideo == true){
$this->type = self::TYPE_VIDEO;
}
else{
$this->type = self::TYPE_IMAGE;
}
if($this->type != self::TYPE_VIDEO)
return(false);
if(isset($item["video_url"])){
$this->arrVideos[self::VIDEO_STANDART] = array();
$this->arrVideos[self::VIDEO_STANDART]["url"] = UniteFunctionsUC::getVal($item, "video_url");
}
$this->videoViews = UniteFunctionsUC::getVal($item, "video_view_count");
}
/**
* get link from code
*/
private function getLinkFromCode($code){
$link = "https://www.instagram.com/p/{$code}";
return($link);
}
/**
* init by new API
*/
public function initNewAPI($item){
if(isset($item["node"]))
$item = $item["node"];
$this->initNew_isVideo($item);
$this->id = UniteFunctionsUC::getVal($item, "id");
$this->code = UniteFunctionsUC::getVal($item, "code");
if(empty($this->code))
$this->code = $this->code = UniteFunctionsUC::getVal($item, "shortcode");
$commentsDisabled = UniteFunctionsUC::getVal($item, "comments_disabled");
$commentsDisabled = UniteFunctionsUC::strToBool($commentsDisabled);
$this->canViewComments = !$commentsDisabled;
$this->createdDateStamp = UniteFunctionsUC::getVal($item, "taken_at_timestamp");
if(!empty($this->createdDateStamp))
$this->createdDateText = HelperInstaUC::stampToDate($this->createdDateStamp);
$this->captionText = UniteFunctionsUC::getVal($item, "caption");
$this->captionText = trim($this->captionText);
if(!empty($this->captionText))
$this->hasCaption = true;
$this->link = $this->getLinkFromCode($this->code);
//init images
$this->arrImages = array();
$this->arrImages[self::IMAGE_LOW] = array();
$this->arrImages[self::IMAGE_STANDARD] = array();
$urlImageNormal = UniteFunctionsUC::getVal($item, "display_url");
$this->arrImages[self::IMAGE_LOW]["url"] = UniteFunctionsUC::getVal($item, "thumbnail_src");
$this->arrImages[self::IMAGE_STANDARD]["url"] = $urlImageNormal;
$arrLikes = UniteFunctionsUC::getVal($item, "edge_liked_by");
if(empty($arrLikes))
$arrLikes = UniteFunctionsUC::getVal($item, "edge_media_preview_like");
$this->numLikes = UniteFunctionsUC::getVal($arrLikes, "count");
//init owner
$ownerID = UniteFunctionsUC::getVal($item, "owner");
if(!empty($ownerID))
$this->itemUserID = $ownerID;
//get comments
$arrComments = UniteFunctionsUC::getVal($item, "comments");
if(empty($arrComments)){
$arrComments = UniteFunctionsUC::getVal($item, "edge_media_to_comment");
}
$this->numComments = UniteFunctionsUC::getVal($arrComments, "count");
$commentsNodes = UniteFunctionsUC::getVal($arrComments, "nodes");
if(empty($commentsNodes))
$commentsNodes = UniteFunctionsUC::getVal($arrComments, "edges");
if(!empty($commentsNodes)){
$this->objComments = new InstaObjCommentsUC();
$this->objComments->initByData($item);
}
$this->isInited = true;
}
/**
* init item by official API
*/
public function initOfficialAPI($item){
$mediaType = UniteFunctionsUC::getVal($item, "media_type");
switch($mediaType){
default:
case "IMAGE":
$this->type = self::TYPE_IMAGE;
break;
case "CAROUSEL_ALBUM":
$this->type = self::TYPE_ALBOM;
break;
case "VIDEO":
$this->type = self::TYPE_VIDEO;
break;
}
$urlImage = UniteFunctionsUC::getVal($item, "media_url");
if($this->type == self::TYPE_VIDEO){
$url = $this->arrVideos[self::VIDEO_STANDART]["url"] = $urlImage;
$urlImage = UniteFunctionsUC::getVal($item, "thumbnail_url");
$this->urlVideo = UniteFunctionsUC::getVal($item, "media_url");
}
$this->arrImages[self::IMAGE_LOW]["url"] = $urlImage;
$this->arrImages[self::IMAGE_STANDARD]["url"] = $urlImage;
$this->hasCaption = true;
$this->captionText = UniteFunctionsUC::getVal($item, "caption");
$this->id = UniteFunctionsUC::getVal($item, "id");
$this->link = UniteFunctionsUC::getVal($item, "permalink");
$time = UniteFunctionsUC::getVal($item, "timestamp");
$timeStamp = strtotime($time);
$this->createdDateStamp = $timeStamp;
if(!empty($this->createdDateStamp))
$this->createdDateText = HelperInstaUC::stampToDate($this->createdDateStamp);
$this->isInited = true;
}
/**
* print item data
*/
public function printData(){
$this->validateInited();
$str = "ID: {$this->id} <br> caption: $this->captionText ";
dmp($str);
dmp("---------------------");
}
}

View File

@@ -0,0 +1,429 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class InstaObjUserUCItemsUC{
protected $isInited = false;
protected $istag = false;
protected $status;
protected $totalItems;
protected $numItems;
protected $arrItems = array();
protected $isMoreAvaliable = false;
protected $lastID = null;
private $username;
private $userID;
private $objUser;
private $profileImage;
/**
* construct the class
*/
public function __construct(){
$this->objUser = new InstaObjUserUC();
}
/**
* validate inited
*/
private function validateInited(){
if($this->isInited == false)
UniteFunctionsUC::throwError("the items object not inited");
}
private function _GETTERS(){}
/**
* get items
*/
public function getItems(){
$this->validateInited();
return($this->arrItems);
}
/**
* get last ID
*/
public function getLastID(){
$this->validateInited();
return($this->lastID);
}
/**
* get user id
*/
public function getUserID(){
$this->validateInited();
return($this->userID);
}
/**
* get username text
*/
public function getUsernameText(){
$name = $this->username;
if(!empty($this->objUser))
$name = $this->objUser->name;
if(!$name)
$name = $this->username;
return($name);
}
/**
* get username
*/
public function getUsername(){
if($this->istag == false)
$username = "@".$this->username;
else
$username = "#".$this->username;
return($username);
}
/**
* get profile image
*/
public function getProfileImage(){
if(!empty($this->profileImage))
return($this->profileImage);
if(!$this->objUser)
return(false);
$profileImage = $this->objUser->urlProfileImage;
if(!$profileImage)
return(false);
return($profileImage);
}
/**
* get if more available
*/
public function getIsMoreAvaliable(){
return($this->isMoreAvaliable);
}
/**
* get link to page
*/
public function getLink(){
if($this->istag == false)
$link = "https://www.instagram.com/".$this->username;
else
$link = "https://www.instagram.com/explore/tags/".$this->username;
return($link);
}
/**
* get page data
*/
public function getArrPageData(){
$this->validateInited();
$arr = array();
$arr["name"] = $this->objUser->name;
$arr["username"] = $this->getUsername();
$arr["biography"] = $this->objUser->biography;
$arr["image_profile"] = $this->objUser->urlProfileImage;
$arr["num_followers"] = HelperInstaUC::convertNumberToText($this->objUser->numFollowedBy);
$arr["num_following"] = HelperInstaUC::convertNumberToText($this->objUser->numFollows);
$arr["num_posts"] = HelperInstaUC::convertNumberToText($this->objUser->numPosts);
$arr["url_external"] = $this->objUser->externalUrl;
$arr["link"] = $this->getLink();
return($arr);
}
private function ___________SETTERS___________(){}
/**
* parse items from api
*/
private function parseItems($items){
$this->arrItems = array();
if(empty($items))
return(false);
if(is_array($items) == false)
return(false);
foreach($items as $item){
$objItem = new InstaObjItemUC();
$objItem->init($item);
$this->arrItems[] = $objItem;
}
}
/**
* parse item new api
*/
private function parseItemsNewApi($arrNodes){
$arrItems = array();
foreach($arrNodes as $item){
$objItem = new InstaObjItemUC();
$objItem->initNewAPI($item);
$arrItems[] = $objItem;
}
$this->arrItems = $arrItems;
}
/**
* set if it's user or tag
*/
public function setIsTag(){
$this->istag = true;
}
/**
* init by api response
*/
public function init($apiResponse, $username){
$this->username = $username;
$this->status = UniteFunctionsUC::getVal($apiResponse, "status");
if($this->status != "ok"){
dmp("status not ok!!!");
dmp($apiResponse);
exit();
}
$moreAvailable = UniteFunctionsUC::getVal($apiResponse, "more_available");
$this->isMoreAvaliable = UniteFunctionsUC::strToBool($moreAvailable);
$items = UniteFunctionsUC::getVal($apiResponse, "items");
$this->parseItems($items);
$this->numItems = count($this->arrItems);
//init user
if($this->numItems == 0)
$this->objUser = null;
else{
$firstItem = $this->arrItems[0];
$this->objUser = $firstItem->itemUser;
if(!$this->objUser)
$this->objUser = null;
}
//set last ID
if($this->numItems > 0)
$this->lastID = $this->arrItems[$this->numItems-1]->getID();
$this->isInited = true;
}
/**
* init from graph ql api
*/
public function initApiGraphQL($arrItemsData, $arrUserData){
$arrData = UniteFunctionsUC::getVal($arrItemsData, "data");
if(empty($arrData))
return(null);
$arrUser = UniteFunctionsUC::getVal($arrData, "user");
if(empty($arrUser))
return(null);
$arrMedia = UniteFunctionsUC::getVal($arrUser, "edge_owner_to_timeline_media");
if(empty($arrMedia))
return(null);
$arrEdges = UniteFunctionsUC::getVal($arrMedia, "edges");
if(empty($arrEdges))
return(null);
//$keys = array_keys($arrEdges);
$this->parseItemsNewApi($arrEdges);
$this->totalItems = 0;
//init obj user
$this->userID = UniteFunctionsUC::getVal($arrUserData, "pk");
$this->username = UniteFunctionsUC::getVal($arrUserData, "username");
$this->objUser->initByNew($arrUserData);
$this->isInited = true;
}
/**
* init new API
*/
public function initNewAPI($apiResponse){
$arrInstance = null;
if(isset($apiResponse["entry_data"])){
$apiResponse = $apiResponse["entry_data"];
$apiResponse = $apiResponse["ProfilePage"][0];
}
if(isset($apiResponse["graphql"]))
$apiResponse = $apiResponse["graphql"];
if(isset($apiResponse["user"]))
$arrInstance = $apiResponse["user"];
else
if(isset($apiResponse["tag"]))
$arrInstance = $apiResponse["tag"];
//init user
if(!empty($apiResponse["user"])){
$this->userID = UniteFunctionsUC::getVal($arrInstance, "id");
$this->username = UniteFunctionsUC::getVal($arrInstance, "username");
$this->objUser->initByNew($arrInstance);
}
if(empty($arrInstance))
UniteFunctionsUC::throwError("Server error - instance items not found");
$arrTopPosts = UniteFunctionsUC::getVal($arrInstance, "top_posts");
$arrMedia = UniteFunctionsUC::getVal($arrInstance, "edge_owner_to_timeline_media");
$arrNodes = array();
if(!empty($arrTopPosts))
$arrNodes = $arrTopPosts["nodes"];
if(!empty($arrMedia)){
$arrMediaNodes = $arrMedia["edges"];
foreach($arrMediaNodes as $node)
$arrNodes[] = $node;
}
if(empty($arrNodes))
UniteFunctionsUC::throwError("No items found");
$this->parseItemsNewApi($arrNodes);
//get total items
$this->totalItems = UniteFunctionsUC::getVal($arrMedia, "count");
if(empty($this->totalItems))
$this->totalItems = 0;
$arrPageInfo = UniteFunctionsUC::getVal($arrMedia, "page_info");
$this->isMoreAvaliable = false;
if(!empty($arrPageInfo)){
$hasNext = UniteFunctionsUC::getVal($arrPageInfo, "has_next_page");
$hasNext = UniteFunctionsUC::strToBool($hasNext);
$this->isMoreAvaliable = $hasNext;
if($hasNext == true)
$this->lastID = UniteFunctionsUC::getVal($arrPageInfo, "end_cursor");
}
$this->isInited = true;
}
/**
* init from official api
*/
public function initOfficialAPI($arrItemsData, $arrUserData){
$this->userID = UniteFunctionsUC::getVal($arrUserData, "id");
$this->username = UniteFunctionsUC::getVal($arrUserData, "username");
$this->isInited = true;
$this->isMoreAvaliable = false;
if(empty($arrItemsData))
UniteFunctionsUC::throwError("No Items Found");
foreach($arrItemsData as $item){
$objItem = new InstaObjItemUC();
$objItem->initOfficialAPI($item);
$this->arrItems[] = $objItem;
}
$this->numItems = count($this->arrItems);
}
/**
* print the data
*/
public function printData(){
$this->validateInited();
dmp("num items: ".$this->numItems);
dmp("---------------");
foreach($this->arrItems as $key => $item){
dmp($key);
$item->printData();
}
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class InstaObjUserUC{
public $isInited = false;
public $username,$urlProfileImage,$id,$name,$externalUrl,$numFollows;
public $numFollowedBy, $biography, $urlProfileImageHD, $userData, $numPosts;
/**
* init user
*/
public function init($user){
if(empty($user))
return(false);
if(is_array($user) == false)
return(false);
$this->username = UniteFunctionsUC::getVal($user, "username");
$this->urlProfileImage = UniteFunctionsUC::getVal($user, "profile_picture");
$this->id = UniteFunctionsUC::getVal($user, "id");
$this->name = UniteFunctionsUC::getVal($user, "full_name");
$this->isInited = true;
}
/**
* init by new API
*/
public function initByNew($user){
$this->externalUrl = UniteFunctionsUC::getVal($user, "external_url");
$this->name = UniteFunctionsUC::getVal($user, "full_name");
$this->id = UniteFunctionsUC::getVal($user, "id");
$media = UniteFunctionsUC::getVal($user, "edge_owner_to_timeline_media");
$this->numPosts = UniteFunctionsUC::getVal($media, "count");
$arrFollows = UniteFunctionsUC::getVal($user, "edge_follow");
$this->numFollows = UniteFunctionsUC::getVal($arrFollows, "count");
$arrFollowedBy = UniteFunctionsUC::getVal($user, "edge_followed_by");
$this->numFollowedBy = UniteFunctionsUC::getVal($arrFollowedBy, "count");
$this->urlProfileImage = UniteFunctionsUC::getVal($user, "profile_pic_url");
$this->urlProfileImageHD = UniteFunctionsUC::getVal($user, "profile_pic_url_hd");
$this->biography = UniteFunctionsUC::getVal($user, "biography");
$this->username = UniteFunctionsUC::getVal($user, "username");
$this->userData = $user;
$this->isInited = true;
}
/**
* init by new API - from comment
*/
public function initByComment($user){
$this->id = UniteFunctionsUC::getVal($user, "id");
$this->urlProfileImage = UniteFunctionsUC::getVal($user, "profile_pic_url");
$this->username = UniteFunctionsUC::getVal($user, "username");
$this->isInited = true;
}
}

View File

@@ -0,0 +1,287 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteMySql{
// sqlite class constants:
const TYPE_KEY = "INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT";
const TYPE_STRING = "VARCHAR(120)";
const TYPE_NUMBER = "INTEGER";
const TYPE_TEXT = "TEXT";
const TYPE_BOOLEAN = "BOOLEAN";
//error codes:
const CODE_ZERO = 0;
const CODE_TABLE_NOT_EXISTS = 1;
private $mysql_host = "";
private $mysql_user = "";
private $mysql_pass = "";
private $mysql_database = "";
public static $handle = null;
public $lastRowID = -1;
public $lastArr = array();
private $charset = null;
function __construct(){}
/**
* connect to database
*/
public function connect($host,$user,$pass,$database){
if(!function_exists("mysqli_connect"))
throw new Exception("php mysql extension doesn't activated, please activate it in php.ini");
$this->mysql_host = $host;
$this->mysql_user = $user;
$this->mysql_pass = $pass;
$this->mysql_database = $database;
$this->getCreateDatabase();
}
/**
* set charset before connect
*/
public function setCharset($charset){
$this->charset = $charset;
}
/**
* perform multi queries
*/
public function multiQueries($query){
$result = mysqli_multi_query(self::$handle, $query);
$this->checkForErrors("Multi Query");
return $result;
}
/**
*
* throw new error
*
*/
private function throwError($message, $code=null){
if($code == null)
throw new Exception($message);
else
throw new Exception($message,$code);
}
//------------------------------------------------------------
public function confirmOutput($message=""){
return(array("success"=>true,"message"=>$message));
}
//------------------------------------------------------------
// validates if handle exists. if not - exit with error message
public function validateHandle($functionName = ""){
if(self::$handle == false){
if($functionName) $this->exitWithMessage("$functionName error - no open database");
else $this->throwError("sqlite error - no open database");
}
return($this->confirmOutput());
}
//------------------------------------------------------------
// validate table name field if empty or not exists - write error and exit.
public function validateTableName($tableName,$functionName=""){
if(trim($tableName) == ""){
if($functionName) $this->throwError("$functionName error - no table found");
else $this->throwError("sqlite error - no table found");
}
}
//------------------------------------------------------------
// validate if table is created. if not - write error message and exist
public function validateTable($tableName,$functionName){
$this->validateTableName($tableName,$functionName);
if($this->isTableExists($tableName) == false){
if($functionName) return($this->throwError("$functionName error - the table $tableName doesn't exists",self::CODE_TABLE_NOT_EXISTS));
else $this->throwError("sqlite error - the table $tableName doesn't exists",self::CODE_TABLE_NOT_EXISTS);
}
}
//------------------------------------------------------------
// valiadte fields array. if empty or the type is not array - write error message and exit.
public function validateFields($arrFields,$functionName=""){
if(gettype($arrFields)!="array") $this->throwError("createTable error - the fields array isn't array type.");
if(count($arrFields) == 0) $this->throwError("createTable error - the fields don't given.");
}
//------------------------------------------------------------
// set database file (without path)
public function setDbFile($dbFilepath){
$this->dbFilepath = $dbFilepath;
$response = $this->getCreateDatabase();
return($response);
}
//------------------------------------------------------------
public function setAbsolutePath($path){
$this->databaseAbsolutePath = $path;
$this->dbFilepath = "";
}
//------------------------------------------------------------
public function getLastRowID(){
return($this->lastRowID);
}
//------------------------------------------------------------
// return if table exists or not.
public function isTableExists($tableName){
$sql = 'select * from '.$tableName;
$numRows = mysqli_num_rows(mysqli_query(self::$handle,"SHOW TABLES LIKE '".$tableName."'"));
$this->checkForErrors("Is table exists error",$sql);
return($numRows != 0);
}
//------------------------------------------------------------
// create database. if already created - get database.
public function getCreateDatabase(){
self::$handle = @mysqli_connect($this->mysql_host, $this->mysql_user, $this->mysql_pass);
if(!self::$handle){
$errorNumber = mysqli_connect_errno();
if(!empty($errorNumber)){
$error = mysqli_connect_error();
$this->throwError($error);
}
}
mysqli_select_db(self::$handle,$this->mysql_database);
$this->checkForErrors("Mysql connect to database error");
if(!empty($this->charset))
mysqli_set_charset(self::$handle, $this->charset);
return($this->confirmOutput());
}
//------------------------------------------------------------
// validate for errors
private function checkForErrors($prefix = "",$query=""){
if(mysqli_error(self::$handle) == false)
return(false);
$message = mysqli_error(self::$handle);
if($prefix) $message = $prefix.' - '.$message;
if($query) $message .= ' query: ' . $query;
$this->throwError($message);
}
/**
* get error message
*/
public function getErrorMsg(){
return mysqli_error(self::$handle);
}
/**
* get last operation error code
*/
public function getErrorNumber(){
return mysql_errno(self::$handle);
}
/**
* execute query with some error text
*/
public function query($query,$errorText=""){
mysqli_query(self::$handle,$query);
$this->checkForErrors($errorText,$query);
return(mysqli_affected_rows(self::$handle));
}
/**
* get query array
*/
public function getQueryArr($query, $errorText){
$rs = mysqli_query(self::$handle, $query);
$this->checkForErrors($errorText, $query);
$arrRows = array();
while($row = mysqli_fetch_assoc($rs))
$arrRows[] = $row;
$this->lastArr = $arrRows;
return($arrRows);
}
/**
* get affected rows
*/
public function getAffectedRows(){
return(mysqli_affected_rows(self::$handle));
}
/**
*
* returrn last insert id.
*/
public function insertid(){
$this->lastRowID = mysqli_insert_id(self::$handle);
return($this->lastRowID);
}
//------------------------------------------------------------
//return escape database parameter string.
public function escape($str){
if(function_exists("mysqli_real_escape_string"))
return mysqli_real_escape_string(self::$handle, $str);
return $str;
}
}// Database class end.
?>

View File

@@ -0,0 +1,197 @@
<?php
class UEOpenWeatherAPIClient{
const DATA_BASE_URL = "https://api.openweathermap.org/data/3.0";
const GEO_BASE_URL = "http://api.openweathermap.org/geo/1.0";
private $apiKey;
private $cacheTime = 0; // in seconds
/**
* Create a new client instance.
*
* @param string $apiKey
*
* @return void
*/
public function __construct($apiKey){
$this->apiKey = $apiKey;
}
/**
* Set the cache time.
*
* @param int $seconds
*
* @return void
*/
public function setCacheTime($seconds){
$this->cacheTime = $seconds;
}
/**
* Get the test URL for the API key.
*
* @return string
*/
public function getApiKeyTestUrl(){
return self::DATA_BASE_URL . "/onecall?" . http_build_query(array(
// London, GB
"lat" => "51.5073219",
"lon" => "-0.1276474",
"appid" => $this->apiKey,
));
}
/**
* Get forecasts for the given location.
*
* @param string $country
* @param string $city
* @param string $units
*
* @return UEOpenWeatherAPIForecast[]
* @throws Exception
*/
public function getForecasts($country, $city, $units = UEOpenWeatherAPIForecast::UNITS_STANDARD){
$location = $this->findLocation($country, $city);
$locale = get_locale();
$locale = explode("_", $locale);
$locale = reset($locale);
$params = array(
"lat" => $location["lat"],
"lon" => $location["lon"],
"units" => $units,
"exclude" => "minutely",
"lang" => $locale,
);
$response = $this->get(self::DATA_BASE_URL . "/onecall", $params);
$params = array(
"latitude" => UniteFunctionsUC::getVal($response, "lat"),
"longitude" => UniteFunctionsUC::getVal($response, "lon"),
"timezone" => UniteFunctionsUC::getVal($response, "timezone"),
"timezone_offset" => UniteFunctionsUC::getVal($response, "timezone_offset"),
"units" => $units,
);
$current = UniteFunctionsUC::getVal($response, "current", array());
$current = UEOpenWeatherAPIForecastCurrent::transform($current, $params);
$hourly = UniteFunctionsUC::getVal($response, "hourly", array());
$hourly = UEOpenWeatherAPIForecastHourly::transformAll($hourly, $params);
$daily = UniteFunctionsUC::getVal($response, "daily", array());
$daily = UEOpenWeatherAPIForecastDaily::transformAll($daily, $params);
$alerts = UniteFunctionsUC::getVal($response, "alerts", array());
$forecast = array(
"current" => $current,
"hourly" => $hourly,
"daily" => $daily,
"alerts" => $alerts,
);
return $forecast;
}
/**
* Find a location by the given country and city.
*
* @param string $country
* @param string $city
*
* @return array
* @throws Exception
*/
private function findLocation($country, $city){
$params = array(
"q" => "$city, $country",
"limit" => 1,
);
$response = $this->get(self::GEO_BASE_URL . "/direct", $params);
$location = reset($response);
if(empty($location) === true)
throw new Exception("Location not found.");
return $location;
}
/**
* Make a GET request to the API.
*
* @param $url
* @param $params
*
* @return array
* @throws Exception
*/
private function get($url, $params = array()){
return $this->request(UEHttpRequest::METHOD_GET, $url, $params);
}
/**
* Make a request to the API.
*
* @param string $method
* @param string $url
* @param array $params
*
* @return array
* @throws Exception
*/
private function request($method, $url, $params = array()){
$params["appid"] = $this->apiKey;
$query = ($method === UEHttpRequest::METHOD_GET) ? $params : array();
$body = ($method !== UEHttpRequest::METHOD_GET) ? $params : array();
$request = UEHttp::make();
$request->asJson();
$request->acceptJson();
$request->cacheTime($this->cacheTime);
$request->withQuery($query);
$request->withBody($body);
$request->validateResponse(function($response){
$data = $response->json();
if(isset($data["cod"]) === true)
$this->throwError("{$data["message"]} ({$data["cod"]})");
});
$response = $request->request($method, $url);
$data = $response->json();
return $data;
}
/**
* Thrown an exception with the given message.
*
* @param string $message
*
* @return void
* @throws Exception
*/
private function throwError($message){
UniteFunctionsUC::throwError("OpenWeather API Error: $message");
}
}

View File

@@ -0,0 +1,545 @@
<?php
class UEOpenWeatherAPIForecast extends UEOpenWeatherAPIModel{
const UNITS_STANDARD = "standard";
const UNITS_METRIC = "metric";
const UNITS_IMPERIAL = "imperial";
/**
* Get the identifier.
*
* @return int
*/
public function getId(){
$id = $this->getTime();
return $id;
}
/**
* Get the description.
*
* @return string
*/
public function getDescription(){
$description = $this->getAttribute("summary");
return $description;
}
/**
* Get the icon name.
*
* @return string
*/
public function getIconName(){
$iconName = $this->getWeatherArrayAttribute("icon");
return $iconName;
}
/**
* get current description
*/
public function getCurrentDescription(){
$description = $this->getWeatherArrayAttribute("description");
return $description;
}
/**
* get current description
*/
public function getCurrentState(){
$state = $this->getWeatherArrayAttribute("main");
return $state;
}
/**
* Get the icon URL.
*
* @return string
*/
public function getIconUrl(){
$name = $this->getIconName();
$url = "https://openweathermap.org/img/wn/" . $name . "@2x.png";
return $url;
}
/**
* Get the pressure.
*
* @return string
*/
public function getPressure(){
$pressure = $this->getAttribute("pressure");
$pressure = sprintf(__("%s hPa", "unlimited-elements-for-elementor"), $pressure);
return $pressure;
}
/**
* Get the humidity.
*
* @return string
*/
public function getHumidity(){
$humidity = $this->getAttribute("humidity");
$humidity = $this->formatPercentage($humidity);
return $humidity;
}
/**
* Get the cloudiness.
*
* @return string
*/
public function getCloudiness(){
$cloudiness = $this->getAttribute("clouds");
$cloudiness = $this->formatPercentage($cloudiness);
return $cloudiness;
}
/**
* Get the rain.
*
* @return string
*/
public function getRain(){
$rain = $this->getAttribute("rain", 0);
$rain = $this->formatPrecipitation($rain);
return $rain;
}
/**
* Get the snow.
*
* @return string
*/
public function getSnow(){
$snow = $this->getAttribute("snow", 0);
$snow = $this->formatPrecipitation($snow);
return $snow;
}
/**
* Get the UVI.
*
* @return float
*/
public function getUvi(){
$uvi = $this->getAttribute("uvi");
return $uvi;
}
/**
* Get the minimum temperature.
*
* @return string
*/
public function getMinTemperature(){
$temperature = $this->getTemperature("min");
return $temperature;
}
/**
* Get the maximum temperature.
*
* @return string
*/
public function getMaxTemperature(){
$temperature = $this->getTemperature("max");
return $temperature;
}
/**
* Get the morning temperature.
*
* @return string
*/
public function getMorningTemperature(){
$temperature = $this->getTemperature("morn");
return $temperature;
}
/**
* Get the day temperature.
*
* @return string
*/
public function getDayTemperature(){
$temperature = $this->getTemperature("day");
return $temperature;
}
/**
* Get the evening temperature.
*
* @return string
*/
public function getEveningTemperature(){
$temperature = $this->getTemperature("eve");
return $temperature;
}
/**
* Get the night temperature.
*
* @return string
*/
public function getNightTemperature(){
$temperature = $this->getTemperature("night");
return $temperature;
}
/**
* get current temperature
*/
public function getCurrentTemperature(){
$temperature = $this->getAttributeTemperature("temp");
return ($temperature);
}
/**
* get current feels like
*/
public function getCurrentFeelsLike(){
$temperature = $this->getAttributeTemperature("feels_like");
return ($temperature);
}
/**
* Get the morning "feels like" temperature.
*
* @return string
*/
public function getMorningFeelsLike(){
$temperature = $this->getFeelsLike("morn");
return $temperature;
}
/**
* Get the day "feels like" temperature.
*
* @return string
*/
public function getDayFeelsLike(){
$temperature = $this->getFeelsLike("day");
return $temperature;
}
/**
* Get the evening "feels like" temperature.
*
* @return string
*/
public function getEveningFeelsLike(){
$temperature = $this->getFeelsLike("eve");
return $temperature;
}
/**
* Get the night "feels like" temperature.
*
* @return string
*/
public function getNightFeelsLike(){
$temperature = $this->getFeelsLike("night");
return $temperature;
}
/**
* Get the wind speed.
*
* @return string
*/
public function getWindSpeed(){
$speed = $this->getAttribute("wind_speed");
$speed = $this->formatSpeed($speed);
return $speed;
}
/**
* Get the wind degrees.
*
* @return int
*/
public function getWindDegrees(){
$degrees = $this->getAttribute("wind_deg");
return $degrees;
}
/**
* Get the wind gust.
*
* @return string
*/
public function getWindGust(){
$gust = $this->getAttribute("wind_gust");
$gust = $this->formatSpeed($gust);
return $gust;
}
/**
* Get the date.
*
* @param string $format
*
* @return string
*/
public function getDate($format){
$time = $this->getTime();
$date = $this->formatTime($time, $format);
return $date;
}
/**
* get sunrise
*/
public function getSunrise(){
$sunrise = $this->getAttribute("sunrise");
$sunrise = $this->formatTime($sunrise, "H:i");
return ($sunrise);
}
/**
* get sunrise
*/
public function getSunset(){
$sunset = $this->getAttribute("sunset");
$sunset = $this->formatTime($sunset, "H:i");
return ($sunset);
}
/**
* format hours for sunset
*/
private function formatTime($timestemp, $format){
$timezone = $this->getParameter("timezone");
$date = new DateTime();
$objTimezone = new DateTimeZone($timezone);
$date->setTimestamp($timestemp);
$date->setTimezone($objTimezone);
$hours = $date->format($format);
return ($hours);
}
/**
* Get the current description.
*
* @return string
*/
private function getWeatherArrayAttribute($key){
$weather = $this->getAttribute("weather");
$weather = UniteFunctionsUC::getVal($weather, 0, array()); // the first weather condition is primary
$value = UniteFunctionsUC::getVal($weather, $key);
return $value;
}
/**
* get temperature from numeric attribute
*/
private function getAttributeTemperature($key){
$temperature = $this->getAttribute($key);
$temperature = $this->formatTemperature($temperature);
return ($temperature);
}
/**
* Get the temperature.
*
* @param string $key
* @param mixed $fallback
*
* @return string
*/
private function getTemperature($key, $fallback = null){
$temperature = $this->getAttribute("temp");
$temperature = UniteFunctionsUC::getVal($temperature, $key, $fallback);
$temperature = $this->formatTemperature($temperature);
return $temperature;
}
/**
* Get the "feels like" temperature.
*
* @param string $key
* @param mixed $fallback
*
* @return string
*/
private function getFeelsLike($key, $fallback = null){
$temperature = $this->getAttribute("feels_like");
$temperature = UniteFunctionsUC::getVal($temperature, $key, $fallback);
$temperature = $this->formatTemperature($temperature);
return $temperature;
}
/**
* Get the time.
*
* @return int
*/
private function getTime(){
$time = $this->getAttribute("dt");
return $time;
}
/**
* Get the units.
*
* @return string
*/
private function getUnits(){
$units = $this->getParameter("units");
return $units;
}
/**
* Format the percentage.
*
* @param string $value
*
* @return string
*/
private function formatPercentage($value){
return sprintf(__("%s%%", "unlimited-elements-for-elementor"), $value);
}
/**
* Format the precipitation.
*
* @param string $value
*
* @return string
*/
private function formatPrecipitation($value){
if(is_array($value))
$value = UniteFunctionsUC::getArrFirstValue($value);
if(is_array($value))
$value = 0;
return sprintf(__("%s mm", "unlimited-elements-for-elementor"), $value);
}
/**
* Format the speed.
*
* @param string $value
*
* @return string
*/
private function formatSpeed($value){
switch($this->getUnits()){
case self::UNITS_IMPERIAL:
return sprintf(__("%s mph", "unlimited-elements-for-elementor"), $value);
default:
return sprintf(__("%s m/s", "unlimited-elements-for-elementor"), $value);
}
}
/**
* Format the temperature.
*
* @param string $value
*
* @return string
*/
private function formatTemperature($value){
if(is_numeric($value))
$value = round($value);
return sprintf(__("%s°", "unlimited-elements-for-elementor"), $value);
//switch($this->getUnits()){
// case self::UNITS_METRIC:
// return sprintf(__("%s°C", "unlimited-elements-for-elementor"), $value);
// case self::UNITS_IMPERIAL:
// return sprintf(__("%s°F", "unlimited-elements-for-elementor"), $value);
// default:
// return sprintf(__("%sK", "unlimited-elements-for-elementor"), $value);
//}
}
}

View File

@@ -0,0 +1,335 @@
<?php
abstract class UEOpenWeatherAPIForecastAbstract extends UEOpenWeatherAPIModel{
const UNITS_STANDARD = "standard";
const UNITS_METRIC = "metric";
const UNITS_IMPERIAL = "imperial";
/**
* Get the identifier.
*
* @return int
*/
public function getId(){
$id = $this->getTime();
return $id;
}
/**
* Get the date.
*
* @param string $format
*
* @return string
*/
public function getDate($format){
$time = $this->getTime();
$date = $this->formatTime($time, $format);
return $date;
}
/**
* Get the description.
*
* @return string
*/
public function getDescription(){
$description = $this->getWeather("description");
return $description;
}
/**
* Get the state.
*
* @return string
*/
public function getState(){
$state = $this->getWeather("main");
return $state;
}
/**
* Get the icon name.
*
* @return string
*/
public function getIconName(){
$name = $this->getWeather("icon");
return $name;
}
/**
* Get the icon URL.
*
* @return string
*/
public function getIconUrl(){
$name = $this->getIconName();
$url = "https://openweathermap.org/img/wn/" . $name . "@2x.png";
return $url;
}
/**
* Get the pressure.
*
* @return string
*/
public function getPressure(){
$pressure = $this->getAttribute("pressure");
$pressure = sprintf(__("%s hPa", "unlimited-elements-for-elementor"), $pressure);
return $pressure;
}
/**
* Get the humidity.
*
* @return string
*/
public function getHumidity(){
$humidity = $this->getAttribute("humidity");
$humidity = $this->formatPercentage($humidity);
return $humidity;
}
/**
* Get the cloudiness.
*
* @return string
*/
public function getCloudiness(){
$cloudiness = $this->getAttribute("clouds");
$cloudiness = $this->formatPercentage($cloudiness);
return $cloudiness;
}
/**
* Get the rain.
*
* @return string
*/
public function getRain(){
$rain = $this->getAttribute("rain", 0);
$rain = $this->formatPrecipitation($rain);
return $rain;
}
/**
* Get the snow.
*
* @return string
*/
public function getSnow(){
$snow = $this->getAttribute("snow", 0);
$snow = $this->formatPrecipitation($snow);
return $snow;
}
/**
* Get the UVI.
*
* @return float
*/
public function getUvi(){
$uvi = $this->getAttribute("uvi");
return $uvi;
}
/**
* Get the wind speed.
*
* @return string
*/
public function getWindSpeed(){
$speed = $this->getAttribute("wind_speed");
$speed = $this->formatSpeed($speed);
return $speed;
}
/**
* Get the wind degrees.
*
* @return int
*/
public function getWindDegrees(){
$degrees = $this->getAttribute("wind_deg");
return $degrees;
}
/**
* Get the wind gust.
*
* @return string
*/
public function getWindGust(){
$gust = $this->getAttribute("wind_gust");
$gust = $this->formatSpeed($gust);
return $gust;
}
/**
* Get the weather.
*
* @param string $key
* @param mixed $fallback
*
* @return string
*/
protected function getWeather($key, $fallback = null){
$weather = $this->getAttribute("weather");
$weather = UniteFunctionsUC::getVal($weather, 0, array()); // the first weather condition is primary
$value = UniteFunctionsUC::getVal($weather, $key, $fallback);
return $value;
}
/**
* Get the time.
*
* @return int
*/
protected function getTime(){
$time = $this->getAttribute("dt");
return $time;
}
/**
* Get the units.
*
* @return string
*/
protected function getUnits(){
$units = $this->getParameter("units");
return $units;
}
/**
* Format the percentage.
*
* @param string $value
*
* @return string
*/
protected function formatPercentage($value){
return sprintf(__("%s%%", "unlimited-elements-for-elementor"), $value);
}
/**
* Format the precipitation.
*
* @param string $value
*
* @return string
*/
protected function formatPrecipitation($value){
if(is_array($value))
$value = UniteFunctionsUC::getArrFirstValue($value);
if(is_array($value))
$value = 0;
return sprintf(__("%s mm", "unlimited-elements-for-elementor"), $value);
}
/**
* Format the speed.
*
* @param string $value
*
* @return string
*/
protected function formatSpeed($value){
switch($this->getUnits()){
case self::UNITS_IMPERIAL:
return sprintf(__("%s mph", "unlimited-elements-for-elementor"), $value);
default:
return sprintf(__("%s m/s", "unlimited-elements-for-elementor"), $value);
}
}
/**
* Format the temperature.
*
* @param string $value
*
* @return string
*/
protected function formatTemperature($value){
if(is_numeric($value) === true)
$value = round($value);
return sprintf(__("%s°", "unlimited-elements-for-elementor"), $value);
//switch($this->getUnits()){
// case self::UNITS_METRIC:
// return sprintf(__("%s°C", "unlimited-elements-for-elementor"), $value);
// case self::UNITS_IMPERIAL:
// return sprintf(__("%s°F", "unlimited-elements-for-elementor"), $value);
// default:
// return sprintf(__("%sK", "unlimited-elements-for-elementor"), $value);
//}
}
/**
* Format the time.
*
* @param int $timestamp
* @param string $format
*
* @return string
*/
protected function formatTime($timestamp, $format){
$timezone = $this->getParameter("timezone");
$dateTimezone = new DateTimeZone($timezone);
$date = new DateTime();
$date->setTimezone($dateTimezone);
$date->setTimestamp($timestamp);
$time = $date->format($format);
return $time;
}
}

View File

@@ -0,0 +1,7 @@
<?php
class UEOpenWeatherAPIForecastCurrent extends UEOpenWeatherAPIForecastAbstract{
use UEOpenWeatherAPIForecastHasInlineTemperature, UEOpenWeatherAPIForecastHasSunTime;
}

View File

@@ -0,0 +1,159 @@
<?php
class UEOpenWeatherAPIForecastDaily extends UEOpenWeatherAPIForecastAbstract{
use UEOpenWeatherAPIForecastHasSunTime;
/**
* Get the minimum temperature.
*
* @return string
*/
public function getMinTemperature(){
$temperature = $this->getTemperature("min");
return $temperature;
}
/**
* Get the maximum temperature.
*
* @return string
*/
public function getMaxTemperature(){
$temperature = $this->getTemperature("max");
return $temperature;
}
/**
* Get the morning temperature.
*
* @return string
*/
public function getMorningTemperature(){
$temperature = $this->getTemperature("morn");
return $temperature;
}
/**
* Get the day temperature.
*
* @return string
*/
public function getDayTemperature(){
$temperature = $this->getTemperature("day");
return $temperature;
}
/**
* Get the evening temperature.
*
* @return string
*/
public function getEveningTemperature(){
$temperature = $this->getTemperature("eve");
return $temperature;
}
/**
* Get the night temperature.
*
* @return string
*/
public function getNightTemperature(){
$temperature = $this->getTemperature("night");
return $temperature;
}
/**
* Get the morning "feels like" temperature.
*
* @return string
*/
public function getMorningFeelsLike(){
$temperature = $this->getFeelsLike("morn");
return $temperature;
}
/**
* Get the day "feels like" temperature.
*
* @return string
*/
public function getDayFeelsLike(){
$temperature = $this->getFeelsLike("day");
return $temperature;
}
/**
* Get the evening "feels like" temperature.
*
* @return string
*/
public function getEveningFeelsLike(){
$temperature = $this->getFeelsLike("eve");
return $temperature;
}
/**
* Get the night "feels like" temperature.
*
* @return string
*/
public function getNightFeelsLike(){
$temperature = $this->getFeelsLike("night");
return $temperature;
}
/**
* Get the temperature.
*
* @param string $key
*
* @return string
*/
private function getTemperature($key){
$temperature = $this->getAttribute("temp", array());
$temperature = UniteFunctionsUC::getVal($temperature, $key, 0);
$temperature = $this->formatTemperature($temperature);
return $temperature;
}
/**
* Get the "feels like" temperature.
*
* @param string $key
*
* @return string
*/
private function getFeelsLike($key){
$temperature = $this->getAttribute("feels_like", array());
$temperature = UniteFunctionsUC::getVal($temperature, $key, 0);
$temperature = $this->formatTemperature($temperature);
return $temperature;
}
}

View File

@@ -0,0 +1,40 @@
<?php
trait UEOpenWeatherAPIForecastHasInlineTemperature{
/**
* Get the temperature.
*
* @return string
*/
public function getTemperature(){
$temperature = $this->getTemperatureAttribute("temp");
return $temperature;
}
/**
* Get the "feels like" temperature.
*
* @return string
*/
public function getFeelsLike(){
$temperature = $this->getTemperatureAttribute("feels_like");
return $temperature;
}
/**
* Get the temperature attribute.
*/
private function getTemperatureAttribute($key){
$temperature = $this->getAttribute($key);
$temperature = $this->formatTemperature($temperature);
return $temperature;
}
}

View File

@@ -0,0 +1,31 @@
<?php
trait UEOpenWeatherAPIForecastHasSunTime{
/**
* Get the sunrise time.
*
* @return string
*/
public function getSunrise(){
$sunrise = $this->getAttribute("sunrise");
$sunrise = $this->formatTime($sunrise, "H:i");
return $sunrise;
}
/**
* Get the sunset time.
*
* @return string
*/
public function getSunset(){
$sunset = $this->getAttribute("sunset");
$sunset = $this->formatTime($sunset, "H:i");
return $sunset;
}
}

View File

@@ -0,0 +1,7 @@
<?php
class UEOpenWeatherAPIForecastHourly extends UEOpenWeatherAPIForecastAbstract{
use UEOpenWeatherAPIForecastHasInlineTemperature;
}

View File

@@ -0,0 +1,11 @@
<?php
require_once __DIR__ . "/model.class.php";
require_once __DIR__ . "/client.class.php";
require_once __DIR__ . "/forecast/forecast_has_inline_temperature.class.php";
require_once __DIR__ . "/forecast/forecast_has_sun_time.class.php";
require_once __DIR__ . "/forecast/forecast_abstract.class.php";
require_once __DIR__ . "/forecast/forecast_current.class.php";
require_once __DIR__ . "/forecast/forecast_daily.class.php";
require_once __DIR__ . "/forecast/forecast_hourly.class.php";

View File

@@ -0,0 +1,86 @@
<?php
abstract class UEOpenWeatherAPIModel{
private $attributes;
private $parameters;
/**
* Create a new class instance.
*
* @param array $attributes
* @param array $parameters
*
* @return void
*/
private function __construct($attributes, $parameters = array()){
$this->attributes = $attributes;
$this->parameters = $parameters;
}
/**
* Transform list of items into models.
*
* @param array $items
* @param array $parameters
*
* @return static[]
*/
public static function transformAll($items, $parameters = array()){
$data = array();
foreach($items as $attributes){
$data[] = self::transform($attributes, $parameters);
}
return $data;
}
/**
* Transform attributes into a model.
*
* @param array $attributes
* @param array $parameters
*
* @return static
*/
public static function transform($attributes, $parameters = array()){
$model = new static($attributes, $parameters);
return $model;
}
/**
* Get the attribute value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
protected function getAttribute($key, $fallback = null){
$value = UniteFunctionsUC::getVal($this->attributes, $key, $fallback);
return $value;
}
/**
* Get the parameter value.
*
* @param string $key
* @param mixed $fallback
*
* @return mixed
*/
protected function getParameter($key, $fallback = null){
$value = UniteFunctionsUC::getVal($this->parameters, $key, $fallback);
return $value;
}
}

View File

@@ -0,0 +1,109 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UEParamsManager{
/**
* Determine if the parameter passes conditions.
*
* @param array $params
* @param array $param
*
* @return bool
* @throws Exception
*/
public static function isParamPassesConditions($params, $param){
$enableCondition = UniteFunctionsUC::getVal($param, "enable_condition");
$enableCondition = UniteFunctionsUC::strToBool($enableCondition);
if($enableCondition === false)
return true;
$conditions = array(
array(
"attribute" => UniteFunctionsUC::getVal($param, "condition_attribute"),
"operator" => UniteFunctionsUC::getVal($param, "condition_operator"),
"value" => UniteFunctionsUC::getVal($param, "condition_value"),
),
array(
"attribute" => UniteFunctionsUC::getVal($param, "condition_attribute2"),
"operator" => UniteFunctionsUC::getVal($param, "condition_operator2"),
"value" => UniteFunctionsUC::getVal($param, "condition_value2"),
),
);
foreach($conditions as $condition){
$passed = self::checkCondition($params, $condition);
if($passed === false)
return false;
}
return true;
}
/**
* Find a parameter by the given name.
*
* @param array $params
* @param string $name
*
* @return array|null
*/
private static function findParamByName($params, $name){
foreach($params as $param){
$paramName = UniteFunctionsUC::getVal($param, "name");
if($paramName === $name){
return $param;
}
}
return null;
}
/**
* Check the parameter condition.
*
* @param array $params
* @param array $condition
*
* @return bool
* @throws Exception
*/
private static function checkCondition($params, $condition){
if(empty($condition["attribute"]) === true)
return true;
$conditionedParam = self::findParamByName($params, $condition["attribute"]);
if($conditionedParam === null)
return false;
if(is_array($condition["value"]) === false)
$condition["value"] = array($condition["value"]);
$conditionedValue = UniteFunctionsUC::getVal($conditionedParam, "value");
switch($condition["operator"]){
case "equal":
return in_array($conditionedValue, $condition["value"]);
case "not_equal":
return !in_array($conditionedValue, $condition["value"]);
default:
UniteFunctionsUC::throwError("Operator \"{$condition["operator"]}\" is not implemented.");
}
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
// advanced settings class. adds some advanced features
class UniteServicesUC{
/**
* include exchange rate api
*/
public function includeExchangeRateAPI(){
$pathAPI = GlobalsUC::$pathPlugin."inc_php/framework/exchangerate/includes.php";
require_once($pathAPI);
}
/**
* include google api
*/
public function includeGoogleAPI(){
$pathAPI = GlobalsUC::$pathPlugin."inc_php/framework/google/includes.php";
require_once($pathAPI);
}
/**
* include open weather api
*/
public function includeOpenWeatherAPI(){
$pathAPI = GlobalsUC::$pathPlugin."inc_php/framework/openweather/includes.php";
require_once($pathAPI);
}
/**
* include instagram api
*/
public function includeInstagramAPI(){
$pathAPI = GlobalsUC::$pathPlugin."inc_php/framework/instagram/include_insta_api.php";
require_once($pathAPI);
}
/**
* get instagram data array
*/
public function getInstagramSavedDataArray(){
$this->includeInstagramAPI();
$arrData = HelperInstaUC::getInstagramSavedAccessData();
return($arrData);
}
/**
* get instagram data
*/
public function getInstagramData($user, $maxItems = null, $isDebug = false){
$arrData = $this->getInstagramSavedDataArray();
$accessToken = UniteFunctionsUC::getVal($arrData, "access_token");
if(empty($accessToken))
UniteFunctionsUC::throwError("Please connect instagram from general settings -> instagram");
$api = new InstagramAPIOfficialUC();
$response = $api->getItemsData($user,null,null,$maxItems);
return($response);
}
}

View File

@@ -0,0 +1,329 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
// advanced settings class. adds some advanced features
class UniteSettingsAdvancedUC extends UniteSettingsUC{
const TYPE_CONTENT = "content";
/**
* add boolean true/false select with custom names
*/
public function addSelect_boolean($name,$text,$bValue=true,$firstItem="Enable",$secondItem="Disable",$arrParams=array()){
$arrItems = array($firstItem=>"true",$secondItem=>"false");
$defaultText = "true";
if($bValue == false)
$defaultText = "false";
$this->addSelect($name,$arrItems,$text,$defaultText,$arrParams);
}
/**
* add radio item boolean true / false
*/
public function addRadioBoolean($name, $text, $defaultValue = true, $trueText = "Yes", $falseText = "No", $params = array()){
$trueValue = UniteFunctionsUC::getVal($params, "true_value", true);
$falseValue = UniteFunctionsUC::getVal($params, "false_value", false);
$defaultItem = ($defaultValue === $trueValue) ? $trueValue : $falseValue;
$params["items"] = array($falseText => $falseValue, $trueText => $trueValue);
$this->add($name, $defaultItem, $text, self::TYPE_SWITCHER, $params);
}
//------------------------------------------------------------------------------
//add float select
public function addSelect_float($name,$defaultValue,$text,$arrParams=array()){
$this->addSelect($name,array("left"=>"Left","right"=>"Right"),$text,$defaultValue,$arrParams);
}
//------------------------------------------------------------------------------
//add align select
public function addSelect_alignX($name,$defaultValue,$text,$arrParams=array()){
$this->addSelect($name,array("left"=>"Left","center"=>"Center","right"=>"Right"),$text,$defaultValue,$arrParams);
}
//------------------------------------------------------------------------------
//add align select
public function addSelect_alignY($name,$defaultValue,$text,$arrParams=array()){
$this->addSelect($name,array("top"=>"Top","middle"=>"Middle","bottom"=>"Bottom"),$text,$defaultValue,$arrParams);
}
//------------------------------------------------------------------------------
//add transitions select
public function addSelect_border($name,$defaultValue,$text,$arrParams=array()){
$arrItems = array();
$arrItems["solid"] = "Solid";
$arrItems["dashed"] = "Dashed";
$arrItems["dotted"] = "Dotted";
$arrItems["double"] = "Double";
$arrItems["groove"] = "Groove";
$this->addSelect($name,$arrItems,$text,$defaultValue,$arrParams);
}
//------------------------------------------------------------------------------
//add transitions select
public function addSelect_textDecoration($name,$defaultValue,$text,$arrParams=array()){
$arrItems = array();
$arrItems["none"] = "None";
$arrItems["underline"] = "Underline";
$arrItems["overline"] = "Overline";
$arrItems["line-through"] = "Line-through";
$this->addSelect($name,$arrItems,$text,$defaultValue,$arrParams);
}
//------------------------------------------------------------------------------
//add transitions select - arrExtensions may be string, and lower case
public function addSelect_filescan($name,$path,$arrExtensions,$defaultValue,$text,$arrParams=array()){
if(getType($arrExtensions) == "string")
$arrExtensions = array($arrExtensions);
elseif(getType($arrExtensions) != "array")
$this->throwError("The extensions array is not array and not string in setting: $name, please check.");
//make items array
if(!is_dir($path))
$this->throwError("path: $path not found");
$arrItems = array();
$files = scandir($path);
foreach($files as $file){
//general filter
if($file == ".." || $file == "." || $file == ".svn")
continue;
$info = pathinfo($file);
$ext = UniteFunctionsUC::getVal($info,"extension");
$ext = strtolower($ext);
if(array_search($ext,$arrExtensions) === FALSE)
continue;
$arrItems[$file] = $file;
}
//handle add data array
if(isset($arrParams["addData"])){
foreach($arrParams["addData"] as $key=>$value)
$arrItems[$key] = $value;
}
if(empty($defaultValue) && !empty($arrItems))
$defaultValue = current($arrItems);
$this->addSelect($name,$arrItems,$text,$defaultValue,$arrParams);
}
/**
* get transitions array
*/
private function getArrEasing(){
$arrItems = array();
$arrItems["linear"] = "Linear";
$arrItems["swing"] = "Swing";
$arrItems["easeOutQuad"] = "EaseOut - Quad";
$arrItems["easeOutQuint"] = "EaseOut - Quint";
$arrItems["easeOutBounce"] = "EaseOut - Bounce";
$arrItems["easeOutElastic"] = "EaseOut - Elastic";
$arrItems["easeOutBack"] = "EaseOut - Back";
$arrItems["easeOutQuart"] = "EaseOut - Quart";
$arrItems["easeOutExpo"] = "EaseOut - Expo";
$arrItems["easeOutCubic"] = "EaseOut - Cubic";
$arrItems["easeOutSine"] = "EaseOut - Sine";
$arrItems["easeOutCirc"] = "EaseOut - Circ";
$arrItems["easeInQuad"] = "EaseIn - Quad";
$arrItems["easeInQuint"] = "EaseIn - Quint";
$arrItems["easeInBounce"] = "EaseIn - Bounce";
$arrItems["easeInElastic"] = "EaseIn - Elastic";
$arrItems["easeInBack"] = "EaseIn - Back";
$arrItems["easeInQuart"] = "EaseIn - Quart";
$arrItems["easeInExpo"] = "EaseIn - Expo";
$arrItems["easeInCubic"] = "EaseIn - Cubic";
$arrItems["easeInSine"] = "EaseIn - Sine";
$arrItems["easeInCirc"] = "EaseIn - Circ";
$arrItems["easeInOutQuad"] = "EaseInOut - Quad";
$arrItems["easeInQuint"] = "EaseInOut - Quint";
$arrItems["easeInOutBounce"] = "EaseInOut - Bounce";
$arrItems["easeInOutElastic"] = "EaseInOut - Elastic";
$arrItems["easeInOutBack"] = "EaseInOut - Back";
$arrItems["easeInOutQuart"] = "EaseInOut - Quart";
$arrItems["easeInOutExpo"] = "EaseInOut - Expo";
$arrItems["easeInOutCubic"] = "EaseInOut - Cubic";
$arrItems["easeInOutSine"] = "EaseInOut - Sine";
$arrItems["easeInOutCirc"] = "EaseInOut - Circ";
return($arrItems);
}
/**
* add transitions array item to some select
*/
public function updateSelectToEasing($name){
$arrItems = $this->getArrEasing();
$this->updateSettingItems($name, $arrItems);
}
/**
* add transitions array item to some select
*/
public function updateSelectToAlignHor($name, $default = null){
$arrItems = array(
"left"=>__("Left","unlimited-elements-for-elementor"),
"center"=>__("Center", "unlimited-elements-for-elementor"),
"right"=>__("Right", "unlimited-elements-for-elementor")
);
$this->updateSettingItems($name, $arrItems, $default);
}
/**
* add transitions array item to some select
*/
public function updateSelectToAlignVert($name, $default = null){
$arrItems = array(
"top"=>__("Top","unlimited-elements-for-elementor"),
"middle"=>__("Middle", "unlimited-elements-for-elementor"),
"bottom"=>__("Bottom", "unlimited-elements-for-elementor")
);
$this->updateSettingItems($name, $arrItems, $default);
}
/**
* add transitions array item to some select
*/
public function updateSelectToAlignCombo($name, $default = null){
$arrItems = array(
"left"=>__("Left","unlimited-elements-for-elementor"),
"center"=>__("Center", "unlimited-elements-for-elementor"),
"right"=>__("Right", "unlimited-elements-for-elementor"),
"top"=>__("Top","unlimited-elements-for-elementor"),
"middle"=>__("Middle", "unlimited-elements-for-elementor"),
"bottom"=>__("Bottom", "unlimited-elements-for-elementor")
);
$this->updateSettingItems($name, $arrItems, $default);
}
private function a_CONTNET_SELECTOR(){}
/**
* add content selector fields, function for override
*/
protected function addContentSelectorField($option, $name, $arrDefaultValues){
dmp("addContentSelectorFields: function for override");
exit();
}
/**
* add content selector options
*/
protected function addContentSelectorOptions($arrOptions, $name){
dmp("addContentSelectorFields: function for override");
exit();
}
/**
* add post picker
*/
public function addContentSelector($name, $defaultValue = "",$text = "",$arrParams = array()){
if(empty($defaultValue))
$defaultValue = "custom";
//$this->add($name, $defaultValue, $text, self::TYPE_CONTENT, $arrParams);
$arrOptions = array();
$arrOptions["Custom"] = "custom";
$arrOptions = $this->addContentSelectorOptions($arrOptions, $name);
$radioValue = "custom";
if(is_array($defaultValue))
$radioValue = UniteFunctionsUC::getVal($defaultValue, $name);
$this->addRadio($name, $arrOptions, "<b>".$text."<b>", $radioValue);
//add fields
foreach($arrOptions as $text=>$option){
$this->startBulkControl($name, self::CONTROL_TYPE_SHOW, $option);
switch($option){
case "custom":
/*
$params = array(
UniteSettingsUC::PARAM_CLASSADD=>"unite-content-title");
$this->addTextBox($name."_title", "", __("&nbsp;Title","unlimited-elements-for-elementor"), $params);
$params = array(
UniteSettingsUC::PARAM_CLASSADD=>"unite-content-intro");
$this->addTextArea($name."_intro", "", __("&nbsp;Custom Intro","unlimited-elements-for-elementor"), $params);
*/
$params = array(
UniteSettingsUC::PARAM_CLASSADD=>"unite-content-content");
if(is_string($defaultValue))
$value = $defaultValue;
else
$value = UniteFunctionsUC::getVal($defaultValue, $name."_content");
$this->addEditor($name."_content", $value, __("&nbsp;Custom Content","unlimited-elements-for-elementor"), $params);
/*
$params = array(
UniteSettingsUC::PARAM_CLASSADD=>"unite-content-link");
$this->addTextBox($name."_link", "", __("&nbsp;Link","unlimited-elements-for-elementor"), $params);
*/
break;
default:
$this->addContentSelectorField($option, $name, $defaultValue);
break;
}
$this->endBulkControl();
}
}
}
?>

View File

@@ -0,0 +1,83 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteSettingsOutputInlineUC extends UniteCreatorSettingsOutput{
/**
* constuct function
*/
public function __construct(){
$this->isParent = true;
self::$serial++;
$this->wrapperID = "unite_settings_wide_output_".self::$serial;
$this->settingsMainClass = "unite-settings-inline";
$this->showDescAsTips = true;
}
/**
* draw settings row
* @param $setting
*/
protected function drawSettingRow($setting, $mode=""){
//set cellstyle:
$cellStyle = "";
if(isset($setting[UniteSettingsUC::PARAM_CELLSTYLE])){
$cellStyle .= $setting[UniteSettingsUC::PARAM_CELLSTYLE];
}
if($cellStyle != "")
$cellStyle = "style='".$cellStyle."'";
$textStyle = $this->drawSettingRow_getTextStyle($setting);
$rowClass = $this->drawSettingRow_getRowClass($setting, "unite-setting-row");
$text = $this->drawSettingRow_getText($setting);
$description = UniteFunctionsUC::getVal($setting,"description");
$addField = UniteFunctionsUC::getVal($setting, UniteSettingsUC::PARAM_ADDFIELD);
?>
<div id="<?php echo esc_attr($setting["id_row"])?>" <?php echo UniteProviderFunctionsUC::escAddParam($rowClass)?>>
<div class="unite-setting-text" <?php echo UniteProviderFunctionsUC::escAddParam($textStyle)?> >
<?php if($this->showDescAsTips == true): ?>
<span class='setting_text' title="<?php echo esc_attr($description)?>"><?php echo $text?></span>
<?php else:?>
<?php echo $text?>
<?php endif?>
</div>
<div class="unite-setting-content" <?php echo UniteProviderFunctionsUC::escAddParam($cellStyle)?>>
<?php
$this->drawInputs($setting);
$this->drawInputAdditions($setting);
?>
</div>
</div>
<?php
}
/**
* draw wrapper end after settings
*/
protected function drawSettingsAfter(){
?><div class="unite-clear"></div><?php
}
}
?>

View File

@@ -0,0 +1,319 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteSettingsOutputSidebarUC extends UniteCreatorSettingsOutput{
private $showSapTitle = true;
private $isAccordion = true;
private $accordionItemsSpaceBetween = 0;//space between accordion items
/**
* constuct function
*/
public function __construct(){
self::$serial++;
$this->isSidebar = true;
$this->isParent = true;
$this->wrapperID = "unite_settings_sidebar_output_" . self::$serial;
$this->settingsMainClass = "unite-settings-sidebar";
$this->showDescAsTips = false;
$this->setShowSaps(true, self::SAPS_TYPE_ACCORDION);
}
/**
* draw before settings row
*/
protected function drawSettings_before(){
parent::drawSettings_before();
?>
<ul class="unite-list-settings">
<?php
}
/**
* draw wrapper end after settings
*/
protected function drawSettingsAfter(){
?>
</ul>
<?php
parent::drawSettingsAfter();
}
/**
* get options override (add accordion space)
*/
protected function getOptions(){
$arrOptions = parent::getOptions();
$arrOptions["accordion_sap"] = $this->accordionItemsSpaceBetween;
return $arrOptions;
}
/**
* set draw options before draw
*/
protected function setDrawOptions(){
$numSaps = $this->settings->getNumSaps();
if($numSaps <= 1)
$this->showSapTitle = false;
}
/**
* draw responsive picker
*/
private function drawResponsivePicker($selectedType){
$devices = array(
"desktop" => array(
"title" => __("Desktop", "unlimited-elements-for-elementor"),
"icon" => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 10"><path d="M3.5 10.5h5M6 7.5v3M11.5.5H.5v7h11v-7Z" /></svg>',
),
"tablet" => array(
"title" => __("Tablet", "unlimited-elements-for-elementor"),
"icon" => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 12"><path d="M2.5 9.5h5M8.5.5h-7a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1Z" /></svg>',
),
"mobile" => array(
"title" => __("Mobile", "unlimited-elements-for-elementor"),
"icon" => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 12"><path d="M2.5 9.5h3M6.5.5h-5a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1Z" /></svg>',
),
);
?>
<select class="unite-responsive-picker">
<?php foreach($devices as $type => $device): ?>
<option
value="<?php esc_attr_e($type); ?>"
data-content="<?php esc_attr_e('<div class="unite-responsive-picker-item uc-tip" title="' . esc_attr($device["title"]) . '" data-tipsy-gravity="w">' . $device["icon"] . '</div>'); ?>"
<?php echo $type === $selectedType ? "selected" : ""; ?>
>
<?php esc_html_e($device["title"]); ?>
</option>
<?php endforeach; ?>
</select>
<?php
}
/**
* draw settings row
*/
protected function drawSettingRow($setting, $mode = ""){
$addAttr = "";
$baseClass = "unite-setting-row";
$id = UniteFunctionsUC::getVal($setting, "id");
$type = UniteFunctionsUC::getVal($setting, "type");
$text = UniteFunctionsUC::getVal($setting, "text");
$description = UniteFunctionsUC::getVal($setting, "description");
$toDrawText = true;
$attribsText = UniteFunctionsUC::getVal($setting, "attrib_text");
if(empty($attribsText) && empty($text))
$toDrawText = false;
$labelBlock = UniteFunctionsUC::getVal($setting, "label_block");
$labelBlock = UniteFunctionsUC::strToBool($labelBlock);
if($labelBlock === false)
$baseClass .= " unite-inline-setting";
$isResponsive = UniteFunctionsUC::getVal($setting, "is_responsive");
$isResponsive = UniteFunctionsUC::strToBool($isResponsive);
$responsiveId = UniteFunctionsUC::getVal($setting, "responsive_id");
$responsiveType = UniteFunctionsUC::getVal($setting, "responsive_type");
if($isResponsive === true)
$addAttr .= " data-responsive-id=\"$responsiveId\" data-responsive-type=\"$responsiveType\"";
$tabsId = UniteFunctionsUC::getVal($setting, "tabs_id");
$tabsValue = UniteFunctionsUC::getVal($setting, "tabs_value");
if (empty($tabsId) === false && empty($tabsValue) === false)
$addAttr .= " data-tabs-id=\"$tabsId\" data-tabs-value=\"$tabsValue\"";
$rowClass = $this->drawSettingRow_getRowClass($setting, $baseClass);
?>
<li
id="<?php esc_attr_e($id); ?>_row"
<?php echo UniteProviderFunctionsUC::escAddParam($rowClass); ?>
<?php echo UniteProviderFunctionsUC::escAddParam($addAttr); ?>
data-type="<?php esc_attr_e($type); ?>"
>
<div class="unite-setting-field">
<?php if($toDrawText === true): ?>
<div class="unite-setting-text-wrapper">
<div id="<?php echo esc_attr($id); ?>_text" class='unite-setting-text' <?php echo UniteProviderFunctionsUC::escAddParam($attribsText); ?>>
<?php echo esc_html($text); ?>
</div>
<?php if($isResponsive === true): ?>
<?php $this->drawResponsivePicker($responsiveType); ?>
<?php endif; ?>
</div>
<?php endif ?>
<?php if(!empty($addHtmlBefore)): ?>
<div class="unite-setting-addhtmlbefore"><?php echo UniteProviderFunctionsUC::escAddParam($addHtmlBefore); ?></div>
<?php endif; ?>
<div class="unite-setting-input">
<?php $this->drawInputs($setting); ?>
</div>
</div>
<?php if(!empty($description)): ?>
<div class="unite-setting-helper">
<?php echo $description; ?>
</div>
<?php endif; ?>
</li>
<?php
}
/**
* draw text row
*/
protected function drawTextRow($setting){
$id = UniteFunctionsUC::getVal($setting, "id");
$label = UniteFunctionsUC::getVal($setting, "label");
$text = UniteFunctionsUC::getVal($setting, "text");
$classAdd = UniteFunctionsUC::getVal($setting, UniteSettingsUC::PARAM_CLASSADD);
$isHeading = UniteFunctionsUC::getVal($setting, "is_heading");
$isHeading = UniteFunctionsUC::strToBool($isHeading);
if($isHeading === true)
$classAdd .= " unite-settings-static-text__heading";
$rowClass = $this->drawSettingRow_getRowClass($setting);
?>
<li id="<?php esc_attr_e($id) ?>_row" <?php echo UniteProviderFunctionsUC::escAddParam($rowClass); ?>>
<?php if(empty($label) === false): ?>
<span class="unite-settings-text-label">
<?php esc_html_e($label) ?>
</span>
<?php endif ?>
<span class="unite-settings-static-text<?php esc_attr_e($classAdd); ?>">
<?php esc_html_e($text); ?>
</span>
</li>
<?php
}
/**
* draw sap before override
*/
protected function drawSapBefore($sap, $key){
$tab = UniteFunctionsUC::getVal($sap, "tab");
$name = UniteFunctionsUC::getVal($sap, "name");
$text = UniteFunctionsUC::getVal($sap, "text");
//$classIcon = UniteFunctionsUC::getVal($sap, "icon");
$classIcon = null; // disable icon for now
$isHidden = UniteFunctionsUC::getVal($sap, "hidden");
$isHidden = UniteFunctionsUC::strToBool($isHidden);
if(empty($tab) === true)
$tab = UniteSettingsUC::TAB_CONTENT;
if(empty($name) === true)
$name = "unnamed_" . UniteFunctionsUC::getRandomString();
$class = "unite-postbox";
if(empty($this->addClass) === false)
$class .= " " . $this->addClass;
if($this->isAccordion === false)
$class .= " unite-no-accordion";
if($isHidden === true)
$class .= " unite-setting-hidden";
$id = $this->idPrefix . "ucsap_" . $name;
?>
<div
id="<?php esc_attr_e($id) ?>"
class="<?php esc_attr_e($class); ?>"
data-tab="<?php esc_attr_e($tab); ?>"
>
<?php if($this->showSapTitle === true): ?>
<div class="unite-postbox-title">
<?php if(empty($classIcon) === false): ?>
<i class="unite-postbox-icon <?php esc_attr_e($classIcon); ?>"></i>
<?php endif; ?>
<span><?php esc_html_e($text); ?></span>
<?php if($this->isAccordion === true): ?>
<div class="unite-postbox-arrow"></div>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="unite-postbox-inside">
<?php
}
/**
* draw sap after
*/
protected function drawSapAfter(){
?>
</div>
</div>
<?php
}
/**
* draw hr row
*/
protected function drawHrRow($setting){
$id = UniteFunctionsUC::getVal($setting, "id");
$rowClass = $this->drawSettingRow_getRowClass($setting);
?>
<li id="<?php esc_attr_e($id) ?>_row" <?php echo UniteProviderFunctionsUC::escAddParam($rowClass) ?>>
<hr id="<?php esc_attr_e($id) ?>">
</li>
<?php
}
}

View File

@@ -0,0 +1,251 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteSettingsOutputWideUC extends UniteCreatorSettingsOutput{
/**
* constuct function
*/
public function __construct(){
$this->isParent = true;
self::$serial++;
$this->wrapperID = "unite_settings_wide_output_".self::$serial;
$this->settingsMainClass = "unite_settings_wide";
}
/**
* draw settings row
* @param $setting
* modes: single_editor (only 1 setting, editor type)
*/
protected function drawSettingRow($setting, $mode = ""){
//set cellstyle:
$cellStyle = "";
if(isset($setting[UniteSettingsUC::PARAM_CELLSTYLE])){
$cellStyle .= $setting[UniteSettingsUC::PARAM_CELLSTYLE];
}
if($cellStyle != "")
$cellStyle = "style='".$cellStyle."'";
$textStyle = $this->drawSettingRow_getTextStyle($setting);
$rowClass = $this->drawSettingRow_getRowClass($setting);
$text = $this->drawSettingRow_getText($setting);
$description = UniteFunctionsUC::getVal($setting,"description");
//set settings text width:
$textWidth = "";
if(isset($setting["textWidth"]))
$textWidth = 'width="'.$setting["textWidth"].'"';
$addField = UniteFunctionsUC::getVal($setting, UniteSettingsUC::PARAM_ADDFIELD);
$drawTh = true;
$tdHtmlAdd = "";
if($mode == "single_editor")
$drawTh = false;
if(empty($text))
$drawTh = false;
if($drawTh == false)
$tdHtmlAdd = " colspan=2";
?>
<?php
if(!empty($addField)):
$addSetting = $this->settings->getSettingByName($addField);
UniteFunctionsUC::validateNotEmpty($addSetting,"AddSetting {$addField}");
$addSettingText = UniteFunctionsUC::getVal($addSetting,"text","");
$addSettingText = str_replace(" ","&nbsp;", $addSettingText);
$tdSettingAdd = "";
if(!empty($addSetting)){
$tdSettingAdd = ' class="unite-settings-onecell" colspan="2"';
}
?>
<tr <?php echo UniteProviderFunctionsUC::escAddParam($rowClass)?> valign="top">
<?php if(empty($addSettingText)):?>
<th <?php echo UniteProviderFunctionsUC::escAddParam($textStyle)?> scope="row" <?php echo UniteProviderFunctionsUC::escAddParam($textWidth) ?>>
<?php if($this->showDescAsTips == true): ?>
<span class='setting_text' title="<?php echo esc_attr($description)?>"><?php echo $text?></span>
<?php else:?>
<?php echo $text?>
<?php endif?>
</th>
<?php endif?>
<td <?php echo UniteProviderFunctionsUC::escAddParam($cellStyle)?> <?php echo UniteProviderFunctionsUC::escAddParam($tdSettingAdd)?>>
<span id="<?php echo UniteProviderFunctionsUC::escAddParam($setting["id_row"])?>">
<?php if(!empty($addSettingText)):?>
<span class='setting_onecell_text'><?php echo esc_html($text)?></span>
<?php endif?>
<?php
$this->drawInputs($setting);
$this->drawInputAdditions($setting);
?>
<?php if(!empty($addSettingText)):?>
<span class="setting_onecell_horsap"></span>
<?php endif?>
</span>
<span id="<?php echo esc_attr($addSetting["id_row"])?>">
<span class='setting_onecell_text'><?php echo esc_html($addSettingText)?></span>
<?php
$this->drawInputs($addSetting);
$this->drawInputAdditions($addSetting);
?>
</span>
</td>
</tr>
<?php
?>
<?php else: ?>
<tr id="<?php echo esc_attr($setting["id_row"])?>" <?php echo UniteProviderFunctionsUC::escAddParam($rowClass)?> valign="top">
<?php if($drawTh == true):?>
<th <?php echo UniteProviderFunctionsUC::escAddParam($textStyle)?> scope="row" <?php echo UniteProviderFunctionsUC::escAddParam($textWidth) ?>>
<?php if($this->showDescAsTips == true): ?>
<span class='setting_text' title="<?php echo esc_attr($description)?>"><?php echo $text?></span>
<?php else:?>
<?php echo $text?>
<?php endif?>
</th>
<?php endif?>
<td <?php echo UniteProviderFunctionsUC::escAddParam($cellStyle)?> <?php echo UniteProviderFunctionsUC::escAddParam($tdHtmlAdd)?>>
<?php
$this->drawInputs($setting);
$this->drawInputAdditions($setting);
?>
</td>
</tr>
<?php
endif;
}
/**
* draw hr row
* @param $setting
*/
protected function drawHrRow($setting){
//set hidden
$class = UniteFunctionsUC::getVal($setting, "class");
$classHidden = $this->drawSettingRow_getRowHiddenClass($setting);
if(!empty($classHidden)){
if(!empty($class))
$class .= " ";
$class .= $classHidden;
}
if(!empty($class)){
$class = esc_attr($class);
$class = "class='$class'";
}
?>
<tr id="<?php echo esc_attr($setting["id_row"])?>">
<td colspan="4" align="left" style="text-align:left;">
<hr <?php echo UniteProviderFunctionsUC::escAddParam($class); ?> />
</td>
</tr>
<?php
}
/**
* draw text row
* @param unknown_type $setting
*/
protected function drawTextRow($setting){
//set cell style
$cellStyle = "";
if(isset($setting["padding"]))
$cellStyle .= "padding-left:".$setting["padding"].";";
if(!empty($cellStyle))
$cellStyle="style='$cellStyle'";
//set style
$tdHtmlAdd = 'colspan="2"';
$label = UniteFunctionsUC::getVal($setting, "label");
if(!empty($label))
$tdHtmlAdd = "";
$rowClass = $this->drawSettingRow_getRowClass($setting);
$classAdd = UniteFunctionsUC::getVal($setting, UniteSettingsUC::PARAM_CLASSADD);
if(!empty($classAdd))
$classAdd = " ".$classAdd;
?>
<tr id="<?php echo esc_attr($setting["id_row"])?>" <?php echo UniteProviderFunctionsUC::escAddParam($rowClass)?> valign="top">
<?php if(!empty($label)):?>
<th>
<?php echo $label?>
</th>
<?php endif?>
<td <?php echo UniteProviderFunctionsUC::escAddParam($tdHtmlAdd)?> <?php echo UniteProviderFunctionsUC::escAddParam($cellStyle)?>>
<span class="unite-settings-static-text<?php echo esc_attr($classAdd)?>"><?php echo $setting["text"]?></span>
</td>
</tr>
<?php
}
/**
* draw wrapper before settings
*/
protected function drawSettings_before(){
?><table class='unite_table_settings_wide'><?php
}
/**
* draw wrapper end after settings
*/
protected function drawSettingsAfter(){
?></table><?php
}
}
?>

View File

@@ -0,0 +1,365 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteShapeManagerUC extends HtmlOutputBaseUC{
private static $arrShapeDividersCache = array();
private static $arrShapesCache = array();
/**
* get output shapes by type
*/
private function getShapesOutputByType($arrAddons, $getType){
$arrOutput = array();
foreach($arrAddons as $addon){
$alias = $addon->getAlias();
switch($getType){
case "picker":
$title = $addon->getTitle();
$arrOutput[$alias] = $title;
break;
case "short":
$title = $addon->getTitle();
$arrOutput[$title] = $alias;
break;
case "data":
$svgContent = $addon->getHtml();
$svgEncoded = base64_encode($svgContent);
$arrOutput[$alias] = $svgEncoded;
break;
case "bgurl":
$svgContent = $addon->getHtml();
$svgEncoded = UniteFunctionsUC::encodeSVGForBGUrl($svgContent);
$arrOutput[$alias] = $svgEncoded;
break;
case "svg":
$svgContent = $addon->getHtml();
$arrOutput[$alias] = $svgContent;
break;
}
}
return($arrOutput);
}
/**
* get shape deviders array
* getType - short / html
*/
public function getArrShapeDividers($getType = null){
if(empty(self::$arrShapeDividersCache)){
$objAddons = new UniteCreatorAddons();
$params = array();
$params["addontype"] = GlobalsUC::ADDON_TYPE_SHAPE_DEVIDER;
self::$arrShapeDividersCache = $objAddons->getArrAddons("", $params);
}
if(empty($getType))
return(self::$arrShapeDividersCache);
$arrOutput = $this->getShapesOutputByType(self::$arrShapeDividersCache, $getType);
return($arrOutput);
}
/**
* get shape deviders array
* getType - short / html
*/
public function getArrShapes($getType = null){
if(empty(self::$arrShapesCache)){
$objAddons = new UniteCreatorAddons();
$params = array();
$params["addontype"] = GlobalsUC::ADDON_TYPE_SHAPES;
self::$arrShapesCache = $objAddons->getArrAddons("", $params);
}
if(empty($getType))
return(self::$arrShapesCache);
$arrOutput = self::getShapesOutputByType(self::$arrShapesCache, $getType);
return($arrOutput);
}
/**
* get element shape evider html
*/
private function getElementShapeDividerHtml($position, $settings, $elementID){
$enableKey = "enable_shape_devider_".$position;
if(isset($settings[$enableKey])){
$isEnable = UniteFunctionsUC::getVal($settings, "enable_shape_devider_".$position);
$isEnable = UniteFunctionsUC::strToBool($isEnable);
if($isEnable == false)
return("");
}
$shapeType = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_type");
if(empty($shapeType))
return("");
$class = "uc-shape-devider-{$position}";
$selector = "#{$elementID} > .{$class}";
$shapeColor = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_color");
$isflip = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_flip");
$isflip = UniteFunctionsUC::strToBool($isflip);
$height = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_height");
$placement = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_placement");
$repeat = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_repeat");
$arrShapes = self::getArrShapeDividers("svg");
$shapeSVG = UniteFunctionsUC::getVal($arrShapes, $shapeType);
if(empty($shapeSVG))
return("");
//replace color
if(!empty($shapeColor)){
$shapeSVG = str_replace('g fill="#ffffff"', 'g fill="'.$shapeColor.'"', $shapeSVG);
}
$shapeContent = UniteFunctionsUC::encodeSVGForBGUrl($shapeSVG);
$arrCss = array();
$arrCss["background-image"] = "url('{$shapeContent}')";
//add rotation
$rotation = "";
if($isflip == true){
if($position == "top")
$arrCss["transform"] = "rotateY(180deg)";
else
$arrCss["transform"] = "rotateX(180deg) rotateY(180deg)";
}
//set repeat
$percentRepeat = 100;
if(is_numeric($repeat)){
if($repeat <= 0)
$repeat = 1;
if($repeat > 1)
$percentRepeat = 100 / $repeat;
$decimal = $percentRepeat - (int)$percentRepeat;
if($decimal > 0)
$percentRepeat = number_format($percentRepeat, 2);
}
if(!empty($height)){
$height = UniteFunctionsUC::normalizeSize($height);
$arrCss["height"] = $height;
$arrCss["background-size"] = $percentRepeat."% ".$height;
}
//get mobile size css
$arrCssSizes = array();
foreach(GlobalsUC::$arrSizes as $size){
$settingName = "shape_devider_{$position}_height_$size";
$heightSize = UniteFunctionsUC::getVal($settings, $settingName);
$arrCssSize = array();
if(empty($heightSize))
continue;
$heightSize = UniteFunctionsUC::normalizeSize($heightSize);
$arrCssSize["height"] = $heightSize;
$arrCssSize["background-size"] = $percentRepeat."% ".$heightSize;
$cssSize = UniteFunctionsUC::arrStyleToStrStyle($arrCssSize, $selector);
$arrCssSizes[$size] = $cssSize;
}
if($placement == "beneath"){
$arrCss["z-index"] = "0";
}
//--- output
$css = UniteFunctionsUC::arrStyleToStrStyle($arrCss, $selector);
HelperUC::putInlineStyle(self::BR2.$css);
//put mobile size css
if(!empty($arrCssSizes)){
$cssMobileSize = HelperUC::getCssMobileSize($arrCssSizes);
HelperUC::putInlineStyle(self::BR2.$cssMobileSize);
}
$html = "";
$class = esc_attr($class);
$html .= "<div class='uc-shape-devider {$class}'></div> \n";
return($html);
}
/**
* get shpae devider addons from grid settings
*/
public function getShapeDividerNameFromSettings($settings, $position){
//preserve old way
$enableKey = "enable_shape_devider_".$position;
if(isset($settings[$enableKey])){
$isEnable = $settings[$enableKey];
$isEnable = UniteFunctionsUC::strToBool($isEnable);
if($isEnable == false)
return(null);
}
$shapeType = UniteFunctionsUC::getVal($settings, "shape_devider_{$position}_type");
if(empty($shapeType))
return(null);
return($shapeType);
}
/**
* get element shape deviders
*/
public function getElementShapeDividersHtml($settings, $elementID){
$html = "";
$html .= self::getElementShapeDividerHtml("top", $settings, $elementID);
$html .= self::getElementShapeDividerHtml("bottom", $settings, $elementID);
return($html);
}
/**
* output shapes css
*/
public function outputCssShapes(){
header("Content-type: text/css");
$arrShapes = self::getArrShapes("bgurl");
$css = "";
foreach($arrShapes as $name=>$urlShape)
$css .= ".unite-shapecontent-{$name}{background-image:url({$urlShape})}".self::BR2;
echo UniteProviderFunctionsUC::escCombinedHtml($css);
}
/**
* get json shapes array for the picker
*/
public function getJsonShapes(){
try{
$arrShapes = $this->getArrShapes("picker");
}catch(Exception $e){
$arrShapes = array();
}
$jsonShapes = json_encode($arrShapes);
return($jsonShapes);
}
/**
* get shape svg content
*/
public function getShapeSVGContent($shapeName){
try{
$addon = new UniteCreatorAddon();
$addon->initByAlias($shapeName, GlobalsUC::ADDON_TYPE_SHAPES);
$svgContent = $addon->getHtml();
return($svgContent);
}catch(Exception $e){
return($shapeName." not found");
}
}
/**
* get shape content by id
*/
public function getShapeBGContentBYAddonID($addonID){
$objAddon = new UniteCreatorAddon();
$objAddon->initByID($addonID);
$objAddonType = $objAddon->getObjAddonType();
if($objAddonType->isSVG == false)
UniteFunctionsUC::throwError("The addon is not svg");
$svgContent = $objAddon->getHtml();
$encodedContent = base64_encode($svgContent);
return($encodedContent);
}
/**
* get devider content by data
*/
public static function getShapeDividerBGContentByData($data){
$name = UniteFunctionsUC::getVal($data, "name");
$SVGcontent = $this->getShapeSVGContent($name);
$encodedContent = UniteFunctionsUC::encodeSVGForBGUrl($SVGcontent);
$response = array();
$response["content"] = $encodedContent;
return($response);
}
}

View File

@@ -0,0 +1,639 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
/**
*
* outputs all related to table with paging
*
*/
class UniteTableUC extends HtmlOutputBaseUC{
const GET_FIELD_PAGE = "table_page";
const GET_FIELD_INPAGE = "table_inpage";
const GET_FIELD_SEARCH = "table_search";
const GET_FIELD_CATEGORY = "table_category";
const GET_FIELD_ORDER = "table_order";
const GET_FIELD_ORDER_DIR = "table_order_dir";
const GET_FIELD_OPTION = "option";
const GET_FIELD_VIEW = "view";
private $isPaging = false;
private $isInsideTopActions = false;
private $defaultOrderby;
private $page;
private $inPage;
private $total;
private $numPages;
private $baseUrl;
private $arrOrderFields;
private $defaultInPage = 10;
/**
* validate that the paging is inited
*/
private function validatePaging(){
if($this->isPaging == false)
UniteFunctionsUC::throwError("The paging should be available");
}
/**
* validate that it's inside top actions
*/
private function validateTopActions(){
if($this->isInsideTopActions == false)
UniteFunctionsUC::throwError("The top actions form should be started");
}
private function a_GETTERS(){}
/**
* get page from get
*/
private function getPageFromGet(){
$page = UniteFunctionsUC::getGetVar(self::GET_FIELD_PAGE,1,UniteFunctionsUC::SANITIZE_ID);
$page = (int)$page;
return($page);
}
/**
* get inpage from get
*/
private function getInPageFromGet(){
$inpage = UniteFunctionsUC::getGetVar(self::GET_FIELD_INPAGE, $this->defaultInPage, UniteFunctionsUC::SANITIZE_ID);
$inpage = (int)$inpage;
return($inpage);
}
/**
* get category from get
*/
private function getCategoryFromGet(){
$cat = UniteFunctionsUC::getGetVar(self::GET_FIELD_CATEGORY, "", UniteFunctionsUC::SANITIZE_KEY);
if($cat == "all" || $cat === "")
$cat = null;
else
$cat = (int)$cat;
return($cat);
}
/**
* get search value from get
*/
private function getSearchValueFromGet(){
$search = UniteFunctionsUC::getGetVar(self::GET_FIELD_SEARCH, "", UniteFunctionsUC::SANITIZE_TEXT_FIELD);
return($search);
}
/**
* get order value from get
*/
private function getOrderValueFromGet(){
$order = UniteFunctionsUC::getGetVar(self::GET_FIELD_ORDER, "", UniteFunctionsUC::SANITIZE_TEXT_FIELD);
if(empty($order))
$order = $this->defaultOrderby;
return($order);
}
/**
* get all available get fields
*/
private function getGetFieldsNames($includeBaseFields = false, $isBaseOnly = false){
$fields = array();
if($includeBaseFields == true){
$fields[] = self::GET_FIELD_OPTION;
$fields[] = self::GET_FIELD_VIEW;
if($isBaseOnly == true)
return($fields);
}
$fields[] = self::GET_FIELD_PAGE;
$fields[] = self::GET_FIELD_INPAGE;
$fields[] = self::GET_FIELD_SEARCH;
$fields[] = self::GET_FIELD_CATEGORY;
$fields[] = self::GET_FIELD_ORDER;
$fields[] = self::GET_FIELD_ORDER_DIR;
return($fields);
}
/**
* get field values from get, from names array
*/
private function getArrFieldsValuesFromGet($fieldNames, $exceptField = null){
$arrFields = array();
foreach($fieldNames as $name){
if(!empty($exceptField) && $name == $exceptField)
continue;
$fieldValue = UniteFunctionsUC::getGetVar($name, "", UniteFunctionsUC::SANITIZE_TEXT_FIELD);
if(!empty($fieldValue))
$arrFields[$name] = $fieldValue;
}
return($arrFields);
}
/**
* get array of fields from get
*/
private function getArrGetFields($includeBaseFields = false, $exceptField = null){
$fieldNames = $this->getGetFieldsNames($includeBaseFields);
$arrFields = $this->getArrFieldsValuesFromGet($fieldNames, $exceptField);
return($arrFields);
}
/**
* get base fields obnly
*/
private function getArrBaseFields(){
$fieldNames = $this->getGetFieldsNames(true, true);
$arrFields = $this->getArrFieldsValuesFromGet($fieldNames);
return($arrFields);
}
/**
* get page url
*/
private function getUrlPage($page = null,$exceptField=null){
$arrGetFields = $this->getArrGetFields(false, $exceptField);
if(!empty($page))
$arrGetFields[self::GET_FIELD_PAGE] = $page;
$urlPage = UniteFunctionsUC::addUrlParams($this->baseUrl, $arrGetFields);
return($urlPage);
}
private function a_SETTERS(){}
/**
* set default orderby
*/
public function setDefaultOrderby($orderby){
$this->defaultOrderby = $orderby;
}
private function a_GENERAL_GET(){}
/**
* get paging options from get and default
*/
public function getPagingOptions(){
$output = array();
$output["page"] = $this->getPageFromGet();
$output["inpage"] = $this->getInPageFromGet();
$output["search"] = $this->getSearchValueFromGet();
$output["category"] = $this->getCategoryFromGet();
//take ordering
$ordering = $this->getOrderValueFromGet();
$ordering = str_replace("_desc", " desc", $ordering);
$output["ordering"] = $ordering;
return($output);
}
/**
* set paging data
*/
public function setPagingData($baseURl, $data){
$this->baseUrl = $baseURl;
$this->total = UniteFunctionsUC::getVal($data, "total");
$this->page = UniteFunctionsUC::getVal($data, "page");
$this->inPage = UniteFunctionsUC::getVal($data, "inpage");
$this->numPages = UniteFunctionsUC::getVal($data, "num_pages");
UniteFunctionsUC::validateNotEmpty($this->inPage, "in page");
if($this->total > 0){
UniteFunctionsUC::validateNotEmpty($this->page, "page");
UniteFunctionsUC::validateNotEmpty($this->numPages, "num pages");
}
$this->isPaging = true;
}
private function a_GET_HTML(){}
/**
* convert fields array to html hidden inputs
*/
private function arrFieldsToHtmlHiddenInputs($arrGetFields){
$html = "";
foreach($arrGetFields as $name=>$value)
$html .= self::TAB3.HelperHtmlUC::getHiddenInputField($name, $value).self::BR;
return($html);
}
/**
* get all hidden fields html
*/
private function getHtmlHiddenInputs($except_field){
$arrGetFields = $this->getArrGetFields(true, $except_field);
$html = $this->arrFieldsToHtmlHiddenInputs($arrGetFields);
return($html);
}
/**
* get all hidden fields html
*/
private function getHtmlHiddenBaseInputs(){
$arrGetFields = $this->getArrBaseFields();
$html = $this->arrFieldsToHtmlHiddenInputs($arrGetFields);
return($html);
}
/**
* put actions form end
*/
public function putActionsFormStart(){
$this->validatePaging();
$url = $this->baseUrl;
$url = htmlspecialchars($url);
$html = "";
$html .= self::TAB2."<form method='get' name='unite-table-actions' action='{$url}'>".self::BR2;
$html .= $this->getHtmlHiddenBaseInputs();
echo UniteProviderFunctionsUC::escCombinedHtml($html);
$this->isInsideTopActions = true;
}
/**
* put actions form start
*/
public function putActionsFormEnd(){
$this->validateTopActions();
$html = self::TAB2."</form>".self::BR;
$this->isInsideTopActions = false;
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
/**
* get select form
*/
private function getHtmlFormSelect($htmlSelect, $htmlGetFields){
$html = "";
if($this->isInsideTopActions == false)
$html .= "<form method='get'>";
$html .= $htmlSelect;
if($this->isInsideTopActions == false){
$html .= $htmlGetFields;
$html .= '</form>';
}
return $html;
}
/**
* get input with count content, about 10,25,50,100
*/
public function getHTMLInpageSelect(){
$inpage = $this->getInPageFromGet();
$arrNumbers = array(
"10","25","50","100"
);
$fieldInpage = self::GET_FIELD_INPAGE;
$htmlSelect = HelperHtmlUC::getHTMLSelect($arrNumbers, $inpage, "name='{$fieldInpage}' class='unite-tableitems-selectrecords' onchange='this.form.submit()'");
$htmlGetFields = $this->getHtmlHiddenInputs($fieldInpage);
$html = $this->getHtmlFormSelect($htmlSelect, $htmlGetFields);
return($html);
}
/**
* put filter category input
*/
public function putFilterCategory(){
$cat = $this->getCategoryFromGet();
$objCats = new UniteCreatorCategories;
$arrCats = $objCats->getCatsShort("all_uncat_layouts", "layout");
$html = "";
$fieldCat = self::GET_FIELD_CATEGORY;
if($cat === "" || $cat === null)
$cat = "all";
$htmlSelect = HelperHtmlUC::getHTMLSelect($arrCats, $cat, "name='{$fieldCat}' class='unite-tableitems-category' onchange='this.form.submit()'", true);
$htmlGetFields = $this->getHtmlHiddenInputs($fieldCat);
$html = "<span class='uc-table-top-filter-title'>".esc_html__("Filter Category", "unlimited-elements-for-elementor")."</span>";
$html .= $this->getHtmlFormSelect($htmlSelect, $htmlGetFields);
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
/**
* get pagination html
*/
private function getPaginationHtml(){
$this->validatePaging();
$item_per_page = $this->inPage;
$current_page = $this->page;
$total_records = $this->total;
$total_pages = $this->numPages;
$isShowExtras = true;
$pagination = '';
if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
$pagination .= '<ul class="unite-pagination class-for-pagination">';
$right_links = $current_page + 8;
$previous = $current_page - 1; //previous link
$next = $current_page + 1; //next link
$first_link = true; //boolean var to decide our first link
//put first and previous
if($current_page > 1 && $isShowExtras == true){
$previous_link = ($previous==0)?1:$previous;
$urlFirst = $this->getUrlPage(1);
$urlPrev = $this->getUrlPage($previous_link);
$titleFirst = esc_html__("First", "unlimited-elements-for-elementor");
$titlePrev = esc_html__("Previous", "unlimited-elements-for-elementor");
$textFirst = "";
$textPrev = "";
$pagination .= '<li class="unite-first"><a href="'.$urlFirst.'" title="'.$titleFirst.'" > &laquo; '.$textFirst.'</a></li>'; //first link
$pagination .= '<li><a href="'.$urlPrev.'" title="'.$titlePrev.'">&lt; '.$textPrev.'</a></li>'; //previous link
for($i = ($current_page-3); $i < $current_page; $i++){ //Create left-hand side links
if($i > 0){
$urlPage = $this->getUrlPage($i);
$pagination .= '<li><a href="'.$urlPage.'">'.$i.'</a></li>';
}
}
$first_link = false; //set first link to false
}
if($first_link){ //if current active page is first link
$pagination .= '<li class="unite-first unite-active"><a href="javascript:void(0)">'.$current_page.'</a></li>';
}elseif($current_page == $total_pages){ //if it's the last active link
$pagination .= '<li class="unite-last unite-active"><a href="javascript:void(0)">'.$current_page.'</a></li>';
}else{ //regular current link
$pagination .= '<li class="unite-active"><a href="javascript:void(0)">'.$current_page.'</a></li>';
}
for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
if($i<=$total_pages){
$urlPage = $this->getUrlPage($i);
$pagination .= '<li><a href="'.$urlPage.'">'.$i.'</a></li>';
}
}
//show first / last
if($current_page < $total_pages && $isShowExtras == true){
//next and last pages
$next_link = ($i > $total_pages)? $total_pages : $i;
$urlNext = $this->getUrlPage($next_link);
$urlLast = $this->getUrlPage($total_pages);
$titleNext = esc_html__("Next Page", "unlimited-elements-for-elementor");
$titleLast = esc_html__("Last Page", "unlimited-elements-for-elementor");
$textNext = "";
$textLast = "";
$pagination .= "<li><a href=\"{$urlNext}\" title=\"$titleNext\" >{$textNext} &gt;</a></li>";
$pagination .= "<li class=\"unite-last\"><a href=\"{$urlLast}\" title=\"$titleLast\" >{$textLast} &raquo; </a></li>";
}
$pagination .= '</ul>';
}
return($pagination);
}
/**
* draw table pagination
*/
public function putPaginationHtml(){
$this->validatePaging();
$html = $this->getPaginationHtml();
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
/**
* put inpage select
*/
public function putInpageSelect(){
$this->validatePaging();
if($this->total <= 10)
return("");
$html = $this->getHTMLInpageSelect();
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
/**
* function for search content and sorting
*/
public function putSearchForm($buttonText = "", $clearText = "", $putByDefault = true){
//the button must be inside top actions
$this->validateTopActions();
$html = "";
$fieldValue = $this->getSearchValueFromGet();
$fieldValue = htmlspecialchars($fieldValue);
if(empty($buttonText))
$buttonText = esc_html__("Search", "unlimited-elements-for-elementor");
if(empty($clearText))
$clearText = esc_html__("Clear", "unlimited-elements-for-elementor");
$fieldName = self::GET_FIELD_SEARCH;
$htmlFields = $this->getHtmlHiddenInputs($fieldName);
$urlClear = $this->getUrlPage();
//is total allow to put search
$isTotalAllow = ($this->total > 5);
if($isTotalAllow == false && empty($fieldValue))
return(false);
if($putByDefault == false && empty($fieldValue))
return(false);
if($this->isInsideTopActions == false){
$urlForm = $this->baseUrl;
$html .= self::TAB2."<form name='unite_form_table_search' method='get' action='$urlForm'>".self::BR;
}
$html .= self::TAB2." <input name='$fieldName' type='text' class='unite-input-medium mbottom_0 unite-cursor-text' value=\"{$fieldValue}\"/> ".self::BR;
$html .= self::TAB2." <button class='unite-button-primary' type='submit' value='1'>".$buttonText."</button>".self::BR;
//add clear button
if(!empty($fieldValue)){
$urlClear = $this->getUrlPage(null, self::GET_FIELD_SEARCH);
$html .= self::TAB2." <a class='unite-button-secondary' href=\"{$urlClear}\" >". $clearText."</a>".self::BR;
}
if($this->isInsideTopActions == false){
$html .= self::TAB3.$htmlFields.self::BR;
$html .= self::TAB2."</form>".self::BR;
}
if(!empty($searchValue))
$html .= " <a href=\"{$url}\" class=\"unite-button-secondary\">".$clearText."</a>";
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
/**
* put table order header - inside table th
*/
public function putTableOrderHeader($name, $text){
$currentOrder = $this->getOrderValueFromGet();
$currentOrderField = str_replace("_desc", "", $currentOrder);
$isDesc = ($currentOrder != $currentOrderField);
$orderForLink = $name;
if($currentOrderField == $name && $isDesc == false)
$orderForLink = $name."_desc";
$link = $this->getUrlPage(null, self::GET_FIELD_ORDER);
$link = UniteFunctionsUC::addUrlParams($link, self::GET_FIELD_ORDER."=".$orderForLink);
//get text
$signUp = "&#8743;";
$signDown = "&#8744;";
$linkText = $text;
if($name == $currentOrderField){
if($isDesc == true)
$linkText .= " ".$signUp;
else
$linkText .= " ".$signDown;
}
$html = "<a href='$link'>$linkText</a>";
echo UniteProviderFunctionsUC::escCombinedHtml($html);
}
}

View File

@@ -0,0 +1,107 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteTranslateUC{
private $entries;
private $domain;
/**
* load language
*/
public function __construct($domain){
$this->domain = $domain;
$this->get_translations_for_domain($domain);
}
/*
* read from language file and put it in entries for translate
* @Params String $domain - basse name of language file
*/
private function get_translations_for_domain( $domain = "default" ){
if($this->entries != null){
return true;
}
$mo = new MO();
$current_language = JFactory::getLanguage();
$mo_file = JPATH_COMPONENT . DIRECTORY_SEPARATOR."language".DIRECTORY_SEPARATOR. $domain ."-". $current_language->getTag() .".mo" ;
if(!file_exists($mo_file)){
$mo_file = JPATH_COMPONENT . DIRECTORY_SEPARATOR."language".DIRECTORY_SEPARATOR. $domain ."-". str_replace("-", "_", $current_language->getTag()) .".mo" ;
if(!file_exists($mo_file)){
return false;
}
}
if ( !$mo->import_from_file( $mo_file ) ) return false;
if ( !isset( $lang[$domain] ) ){
$lang[$domain] = $mo;
}
$this->merge_with( $lang[$domain] );
}
/**
* translate text
*/
private function translate_singular($singular, $context=null) {
$entry = new Translation_Entry(array('singular' => $singular, 'context' => $context));
$translated = $this->translate_entry($entry);
return ($translated && !empty($translated->translations))? $translated->translations[0] : $singular;
}
/*
* put data read from language file to entries for translate
*/
private function merge_with(&$other) {
foreach( $other->entries as $entry ) {
$this->entries[$entry->key()] = $entry;
}
}
/**
* translate entry
*/
private function translate_entry(&$entry) {
$key = $entry->key();
return isset($this->entries[$key])? $this->entries[$key] : false;
}
/**
* translate the text
*/
public function translate($text) {
$translations = $this->translate_singular($text);
return $translations;
}
}
?>

View File

@@ -0,0 +1,557 @@
<?php
/**
* @package Unlimited Elements
* @author unlimited-elements.com
* @copyright (C) 2021 Unlimited Elements, All Rights Reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
* */
defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access');
class UniteZipUC{
private $_methods = array(0x0 => 'None', 0x1 => 'Shrunk', 0x2 => 'Super Fast', 0x3 => 'Fast', 0x4 => 'Normal', 0x5 => 'Maximum', 0x6 => 'Imploded', 0x8 => 'Deflated');
private $_ctrlDirHeader = "\x50\x4b\x01\x02";
private $_ctrlDirEnd = "\x50\x4b\x05\x06\x00\x00\x00\x00";
private $_fileHeader = "\x50\x4b\x03\x04";
private $_data = null;
private $_metadata = null;
private $contents = array();
private $ctrldir = array();
private $isZipArchiveExists = false;
private $zip;
/**
* make zip archive
* if exists additional paths, add additional items to the zip
*/
public function makeZip($srcPath, $zipFilepath, $additionPaths = array()){
if(!is_dir($srcPath))
UniteFunctionsUC::throwError("The path: '$srcPath' don't exists, can't zip");
$this->isZipArchiveExists = $this->isZipArchiveExists();
if($this->isZipArchiveExists === true){
$this->zip = new ZipArchive();
$success = $this->zip->open($zipFilepath, ZipArchive::CREATE);
if($success === false)
UniteFunctionsUC::throwError("Can't create zip file: $zipFilepath");
}else{
$this->contents = array();
$this->ctrldir = array();
}
$this->addItem($srcPath, $srcPath);
if(gettype($additionPaths) != "array")
UniteFunctionsUC::throwError("Wrong additional paths variable.");
//add additional paths
if(!empty($additionPaths))
foreach($additionPaths as $path){
if(!is_dir($path))
UniteFunctionsUC::throwError("Path: $path not found, can't zip");
$this->addItem($path, $path);
}
if($this->isZipArchiveExists == true){
$this->zip->close();
}else{
$this->_createZIPFile($this->contents, $this->ctrldir, $zipFilepath);
}
}
/**
* extract zip archive
*/
public function extract($src, $dest){
if($this->isZipArchiveExists() === true){
$success = $this->extract_zipArchive($src, $dest);
if($success === true)
return true;
$filename = basename($src);
UniteFunctionsUC::throwError("Can't extract zip: $filename");
}
$success = $this->extract_custom($src, $dest);
return ($success);
}
/**
* check if the zip archive exists
*/
private function isZipArchiveExists(){
$exists = class_exists("ZipArchive");
return $exists;
}
/**
* add zip file
*/
private function addItem($basePath, $path){
$rel_path = str_replace($basePath . "/", "", $path);
if(is_dir($path)){ //directory
//add dir to zip
if($basePath != $path){
if($this->isZipArchiveExists)
$this->zip->addEmptyDir($rel_path);
}
$files = scandir($path);
foreach($files as $file){
if($file == "." || $file == ".." || $file == ".svn")
continue;
$filepath = $path . "/" . $file;
$this->addItem($basePath, $filepath);
}
}else{ //file
if(!file_exists($path))
UniteFunctionsUC::throwError("filepath: '$path' don't exists, can't zip");
if($this->isZipArchiveExists){
$path = str_replace("//", "/", $path);
$this->zip->addFile($path, $rel_path);
}else
$this->addFileToCustomZip($path, $rel_path);
}
}
/**
* check if dir exists, if not, create it recursively
*/
private function checkCreateDir($filepath){
$dir = dirname($filepath);
if(is_dir($dir) == false)
$success = $this->checkCreateDir($dir);
else
return (true);
//this dir is not exists, and all parent dirs exists
@mkdir($dir);
if(is_dir($dir) == false)
UniteFunctionsUC::throwError("Can't create directory: {$dir} maybe zip file is brocken");
}
/**
* write some file
*/
private function writeFile($str, $filepath){
//create folder if not exists
$this->checkCreateDir($filepath);
$fp = fopen($filepath, "w+");
fwrite($fp, $str);
fclose($fp);
if(file_exists($filepath) == false)
UniteFunctionsUC::throwError("can't write file: $filepath");
}
/**
* extract using zip archive
*/
private function extract_zipArchive($src, $dest){
$zip = new ZipArchive();
$result = $zip->open($src);
if($result !== true){
switch($result){
case ZipArchive::ER_NOZIP:
UniteFunctionsUC::throwError('not a zip archive');
case ZipArchive::ER_INCONS :
UniteFunctionsUC::throwError('consistency check failed');
case ZipArchive::ER_CRC :
UniteFunctionsUC::throwError('checksum failed');
default:
UniteFunctionsUC::throwError('error ' . $result);
}
}
$extracted = @$zip->extractTo($dest);
$zip->close();
if($extracted == false)
return (false);
return (true);
}
private function a_MAKEZIP_CUSTOM(){}
/**
* add empty dir to custom zip
*/
/*
private function addEmptyZipToCustomZip($path, $rel_path){
if(is_dir($path) == false)
UniteFunctionsUC::throwError("Can't add directory to zip: $path");
$time = filemtime($path);
$file = array();
$file["data"] = "";
$file["name"] = $rel_path;
$file["time"] = $time;
$this->_addToZIPFile($file, $this->contents, $this->ctrldir);
}
*/
/**
* add some file to custom zip
*/
private function addFileToCustomZip($path, $rel_path){
if(is_file($path) == false)
UniteFunctionsUC::throwError("can't add to zip file: $path");
$content = file_get_contents($path);
$time = filemtime($path);
$file = array();
$file["data"] = $content;
$file["name"] = $rel_path;
$file["time"] = $time;
$this->_addToZIPFile($file, $this->contents, $this->ctrldir);
}
/**
* Adds a "file" to the ZIP archive.
*
* @param array &$file File data array to add
* @param array &$contents An array of existing zipped files.
* @param array &$ctrldir An array of central directory information.
*
* @return void
*
* @since 11.1
*
* @todo Review and finish implementation
*/
private function _addToZIPFile(array &$file, array &$contents, array &$ctrldir){
$data = &$file['data'];
$name = str_replace('\\', '/', $file['name']);
/* See if time/date information has been provided. */
$ftime = null;
if(isset($file['time'])){
$ftime = $file['time'];
}
// Get the hex time.
$dtime = dechex($this->_unix2DosTime($ftime));
$hexdtime = chr(hexdec($dtime[6] . $dtime[7])) . chr(hexdec($dtime[4] . $dtime[5])) . chr(hexdec($dtime[2] . $dtime[3]))
. chr(hexdec($dtime[0] . $dtime[1]));
/* Begin creating the ZIP data. */
$fr = $this->_fileHeader;
/* Version needed to extract. */
$fr .= "\x14\x00";
/* General purpose bit flag. */
$fr .= "\x00\x00";
/* Compression method. */
$fr .= "\x08\x00";
/* Last modification time/date. */
$fr .= $hexdtime;
/* "Local file header" segment. */
$unc_len = strlen($data);
$crc = crc32($data);
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
$c_len = strlen($zdata);
/* CRC 32 information. */
$fr .= pack('V', $crc);
/* Compressed filesize. */
$fr .= pack('V', $c_len);
/* Uncompressed filesize. */
$fr .= pack('V', $unc_len);
/* Length of filename. */
$fr .= pack('v', strlen($name));
/* Extra field length. */
$fr .= pack('v', 0);
/* File name. */
$fr .= $name;
/* "File data" segment. */
$fr .= $zdata;
/* Add this entry to array. */
$old_offset = strlen(implode('', $contents));
$contents[] = &$fr;
/* Add to central directory record. */
$cdrec = $this->_ctrlDirHeader;
/* Version made by. */
$cdrec .= "\x00\x00";
/* Version needed to extract */
$cdrec .= "\x14\x00";
/* General purpose bit flag */
$cdrec .= "\x00\x00";
/* Compression method */
$cdrec .= "\x08\x00";
/* Last mod time/date. */
$cdrec .= $hexdtime;
/* CRC 32 information. */
$cdrec .= pack('V', $crc);
/* Compressed filesize. */
$cdrec .= pack('V', $c_len);
/* Uncompressed filesize. */
$cdrec .= pack('V', $unc_len);
/* Length of filename. */
$cdrec .= pack('v', strlen($name));
/* Extra field length. */
$cdrec .= pack('v', 0);
/* File comment length. */
$cdrec .= pack('v', 0);
/* Disk number start. */
$cdrec .= pack('v', 0);
/* Internal file attributes. */
$cdrec .= pack('v', 0);
/* External file attributes -'archive' bit set. */
$cdrec .= pack('V', 32);
/* Relative offset of local header. */
$cdrec .= pack('V', $old_offset);
/* File name. */
$cdrec .= $name;
/* Optional extra field, file comment goes here. */
/* Save to central directory array. */
$ctrldir[] = &$cdrec;
}
/**
* Creates the ZIP file.
*
* Official ZIP file format: https://support.pkware.com/display/PKZIP/APPNOTE
*
* @param array &$contents An array of existing zipped files.
* @param array &$ctrlDir An array of central directory information.
* @param string $path The path to store the archive.
*
* @return boolean True if successful
*
* @since 11.1
*
* @todo Review and finish implementation
*/
private function _createZIPFile(array &$contents, array &$ctrlDir, $path){
$data = implode('', $contents);
$dir = implode('', $ctrlDir);
$buffer = $data . $dir . $this->_ctrlDirEnd . /* Total # of entries "on this disk". */
pack('v', count($ctrlDir)) . /* Total # of entries overall. */
pack('v', count($ctrlDir)) . /* Size of central directory. */
pack('V', strlen($dir)) . /* Offset to start of central dir. */
pack('V', strlen($data)) . /* ZIP file comment length. */
"\x00\x00";
UniteFunctionsUC::writeFile($buffer, $path);
return true;
}
/**
* Converts a UNIX timestamp to a 4-byte DOS date and time format
* (date in high 2-bytes, time in low 2-bytes allowing magnitude
* comparison).
*
* @param int $unixtime The current UNIX timestamp.
*
* @return int The current date in a 4-byte DOS format.
*
* @since 11.1
*/
private function _unix2DOSTime($unixtime = null){
$timearray = (is_null($unixtime)) ? getdate() : getdate($unixtime);
if($timearray['year'] < 1980){
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) |
($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
}
private function a_EXTRACT_CUSTOM(){}
/**
* extract zip customely
*/
private function extract_custom($src, $dest){
$this->_data = null;
$this->_metadata = null;
if(!extension_loaded('zlib'))
UniteFunctionsUC::throwError('Zlib not supported, please enable in php.ini');
$this->_data = file_get_contents($src);
if(!$this->_data)
UniteFunctionsUC::throwError('Get ZIP Data failed');
$success = $this->extract_custom_readZipInfo($this->_data);
if(!$success)
UniteFunctionsUC::throwError('Get ZIP Information failed');
for($i = 0, $n = count($this->_metadata); $i < $n; $i++){
$lastPathCharacter = substr($this->_metadata[$i]['name'], -1, 1);
if($lastPathCharacter !== '/' && $lastPathCharacter !== '\\'){
//write file
$buffer = $this->extract_custom_getFileData($i);
$destFilepath = UniteFunctionsUC::cleanPath($dest . '/' . $this->_metadata[$i]['name']);
$this->writeFile($buffer, $destFilepath);
}
}
return true;
}
/**
* read zip info
*/
private function extract_custom_readZipInfo(&$data){
$entries = array();
// Find the last central directory header entry
$fhLast = strpos($data, $this->_ctrlDirEnd);
do{
$last = $fhLast;
}while(($fhLast = strpos($data, $this->_ctrlDirEnd, $fhLast + 1)) !== false);
// Find the central directory offset
$offset = 0;
if($last){
$endOfCentralDirectory = unpack(
'vNumberOfDisk/vNoOfDiskWithStartOfCentralDirectory/vNoOfCentralDirectoryEntriesOnDisk/' .
'vTotalCentralDirectoryEntries/VSizeOfCentralDirectory/VCentralDirectoryOffset/vCommentLength',
substr($data, $last + 4)
);
$offset = $endOfCentralDirectory['CentralDirectoryOffset'];
}
// Get details from central directory structure.
$fhStart = strpos($data, $this->_ctrlDirHeader, $offset);
$dataLength = strlen($data);
do{
if($dataLength < $fhStart + 31){
UniteFunctionsUC::throwError('Invalid Zip Data');
}
$info = unpack('vMethod/VTime/VCRC32/VCompressed/VUncompressed/vLength', substr($data, $fhStart + 10, 20));
$name = substr($data, $fhStart + 46, $info['Length']);
$entries[$name] = array(
'attr' => null,
'crc' => sprintf("%08s", dechex($info['CRC32'])),
'csize' => $info['Compressed'],
'date' => null,
'_dataStart' => null,
'name' => $name,
'method' => $this->_methods[$info['Method']],
'_method' => $info['Method'],
'size' => $info['Uncompressed'],
'type' => null,
);
$entries[$name]['date'] = mktime(
(($info['Time'] >> 11) & 0x1f),
(($info['Time'] >> 5) & 0x3f),
(($info['Time'] << 1) & 0x3e),
(($info['Time'] >> 21) & 0x07),
(($info['Time'] >> 16) & 0x1f),
((($info['Time'] >> 25) & 0x7f) + 1980)
);
if($dataLength < $fhStart + 43){
UniteFunctionsUC::throwError('Invalid Zip Data');
}
$info = unpack('vInternal/VExternal/VOffset', substr($data, $fhStart + 36, 10));
$entries[$name]['type'] = ($info['Internal'] & 0x01) ? 'text' : 'binary';
$entries[$name]['attr'] = (($info['External'] & 0x10) ? 'D' : '-') . (($info['External'] & 0x20) ? 'A' : '-')
. (($info['External'] & 0x03) ? 'S' : '-') . (($info['External'] & 0x02) ? 'H' : '-') . (($info['External'] & 0x01) ? 'R' : '-');
$entries[$name]['offset'] = $info['Offset'];
// Get details from local file header since we have the offset
$lfhStart = strpos($data, $this->_fileHeader, $entries[$name]['offset']);
if($dataLength < $lfhStart + 34){
UniteFunctionsUC::throwError('Invalid Zip Data');
}
$info = unpack('vMethod/VTime/VCRC32/VCompressed/VUncompressed/vLength/vExtraLength', substr($data, $lfhStart + 8, 25));
$name = substr($data, $lfhStart + 30, $info['Length']);
$entries[$name]['_dataStart'] = $lfhStart + 30 + $info['Length'] + $info['ExtraLength'];
// Bump the max execution time because not using the built in php zip libs makes this process slow.
$maxTime = ini_get('max_execution_time');
if(!empty($maxTime) && is_numeric($maxTime))
@set_time_limit($maxTime);
}while((($fhStart = strpos($data, $this->_ctrlDirHeader, $fhStart + 46)) !== false));
$this->_metadata = array_values($entries);
return true;
}
/**
* get file data for extract
*/
private function extract_custom_getFileData($key){
if($this->_metadata[$key]['_method'] == 0x8){
return gzinflate(substr($this->_data, $this->_metadata[$key]['_dataStart'], $this->_metadata[$key]['csize']));
}elseif($this->_metadata[$key]['_method'] == 0x0){
/* Files that aren't compressed. */
return substr($this->_data, $this->_metadata[$key]['_dataStart'], $this->_metadata[$key]['csize']);
}elseif($this->_metadata[$key]['_method'] == 0x12){
// If bz2 extension is loaded use it
if(extension_loaded('bz2')){
return bzdecompress(substr($this->_data, $this->_metadata[$key]['_dataStart'], $this->_metadata[$key]['csize']));
}
}
return '';
}
}