/**
  * Ensures that an icon is valid
  * 
  * Checks agains the valid jQuery UI icons and return is, if present.
  * Else throws an Exception.
  * Have a look at the theme roller for valid icons: http://jqueryui.com/themeroller/
  * @param string $icon_to_test Name of the icon like 'circle-plus'
  * @return string The icon string as given in like 'circle-plus'
  */
 static function Icon($icon_to_test)
 {
     if (in_array($icon_to_test, self::$_icons)) {
         return $icon_to_test;
     }
     WdfException::Raise("Invalid Icon '{$icon_to_test}'");
 }
Example #2
0
/**
 * Initializes the payment module.
 * 
 * @return void
 */
function payment_init()
{
    global $CONFIG;
    $CONFIG['class_path']['system'][] = __DIR__ . '/payment/';
    if (!isset($CONFIG["payment"]["order_model"]) || !$CONFIG["payment"]["order_model"]) {
        WdfException::Raise('Please configure an order_model for the payment module');
    }
}
 function __initialize($title = "", $body_class = false)
 {
     parent::__initialize($title, $body_class);
     if (!isset($GLOBALS['CONFIG']['translation']['sync']['poeditor_api_key']) || !$GLOBALS['CONFIG']['translation']['sync']['poeditor_api_key']) {
         WdfException::Raise("POEditor API key missing!");
     }
     if (!isset($GLOBALS['CONFIG']['translation']['sync']['poeditor_project_id']) || !$GLOBALS['CONFIG']['translation']['sync']['poeditor_project_id']) {
         WdfException::Raise("POEditor ProjectID missing!");
     }
 }
Example #4
0
/**
 * Initializes the admin essential.
 * 
 * @return void
 */
function admin_init()
{
    global $CONFIG;
    if ($CONFIG['system']['admin']['enabled']) {
        $CONFIG['class_path']['system'][] = __DIR__ . '/admin/';
        if (!$CONFIG['system']['admin']['username'] || !$CONFIG['system']['admin']['username']) {
            WdfException::Raise("System admin needs username and password to be set!");
        }
        $CONFIG['system']['admin']['actions'] = array();
    }
}
 private static function _data($data)
 {
     if ($data) {
         if (is_string($data)) {
             return "{$data}";
         }
         if (is_array($data) || is_object($data)) {
             return json_encode($data);
         }
         WdfException::Raise("Invalid argmuent: 'data' should be string, array or object, but '" . gettype($data) . "' detected");
     }
     return '';
 }
 function __initialize($title = "", $body_class = false)
 {
     parent::__initialize($title, $body_class);
     if (isset($GLOBALS['CONFIG']['translation']['sync']['scavix_datasource']) && $GLOBALS['CONFIG']['translation']['sync']['scavix_datasource']) {
         $this->ds = model_datasource($GLOBALS['CONFIG']['translation']['sync']['scavix_datasource']);
     } elseif (isset($GLOBALS['CONFIG']['translation']['sync']['datasource']) && $GLOBALS['CONFIG']['translation']['sync']['datasource']) {
         $this->ds = model_datasource($GLOBALS['CONFIG']['translation']['sync']['datasource']);
     } else {
         WdfException::Raise("ScavixTranslations datasource missing!");
     }
     $this->ds->ExecuteSql("CREATE TABLE IF NOT EXISTS `wdf_translations` (\n\t\t\t\t`lang` VARCHAR(10) NULL,\n\t\t\t\t`id` VARCHAR(100) NULL,\n\t\t\t\t`content` TEXT NULL,\n\t\t\t\tPRIMARY KEY (`lang`, `id`) );");
     $this->subnav('Translate', 'TranslationAdmin', 'Translate');
     $this->subnav('Import', 'TranslationAdmin', 'Import');
 }
 function __construct()
 {
     global $CONFIG;
     parent::__construct();
     if (!isset($CONFIG["payment"]["gate2shop"]["merchant_id"])) {
         WdfException::Raise("Gate2Shop: Missing merchant_id");
     }
     if (!isset($CONFIG["payment"]["gate2shop"]["merchant_site_id"])) {
         WdfException::Raise("Gate2Shop: Missing merchant_site_id");
     }
     if (!isset($CONFIG["payment"]["gate2shop"]["secret_key"])) {
         WdfException::Raise("Gate2Shop: Missing secret_key");
     }
     $this->small_image = resFile("payment/gate2shop.png");
 }
Example #8
0
/**
 * @internal Starts the session handler.
 */
function session_run()
{
    global $CONFIG;
    // check for backwards compatibility
    if (isset($CONFIG['session']['usephpsession'])) {
        if ($CONFIG['session']['usephpsession'] && $CONFIG['session']['handler'] != "PhpSession" || !$CONFIG['session']['usephpsession'] && $CONFIG['session']['handler'] == "PhpSession") {
            WdfException::Raise('Do not use $CONFIG[\'session\'][\'usephpsession\'] anymore! See session_init() for details.');
        }
    }
    $CONFIG['session']['handler'] = fq_class_name($CONFIG['session']['handler']);
    $GLOBALS['fw_session_handler'] = new $CONFIG['session']['handler']();
    //	if( system_is_ajax_call() && isset($_SESSION['object_id_storage']) )
    if (isset($_SESSION['object_id_storage'])) {
        $GLOBALS['object_ids'] = $_SESSION['object_id_storage'];
    }
}
 /**
  * Overrides default invokeArgs method
  * 
  * See <ReflectionMethod::invokeArgs>
  * Will additionally check all defined extenders and call the method there if present.
  * @param object $object The object to invoke the method on. In case of static methods, you can pass null to this parameter
  * @param array $argsarray The parameters to be passed to the function, as an array
  * @return mixed Returns the method result. 
  */
 public function invokeArgs($object, array $argsarray)
 {
     try {
         return parent::invokeArgs($object, $argsarray);
     } catch (Exception $e) {
         log_debug("Checking for extender invokation");
     }
     if (!is_null($object) && $object instanceof Control) {
         foreach ($object->_extender as &$ex) {
             try {
                 return $this->invokeArgs($ex, $argsarray);
             } catch (Exception $e) {
                 log_debug("Checking other extenders");
             }
         }
     }
     WdfException::Raise("Error invoking " . $this->class . "->" . $this->name);
 }
 /**
  * Creates a new uiConfirmation object.
  * 
  * The $text_base argument in fact defines two texts in one (and assumes you are using translations!):
  * It will be prefixed with 'TXT_' and 'TITLE_' and that two constants will be used.
  * Sample: 'CONFIRMATION' will become 'TXT_CONFIRMATION' and 'TITLE_CONFIRMATION'.
  * @param string $text_base base of confirmation text.
  * @param string $ok_callback JS code to be executed when the positive button is clicked (OK, YES)
  * @param int $button_mode uiConfirmation::OK_CANCEL or uiConfirmation::YES_NO
  */
 function __initialize($text_base = 'CONFIRMATION', $ok_callback = false, $button_mode = self::OK_CANCEL)
 {
     $options = array('autoOpen' => true, 'modal' => true, 'width' => 450, 'height' => 300);
     $title = "TITLE_{$text_base}";
     $text = "TXT_{$text_base}";
     parent::__initialize($title, $options);
     switch ($button_mode) {
         case self::OK_CANCEL:
             $this->AddButton(tds('BTN_OK', 'Ok'), $ok_callback);
             $this->AddCloseButton(tds('BTN_CANCEL', 'Cancel'));
             break;
         case self::YES_NO:
             $this->AddButton(tds('BTN_YES', 'Yes'), $ok_callback);
             $this->AddCloseButton(tds('BTN_NO', 'No'));
             break;
         default:
             WdfException::Raise("Wrong button_mode: {$button_mode}");
     }
     $this->Mode = $button_mode;
     $this->content($text);
 }
Example #11
0
 /**
  * @override
  */
 public function StartCheckout(IShopOrder $order, $ok_url = false, $cancel_url = false)
 {
     global $CONFIG;
     if (!$ok_url) {
         WdfException::Raise('PayPal needs a return URL');
     }
     if (!$cancel_url) {
         $cancel_url = $ok_url;
     }
     $invoice_id = false;
     if ($tmp = $order->GetInvoiceId()) {
         $invoice_id = $tmp;
     }
     $this->SetVar("cmd", "_cart");
     $this->SetVar("upload", "1");
     $order_currency = $this->EnsureCurrency($order);
     $order->SetCurrency($order_currency);
     $this->SetVar("currency_code", $order_currency);
     $this->SetVar("charset", "utf-8");
     //		set language of paypal UI:
     //		$this->SetVar("lc", );
     if ($CONFIG["payment"]["paypal"]["use_sandbox"] == true) {
         $this->SetVar("sandbox", "1");
         $checkoutUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr";
     } else {
         $checkoutUrl = "https://www.paypal.com/cgi-bin/webscr";
     }
     $this->SetVar('business', $CONFIG["payment"]["paypal"]["paypal_id"]);
     $this->SetVar('custom', $CONFIG["payment"]["paypal"]["custom"]);
     if ($invoice_id) {
         $ok_url .= (stripos($ok_url, '?') !== false ? '&' : '?') . "order_id={$invoice_id}";
         $cancel_url .= (stripos($cancel_url, '?') !== false ? '&' : '?') . "order_id={$invoice_id}";
     }
     $this->SetVar('return', $ok_url);
     $this->SetVar('cancel_return', $cancel_url);
     $params = array("provider" => "paypal");
     $notify_url = buildQuery($CONFIG["payment"]["paypal"]["notify_handler"][0], $CONFIG["payment"]["paypal"]["notify_handler"][1], $params);
     $this->SetVar('notify_url', $notify_url);
     // customer details
     $address = $order->GetAddress();
     if ($address->Firstname) {
         $this->SetVar('first_name', $address->Firstname);
     }
     if ($address->Lastname) {
         $this->SetVar('last_name', $address->Lastname);
     }
     if ($address->Email) {
         $this->SetVar('email', $address->Email);
     }
     if ($address->Address1) {
         $this->SetVar('address1', $address->Address1);
     }
     if ($address->Address2) {
         $this->SetVar('address2', $address->Address2);
     }
     if ($address->Country) {
         $this->SetVar('country', $address->Country);
     }
     if ($address->State) {
         $this->SetVar('state', $address->State);
     }
     if ($address->Zip) {
         $this->SetVar('zip', $address->Zip);
     }
     if ($address->City) {
         $this->SetVar('city', $address->City);
     }
     // tell paypal to use this entered address:
     $this->SetVar('address_override', 1);
     $this->SetVar('bn', $CONFIG["payment"]["paypal"]["custom"]);
     // do not let users add notes in paypal:
     $this->SetVar('no_note', 1);
     /* Return method. The  FORM METHOD used to send data to the 
     		URL specified by the  return variable. 
     		Allowable values are: 
     		0 – all shopping cart payments use the GET  method 
     		1 – the buyer’s browser is re directed to the return URL 
     		by using the GET  method, but no payment variables are 
     		included 
     		2 – the buyer’s browser is re directed to the return URL 
     		by using the POST method, and all payment variables are 
     		included */
     $this->SetVar('rm', 1);
     if ($invoice_id) {
         $this->SetVar('invoice', $invoice_id);
     }
     $items = $order->ListItems();
     if (count($items) > 0) {
         $i = 1;
         foreach ($items as $item) {
             $price = $item->GetAmount();
             $this->SetVar("item_name_{$i}", $item->GetName());
             $this->SetVar("amount_{$i}", round($item->GetAmount($order_currency), 2));
             if ($order->DoAddVat()) {
                 $this->SetVar("tax_{$i}", round($item->GetAmount($order_currency) * ($CONFIG['model']['vat_percent'] / 100), 2));
             }
             $this->SetVar("quantity_{$i}", 1);
             $i++;
         }
     }
     $this->SetVar("tax_cart", round($order->GetTotalVat(), 2));
     return $this->CheckoutForm($checkoutUrl);
 }
Example #12
0
/**
 * Tests if the first given argument contains one of the others.
 * 
 * First argument may be an array or a string.
 * If array, all entries will be checked for equality with at least one of the other given arguments.
 * If string, <contains> performs a <stripos> check with each other given argument and returns true if at least one matched.
 * Use like this: 
 * <code php>
 * contains(array('Hello','nice','World'),'some','other','nice','words'); // true
 * contains('Hello nice World','some','other','nice','words'); // true
 * contains('Hello nice World','some','other','words'); // false
 * </code>
 * @return bool true or false
 */
function contains()
{
    $args = func_get_args();
    $array = array_shift($args);
    if (is_array($array)) {
        foreach ($args as $a) {
            if (in_array($a, $array)) {
                return true;
            }
        }
        return false;
    }
    if (is_string($array)) {
        foreach ($args as $a) {
            if (stripos($array, $a) !== false) {
                return true;
            }
        }
        return false;
    }
    WdfException::Raise('First argument needs to be of type array or string');
}
 /**
  * Attribute handling.
  * 
  * This method may be used in four different ways:
  * 1. to get all attributes
  * 2. to get one attribute
  * 3. to set one attribute
  * 4. to set many attributes
  * 
  * To achieve this pass different parameters into like this:
  * 1. $c->attr() returns all attributes
  * 2. $c->attr('name') returns the 'name' attributes value
  * 3. $c->attr('name','mycontrol') sets the 'name' attribute values
  * 4. $c->attr(array('name'=>'myname','href'=>'my.domain')) sets 'name' and 'href' attribute values
  * 
  * Note: Will return `$this` in cases 3. and 4. (the set cases).
  * @return mixed `$this`, an attribute value or an array of attribute values
  */
 function attr()
 {
     $cnt = func_num_args();
     switch ($cnt) {
         case 0:
             return $this->_attributes;
         case 1:
             $name = func_get_arg(0);
             if (is_array($name)) {
                 foreach ($name as $n => $v) {
                     $this->attr($n, $v);
                 }
                 return $this;
             }
             return $this->{$name};
         case 2:
             $name = func_get_arg(0);
             $this->{$name} = func_get_arg(1);
             return $this;
     }
     WdfException::Raise("Control::attr needs 0,1 or 2 parameters");
 }
Example #14
0
/**
 * @internal Performs JavaScript minifying
 */
function minify_js($paths, $target_file)
{
    require_once __DIR__ . "/minify/jsmin.php";
    $files = minify_collect_files($paths, 'js');
    log_debug("JS files to minify: ", $files);
    //die("stopped");
    $code = "";
    foreach ($files as $f) {
        if (starts_with($f, "/") && !starts_with($f, "//")) {
            $f = (isSSL() ? "https" : "http") . "://{$_SERVER['SERVER_NAME']}" . $f;
        }
        $js = sendHTTPRequest($f, false, false, $response_header);
        if (mb_detect_encoding($js) != "UTF-8") {
            $js = mb_convert_encoding($js, "UTF-8");
        }
        if (stripos($response_header, "404 Not Found") !== false) {
            continue;
        }
        $js = "/* FILE: {$f} */\n{$js}";
        if (!isset($GLOBALS['nominify'])) {
            try {
                $code .= jsmin::minify($js) . "\n";
            } catch (Exception $ex) {
                WdfException::Log("EXCEPTION occured in jsmin::minify ({$js})", $ex);
                $code .= $js . "\n";
            }
        } else {
            $code .= $js . "\n";
        }
    }
    global $ext_resources;
    foreach (array_unique($ext_resources) as $ext) {
        $code .= "\$.getScript('{$ext}', function(){ wdf.debug('external script loaded:','{$ext}'); });";
    }
    file_put_contents($target_file, $code);
}
Example #15
0
 private function __toTypedValue($column_name, $value)
 {
     if (isset(self::$_typeMap[$this->_cacheKey][$column_name])) {
         $t = self::$_typeMap[$this->_cacheKey][$column_name];
     } else {
         $t = $this->__typeOf($column_name);
     }
     switch ($t) {
         case 'int':
         case 'integer':
             return intval($value);
         case 'float':
         case 'double':
             return floatval($value);
         case 'date':
         case 'time':
         case 'datetime':
         case 'timestamp':
             try {
                 return Model::EnsureDateTime($value);
             } catch (Exception $ex) {
                 WdfException::Log("date/time error with value '{$value}'", $ex);
             }
             break;
     }
     return $value;
 }
Example #16
0
 static function SetDataObject(&$obj)
 {
     if ($obj instanceof ITimeframeDataobject) {
         $GLOBALS['timeframe']['data_object'] = $obj;
     } else {
         WdfException::Raise("Trying to set an invalid dataobject. ITimeframeDataobject needed!");
     }
 }
Example #17
0
/**
 * Returns the first property of an object that is available.
 * 
 * See <ifnull> for a detailed description as this works the same way.
 * Difference is that this only checks against null but also if a value is set (weak comparison against false).
 * @return mixed The first set value or null of none found
 */
function ifavail()
{
    $args = func_get_args();
    $data = array_shift($args);
    if (count($args) == 0) {
        ScavixWDF\WdfException::Raise("ifavail needs at one argument");
    }
    if (is_array($data)) {
        $data = (object) $data;
    }
    if (!is_object($data)) {
        foreach (func_get_args() as $arg) {
            if ($arg) {
                return $arg;
            }
        }
        return null;
    }
    foreach ($args as $n) {
        if (avail($data, $n)) {
            return $data->{$n};
        }
    }
    return null;
}
 /**
  * Calculates the age in x
  * 
  * Depending on $unit returns the age of the object in years, months, days, hours, minutes or secods.
  * @param string $unit Values: sec, min, hour, day, weeks, month, year
  * @param DateTimeEx $zero_point The point in time this DateTimeEx object shall be compared to. Defaults to <DateTimeEx::Now>()
  * @return float The calculated age
  */
 public function Age($unit, $zero_point = false)
 {
     $now = $zero_point ? $zero_point : self::Now();
     $factor = $this > $now ? -1 : 1;
     $diff = $now->diff($this);
     switch ($unit) {
         case self::YEARS:
             return $factor * $diff->y;
         case self::MONTHS:
             return $factor * ($diff->y * 12 + $diff->m);
         case self::DAYS:
             return $factor * $diff->days;
         case self::HOURS:
             return $factor * ($diff->days * 24 + $diff->h);
         case self::MINUTES:
             return $factor * ($diff->days * 1440 + $diff->h * 60 + $diff->i);
         case self::SECONDS:
             return $factor * ($diff->days * 86400 + $diff->h * 3600 + $diff->i * 60 + $diff->s);
     }
     WdfException::Raise("Getting the age is not possible in unit '{$unit}'");
 }
Example #19
0
 private function Unser_Inner()
 {
     $orig_line = array_shift($this->Lines);
     if ($orig_line == "") {
         return null;
     }
     $type = $orig_line[0];
     $line = substr($orig_line, 2);
     if ($type == 'k' || $type == 'f' || $type == 'v') {
         $type = $line[0];
         $line = substr($line, 2);
     }
     try {
         switch ($type) {
             case 's':
                 return str_replace("\\n", "\n", $line);
             case 'i':
                 return intval($line);
             case 'a':
                 $res = array();
                 for ($i = 0; $i < $line; $i++) {
                     $key = $this->Unser_Inner();
                     $res[$key] = $this->Unser_Inner();
                 }
                 return $res;
             case 'd':
                 if (!$line) {
                     return null;
                 }
                 return new DateTime($line);
             case 'x':
                 if (!$line) {
                     return null;
                 }
                 return new DateTimeEx($line);
             case 'y':
                 return new WdfReflector($line);
             case 'z':
                 return simplexml_load_string(stripcslashes($line));
             case 'o':
                 list($id, $len, $type, $alias) = explode(':', $line);
                 $datasource = $alias ? model_datasource($alias) : null;
                 $this->Stack[$id] = new $type($datasource);
                 for ($i = 0; $i < $len; $i++) {
                     $field = $this->Unser_Inner();
                     if ($field == "") {
                         continue;
                     }
                     $this->Stack[$id]->{$field} = $this->Unser_Inner();
                 }
                 if (system_method_exists($this->Stack[$id], '__wakeup')) {
                     $this->Stack[$id]->__wakeup();
                 }
                 return $this->Stack[$id];
             case 'r':
                 if (!isset($this->Stack[intval($line)])) {
                     WdfException::Raise("Trying to reference unknown object.");
                 }
                 if ($this->Stack[intval($line)] instanceof DataSource) {
                     return model_datasource($this->Stack[intval($line)]->_storage_id);
                 }
                 return $this->Stack[intval($line)];
             case 'm':
                 return model_datasource($line);
             case 'n':
                 return null;
             case 'f':
                 return floatval($line);
             case 'b':
                 return $line == 1;
             default:
                 WdfException::Raise("Unserialize found unknown datatype '{$type}'. Line was {$orig_line}");
         }
     } catch (Exception $ex) {
         WdfException::Log($ex);
         return null;
     }
 }
/**
 * Checks if a config is set and throws an exception if not.
 * 
 * Last argument will be used as exception message.
 * See cfg_set() for usage and performance thoughts
 * @return void
 */
function cfg_check()
{
    global $CONFIG;
    $args = func_get_args();
    switch (func_num_args()) {
        case 2:
            if (!isset($CONFIG[$args[0]]) || !$CONFIG[$args[0]]) {
                WdfException::Raise($args[1]);
            }
            break;
        case 3:
            if (!isset($CONFIG[$args[0]][$args[1]]) || !$CONFIG[$args[0]][$args[1]]) {
                WdfException::Raise($args[2]);
            }
            break;
        case 4:
            if (!isset($CONFIG[$args[0]][$args[1]][$args[2]]) || $CONFIG[$args[0]][$args[1]][$args[2]]) {
                WdfException::Raise($args[3]);
            }
            break;
        case 5:
            if (!isset($CONFIG[$args[0]][$args[1]][$args[2]][$args[3]]) || $CONFIG[$args[0]][$args[1]][$args[2]][$args[3]]) {
                WdfException::Raise($args[4]);
            }
            break;
        case 6:
            if (!isset($CONFIG[$args[0]][$args[1]][$args[2]][$args[3]][$args[4]]) || !$CONFIG[$args[0]][$args[1]][$args[2]][$args[3]][$args[4]]) {
                WdfException::Raise($args[5]);
            }
            break;
        case 7:
            if (!isset($CONFIG[$args[0]][$args[1]][$args[2]][$args[3]][$args[4]][$args[5]]) || !$CONFIG[$args[0]][$args[1]][$args[2]][$args[3]][$args[4]][$args[5]]) {
                WdfException::Raise($args[6]);
            }
            break;
        default:
            WdfException::Raise("Illegal argument count: " . count($args));
    }
}
/**
 * Returns true if an object's/array's property/key is set.
 * 
 * <avail> is a shorthand function to recursively check if an object property or array key is present and set.
 * It needs at least two arguments: The object/array to check and a property/key to check. If you want to check
 * more deeply just add more arguments.
 * In fact using avail is equivalent to using <isset> and `== true`.
 * See this sample and you will understand:
 * <code php>
 * $o = new stdClass();
 * $o->attributes = new stdClass();
 * $o->attributes->url = 'http://www.scavix.com';
 * $a = array();
 * $a['system']['atad'] = 'wrong order';
 * if( avail($o,'attributes','url') )
 *     log_debug("URL",$o->attributes->url);
 * if( isset($o) && is_object($o->attributes) && isset($o->attributes->url) && $o->attributes->url )
 *     log_debug("URL",$o->attributes->url);
 * if( avail($a,'system','data') )
 *     log_debug("SysData",$a['system']['data']);
 * if( isset($a) && is_array($a['system']) && isset($a['system']['data']) && $a['system']['data'] )
 *     log_debug("SysData",$a['system']['data']);
 * </code>
 * @return boolean True if the requested data is available, else false
 */
function avail()
{
    $args = func_get_args();
    if (count($args) < 2) {
        ScavixWDF\WdfException::Raise("avail needs at least two arguments");
    }
    $ar = array_shift($args);
    if (!is_array($ar) && !is_object($ar)) {
        return false;
    }
    $ar = (array) $ar;
    $l = array_pop($args);
    foreach ($args as $a) {
        if (!isset($ar[$a])) {
            return false;
        }
        if (!is_array($ar[$a]) && !is_object($ar[$a])) {
            return false;
        }
        $ar = (array) $ar[$a];
    }
    if (!isset($ar[$l])) {
        return false;
    }
    return $ar[$l] == true;
    // note the weak comparision!
}
 /**
  * Converts a datetime value to this objects timezone
  * 
  * @param mixed $date Date as string, integer or <DateTime>
  * @return int Converted time
  */
 function GetTimezoneDate($date)
 {
     $date = $this->_ensureTimeStamp($date);
     if (!isset($this->TimeZone) || !$this->TimeZone) {
         return $date;
     }
     $dt = new DateTime(date('Y-m-d H:i:s', $date));
     try {
         $tz = new DateTimeZone($this->TimeZone);
         $dt->setTimezone($tz);
     } catch (Exception $ex) {
         $this->TimeZone = "";
         WdfException::Log($ex);
     }
     return strtotime($dt->format('Y-m-d H:i:s'));
 }
Example #23
0
/**
 * Creates a named lock.
 * 
 * This is useful in some special cases where different PHP processes are creating for example datasets that must be
 * unique. So use it like this:
 * <code php>
 * system_get_lock('creating_something');
 * // do critical things
 * system_release_lock('creating_something');
 * </code>
 * Note that `system_get_lock` will check all existent locks if the processes that created them are still running
 * by using <system_process_running>(). That one depends on <shell_exec>() so make sure it is not disabled.
 * Another note to the datasource argument: This defaults to 'internal' and the 'internal' datasource defaults to 'sqlite:memory'.
 * So if you dont change this the locks will have no effect beyond process bounds!
 * @param string $name A name for the lock.
 * @param mixed $datasource Name of datasource to use or <DataSource> object itself.
 * @param int $timeout Timeout in seconds (an Exception will be thrown on timeout). If <=0 will return immediately true|false
 * @return void|bool Returns true|false only if $timeout is <=0. Else will return nothing or throw an exception
 */
function system_get_lock($name, $datasource = 'internal', $timeout = 10)
{
    $ds = $datasource instanceof DataSource ? $datasource : model_datasource($datasource);
    $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS wdf_locks(lockname VARCHAR(50) NOT NULL, pid INT UNSIGNED NOT NULL, PRIMARY KEY (lockname))");
    $start = microtime(true);
    $args = array($name, getmypid());
    do {
        if (isset($cnt)) {
            usleep(100000);
            if (microtime(true) - $start > $timeout) {
                WdfException::Raise("Timeout while awaiting the lock '{$name}'");
            }
        }
        foreach ($ds->ExecuteSql("SELECT pid FROM wdf_locks")->Enumerate('pid') as $pid) {
            if (!system_process_running($pid)) {
                $ds->ExecuteSql("DELETE FROM wdf_locks WHERE pid=?", $pid);
            }
        }
        $ds->ExecuteSql("INSERT OR IGNORE INTO wdf_locks(lockname,pid)VALUES(?,?)", $args);
        $cnt = $ds->getAffectedRowsCount();
        if ($cnt == 0 && $timeout <= 0) {
            return false;
        }
    } while ($cnt == 0);
    return true;
}
Example #24
0
 /**
  * Adds this Renderable before another Renderable.
  * 
  * In fact it will be inserted before the other Renderable into the other Renderables parent.
  * @param Renderable $target Object of type <Renderable>
  * @return Renderable `$this`
  */
 function insertBefore($target)
 {
     if ($target instanceof Renderable) {
         $target->par()->insert($this, $target);
     } else {
         WdfException::Raise("Target must be of type Renderable");
     }
     return $this;
 }
Example #25
0
/**
 * Returns the timezone for an IP address.
 * 
 * @param string $ip IP address to check (defaults to <get_ip_address>)
 * @return string Timezone identifier or false on error
 */
function get_timezone_by_ip($ip = false)
{
    if ($ip === false) {
        $ip = $GLOBALS['current_ip_addr'];
    }
    if (starts_with($ip, "1.1 ") || starts_with($ip, "192.168.")) {
        return false;
    }
    $key = "get_timezone_by_ip." . getAppVersion('nc') . "-" . $ip;
    $ret = cache_get($key);
    if ($ret) {
        return $ret;
    }
    /*
    	// new url with api key:
    	$url = "https://api.ipinfodb.com/v3/ip-city/?key=ae4dea477cd8a36cc678c582c3f990fb57a5aae696f878b4e0eee70afa53bf1e&ip=".$GLOBALS['current_ip_addr']."&format=xml";
    	try
    	{
    		$xml = downloadData($url, false, false, 60 * 60, 2);
    	}catch(Exception $ex){ WdfException::Log("Unable to get Timezone for ".$ip." ($url)",$ex); return false; }
    	if( preg_match_all('/<timeZone>([^<]*)<\/timeZone>/', $xml, $zone, PREG_SET_ORDER) )
    	{
    		$zone = $zone[0];
    		if($zone[1] != "")
    		{
                cache_set($key,$zone[1], 24 * 60 * 60);
    			return $zone[1];
    		}
    	}
    //	log_error("No timezone found for ".$GLOBALS['current_ip_addr']." via ipinfodb.com");
    */
    $url = "http://ip-api.com/php/" . $ip;
    try {
        $data = @unserialize(downloadData($url, false, false, 60 * 60, 2));
    } catch (Exception $ex) {
        WdfException::Log("Unable to get Timezone for " . $ip . " ({$url}) " . $ex->getMessage(), $ex);
        return false;
    }
    if ($data && $data['status'] == 'success') {
        $zone = $data['timezone'];
        cache_set($key, $zone, 24 * 60 * 60);
        return $zone;
    }
    log_error("No timezone found for " . $ip . " via ip-api.com");
    $coords = get_coordinates_by_ip($ip);
    if ($coords === false) {
        log_error("No timezone found for IP " . $ip . " (missing coordinates)");
        // disaster-fallback: use our timezone:
        return "Etc/GMT+2";
    }
    // ALTERNATIVE 1:
    //	ws.geonames.org had only timeouts on 2/10/2010...
    //	$url = "http://ws.geonames.org/timezone?lat=".$coords['latitude'].'&lng='.$coords['longitude'];
    $url = "http://api.geonames.org/timezone?lat=" . $coords['latitude'] . '&lng=' . $coords['longitude'] . "&username=scavix";
    try {
        $xml = downloadData($url, false, false, 60 * 60, 2);
    } catch (Exception $ex) {
        WdfException::Log("Unable to get Timezone for " . $ip . " ({$url}) " . $ex->getMessage(), $ex);
        return false;
    }
    if (preg_match_all('/<timezoneId>([^<]*)<\\/timezoneId>/', $xml, $zone, PREG_SET_ORDER)) {
        $zone = $zone[0];
        cache_set($key, $zone[1], 24 * 60 * 60);
        return $zone[1];
    }
    log_error("No timezone found for " . $ip . " via geonames.org");
    // ALTERNATIVE 2:
    $url = "http://www.earthtools.org/timezone/" . $coords['latitude'] . '/' . $coords['longitude'];
    try {
        $xml = downloadData($url, false, false, 60 * 60, 2);
    } catch (Exception $ex) {
        WdfException::Log("Unable to get Timezone for " . $ip . " ({$url})", $ex);
        return false;
    }
    if (preg_match_all('/<offset>([^<]*)<\\/offset>/', $xml, $zone, PREG_SET_ORDER)) {
        $zone = $zone[0];
        $zone[1] = round($zone[1], 0);
        $ret = "Etc/GMT" . ($zone[1] < 0 ? $zone[1] : "+" . $zone[1]);
        cache_set($key, $ret, 24 * 60 * 60);
        return $ret;
    }
    log_error("No timezone found for " . $ip . " via earthtools.org");
    // disaster-fallback: use our timezone:
    return "Etc/GMT+2";
}
Example #26
0
/**
 * Gets a list of all keys in the cache.
 * 
 * @return array list of all keys
 */
function globalcache_list_keys()
{
    if (!hook_already_fired(HOOK_POST_INIT)) {
        return array();
    }
    global $CONFIG;
    switch ($CONFIG['globalcache']['CACHE']) {
        case globalcache_CACHE_DB:
            $ds = model_datasource($CONFIG['globalcache']['datasource']);
            try {
                $rs = $ds->ExecuteSql("SELECT full_key FROM wdf_cache WHERE (valid_until IS NULL OR valid_until>=" . $ds->Driver->Now() . ")");
                return $rs->Enumerate('full_key');
            } catch (Exception $ex) {
            }
            return array();
        case globalcache_CACHE_APC:
            $ret = array();
            $cacheinfo = apc_cache_info('user');
            $keyprefixlen = strlen($GLOBALS["globalcache_key_prefix"]);
            foreach ($cacheinfo['cache_list'] as $cacheentry) {
                $ret[] = substr($cacheentry['info'], $keyprefixlen);
            }
            return $ret;
            break;
        default:
            WdfException::Log("globalcache_list_keys not implemented for handler {$CONFIG['globalcache']['CACHE']}");
            break;
    }
    return array();
}
 /**
  * @override
  */
 function WdfRender()
 {
     $tempvars = system_render_object_tree($this->get_vars());
     foreach ($GLOBALS as $key => &$val) {
         ${$key} = $val;
     }
     $buf = array();
     foreach ($tempvars as $key => &$val) {
         if (isset(${$key})) {
             $buf[$key] = ${$key};
         }
         ${$key} = $val;
     }
     if ($this instanceof HtmlPage && stripos($this->file, "htmlpage.tpl.php") !== false) {
         $__template_file = __autoload__template($this, $this->SubTemplate ? $this->SubTemplate : "");
         if ($__template_file === false) {
             WdfException::Raise("SubTemplate for class '" . get_class($this) . "' not found: " . $this->file, $this->SubTemplate);
         }
         if (stripos($__template_file, "htmlpage.tpl.php") === false) {
             ob_start();
             require $__template_file;
             $sub_template_content = ob_get_contents();
             ob_end_clean();
         }
         $this->file = __DIR__ . "/htmlpage.tpl.php";
     }
     $__template_file = __autoload__template($this, $this->file);
     if ($__template_file === false) {
         WdfException::Raise("Template for class '" . get_class($this) . "' not found: " . $this->file);
     }
     ob_start();
     require $__template_file;
     $contents = ob_get_contents();
     ob_end_clean();
     foreach ($tempvars as $key => &$val) {
         unset(${$key});
     }
     foreach ($buf as $key => &$val) {
         ${$key} = $val;
     }
     if (system_is_ajax_call() && count($this->_script) > 0) {
         $contents .= "<script> " . implode("\n", $this->_script) . "</script>";
     }
     return $contents;
 }
Example #28
0
 /**
  * Ensures object validity
  * 
  * Calls <store_object> for every <Renderable> object in the object store to ensure that the stored 
  * objects really match the serialized ones. This is needed because fields/properties can change after
  * the initial save and our caching will hide that from system.
  * 
  * No need to call this manually, ScavixWDF will do!
  * @return void
  */
 function Update()
 {
     global $CONFIG;
     $_SESSION[$CONFIG['session']['prefix'] . "session_lastaccess"] = time();
     foreach ($GLOBALS['object_storage'] as $id => &$obj) {
         try {
             if ($obj instanceof Renderable) {
                 store_object($obj, $id);
             }
         } catch (Exception $ex) {
             WdfException::Log("updating session storage for object {$id} [" . get_class($obj) . "]", $ex);
         }
     }
 }
Example #29
0
/**
 * Sends an email.
 * 
 * @param mixed $recipient Email recipient as string. If $recipient is <PHPMailer> will ignore all other arguments and use this.
 * @param string $subject The subject
 * @param string $message The message (may be HTML formatted)
 * @param string $plainmessage Optional plain message (may differ from $message)
 * @param array $attachments Array of filenames to attach
 * @return boolean true on success or string on error
 */
function mail_send($recipient, $subject = "", $message = "", $plainmessage = "", $attachments = array())
{
    if (is_object($recipient) && $recipient instanceof PHPMailer) {
        $mail = $recipient;
    } else {
        $mail = mail_prepare($recipient, $subject, $message, $plainmessage, $attachments);
    }
    $res = false;
    try {
        $res = $mail->Send();
    } catch (Exception $ex) {
        WdfException::Log($ex);
        $res = false;
    }
    if (!$res) {
        log_trace("mail_send({$subject},{$message}): " . $mail->ErrorInfo, $recipient);
        return $mail->ErrorInfo;
    }
    return true;
}
Example #30
0
 /**
  * Adds a data object to the current row.
  * 
  * This will be stored for AJAX acceess
  * @param mixed $model Data object
  * @return Table `$this`
  */
 function AddDataToRow($model)
 {
     if (!$this->current_row) {
         WdfException::Raise("No row added yet");
     }
     $this->current_row->id = $this->current_row->_storage_id;
     $this->_rowModels[$this->current_row->id] = $model;
     return $this;
 }