Esempio n. 1
0
 /**
  * @attribute[RequestParam('title','string')]
  * @attribute[RequestParam('body','string')]
  */
 function AddPost($title, $body)
 {
     log_debug("Add Post");
     $ds = model_datasource('system');
     $ds->ExecuteSql("INSERT INTO blog(title,body)VALUES(?,?)", array($title, $body));
     redirect('blog', 'index');
 }
Esempio n. 2
0
 /**
  * Shows product details
  * @attribute[RequestParam('id','int')]
  */
 function Details($id)
 {
     // check if product really exists
     $ds = model_datasource('system');
     $prod = $ds->Query('products')->eq('id', $id)->current();
     if (!$prod) {
         redirect('Products', 'Index', array('error' => 'Product not found'));
     }
     // create a template with product details
     $this->content(Template::Make('product_details'))->set('title', $prod->title)->set('description', $prod->body)->set('image', resFile($prod->image))->set('link', buildQuery('Basket', 'Add', array('id' => $prod->id)));
 }
Esempio n. 3
0
/**
 * Creates a all tables and some sample data.
 */
function ensure_db()
{
    $flds = array();
    foreach (array('email', 'fname', 'lname', 'street', 'zip', 'city') as $fld) {
        $flds[] = "{$fld} VARCHAR(255)";
    }
    $flds = implode(",", $flds);
    $ds = model_datasource('system');
    $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS products(id INTEGER,title VARCHAR(50),tagline VARCHAR(100),body TEXT,image VARCHAR(50),price DOUBLE,PRIMARY KEY(id))");
    $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS orders(id INTEGER,customer_id INTEGER,status INTEGER,created DATETIME,updated DATETIME,completed DATETIME,deleted DATETIME,price_total DOUBLE,PRIMARY KEY(id))");
    $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS items(id INTEGER,order_id INTEGER,title VARCHAR(50),tagline VARCHAR(100),body TEXT,price DOUBLE,amount DOUBLE,PRIMARY KEY(id))");
    $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS customers(id INTEGER,{$flds},PRIMARY KEY(id))");
    if ($ds->ExecuteScalar("SELECT count(*) FROM products") == 0) {
        $ds->ExecuteSql("INSERT INTO products(title,tagline,body,image,price)VALUES(?,?,?,?,?)", array('Product 1', 'This is short desc for product 1', 'Here we go with an real description that can be long and will only be displayed on products details page', 'product1.png', 11.99));
        $ds->ExecuteSql("INSERT INTO products(title,tagline,body,image,price)VALUES(?,?,?,?,?)", array('Product 2', 'Product 2 has a tagline too', 'But we will go with a short description', 'product2.png', 9.85));
        $ds->ExecuteSql("INSERT INTO products(title,tagline,body,image,price)VALUES(?,?,?,?,?)", array('Product 3', 'Product 3 tagline: we need that for listings', 'No desc here too as this is demo data', 'product3.png', 1.99));
    }
}
 /**
  * @internal Delete a string
  * @attribute[RequestParam('term','string')]
  */
 function DeleteString($term)
 {
     $ds = model_datasource($GLOBALS['CONFIG']['translation']['sync']['datasource']);
     $ds->ExecuteSql("DELETE FROM wdf_unknown_strings WHERE term=?", $term);
     return AjaxResponse::None();
 }
 /**
  * @internal Fetch action handler
  * @attribute[RequestParam('languages','array',false)]
  */
 function Fetch($languages = false)
 {
     global $CONFIG;
     $this->_contentdiv->content("<h1>Fetch strings</h1>");
     $response = $this->request(array('action' => 'list_languages'));
     if (!$languages) {
         $div = $this->_contentdiv->content(new Form());
         foreach ($response->list as $lang) {
             $cb = $div->content(new CheckBox('languages[]'));
             $cb->value = $lang->code;
             $div->content($cb->CreateLabel($lang->name . " ({$lang->code}, {$lang->percentage}% complete)"));
             $div->content("<br/>");
         }
         $a = $div->content(new Anchor('#', 'Select all'));
         $a->script("\$('#{$a->id}').click(function(){ \$('input','#{$div->id}').attr('checked',true); });");
         $div->content("&nbsp;&nbsp;");
         $div->AddSubmit("Fetch");
         $pid = $GLOBALS['CONFIG']['translation']['sync']['poeditor_project_id'];
         $div->content("<br/><a href='http://poeditor.com/projects/view?id={$pid}' target='_blank'>Open POEditor.com</a>");
         return;
     }
     $head = array();
     foreach ($response->list as $lang) {
         $head[$lang->code] = array('percentage_complete' => $lang->percentage / 100, 'percentage_empty' => 1 - $lang->percentage / 100, 'syntax_error_qty' => 0);
     }
     $info = "\$GLOBALS['translation']['properties'] = " . var_export($head, true);
     $defaults = $this->fetchTerms($CONFIG['localization']['default_language']);
     foreach (array_unique($languages) as $lang) {
         $lang = strtolower($lang);
         $data = $lang == $CONFIG['localization']['default_language'] ? $defaults : $this->fetchTerms($lang, $defaults);
         $strings = "\$GLOBALS['translation']['strings'] = " . var_export($data, true);
         file_put_contents($CONFIG['translation']['data_path'] . $lang . '.inc.php', "<?php\n{$info};\n{$strings};\n");
         $this->_contentdiv->content("<div>Created translation file for {$lang}</div>");
     }
     $ds = model_datasource($GLOBALS['CONFIG']['translation']['sync']['datasource']);
     $ds->ExecuteSql("TRUNCATE TABLE wdf_unknown_strings");
     $this->_contentdiv->content("<div>Cleared the unknown strings table</div>");
     foreach (cache_list_keys() as $key) {
         if (starts_with($key, 'lang_')) {
             cache_del($key);
         }
     }
     $this->_contentdiv->content("<div>Cleared the string cache</div>");
 }
Esempio n. 6
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();
}
Esempio n. 7
0
 /**
  * Creates a ResultSet from a serialized data string
  * 
  * This is mainly needed for query caching
  * @param string $data serialized data string
  * @return ResultSet Restored ResultSet object
  */
 static function &unserialize($data)
 {
     $buf = unserialize($data);
     $res = new ResultSet(model_datasource($buf['ds']), null);
     $res->_sql_used = $buf['sql'];
     $res->_arguments_used = $buf['args'];
     $res->_paging_info = $buf['paging_info'];
     $res->_field_types = $buf['field_types'];
     $res->_index = $buf['index'];
     $res->_rowbuffer = $buf['rows'];
     $res->_rowCount = isset($buf['rowCount']) ? $buf['rowCount'] : false;
     $res->_loaded_from_cache = true;
     $res->_data_fetched = isset($buf['df']) ? $buf['df'] : false;
     if (isset($res->_rowbuffer[$res->_index])) {
         $res->_current = $res->_rowbuffer[$res->_index];
     }
     return $res;
 }
Esempio n. 8
0
/**
 * Releases a named lock.
 * 
 * See <system_get_lock>() for details about this.
 * @param string $name Name of the lock to release
 * @param mixed $datasource Name of datasource to use or <DataSource> object itself.
 * @return void
 */
function system_release_lock($name, $datasource = 'internal')
{
    $ds = $datasource instanceof DataSource ? $datasource : model_datasource($datasource);
    $ds->ExecuteSql("DELETE FROM wdf_locks WHERE lockname=?", $name);
}
 /**
  * @internal Fetch action handler
  * @attribute[RequestParam('languages','array',false)]
  */
 function Fetch($languages = false)
 {
     global $CONFIG;
     $this->_contentdiv->content("<h1>Fetch strings</h1>");
     $db_languages = $this->ds->ExecuteSql("SELECT DISTINCT lang FROM wdf_translations ORDER BY lang")->Enumerate('lang', false);
     $max = $this->ds->ExecuteScalar("SELECT MAX(cnt) FROM (SELECT count(*) as cnt FROM wdf_translations GROUP BY lang) AS x");
     foreach ($db_languages as $i => $lang) {
         $count = $this->ds->ExecuteScalar("SELECT count(*) FROM wdf_translations WHERE lang=?", $lang);
         $db_languages[$i] = new stdClass();
         $db_languages[$i]->name = Localization::getCultureInfo($lang)->EnglishName;
         $db_languages[$i]->code = $lang;
         $db_languages[$i]->percentage = round($count / $max * 100, 0);
     }
     if (!$languages) {
         $div = $this->_contentdiv->content(new Form());
         foreach ($db_languages as $lang) {
             $cb = $div->content(new CheckBox('languages[]'));
             $cb->value = $lang->code;
             $div->content($cb->CreateLabel($lang->name . " ({$lang->code}, {$lang->percentage}% complete)"));
             $div->content("<br/>");
         }
         $a = $div->content(new Anchor('#', 'Select all'));
         $a->script("\$('#{$a->id}').click(function(){ \$('input','#{$div->id}').attr('checked',true); });");
         $div->content("&nbsp;&nbsp;");
         $div->AddSubmit("Fetch");
         return;
     }
     $head = array();
     foreach ($db_languages as $lang) {
         $head[$lang->code] = array('percentage_complete' => $lang->percentage / 100, 'percentage_empty' => 1 - $lang->percentage / 100, 'syntax_error_qty' => 0);
     }
     $info = "\$GLOBALS['translation']['properties'] = " . var_export($head, true);
     $defaults = $this->fetchTerms($CONFIG['localization']['default_language']);
     foreach (array_unique($languages) as $lang) {
         $lang = strtolower($lang);
         $data = $lang == $CONFIG['localization']['default_language'] ? $defaults : $this->fetchTerms($lang, $defaults);
         $strings = "\$GLOBALS['translation']['strings'] = " . var_export($data, true);
         file_put_contents($CONFIG['translation']['data_path'] . $lang . '.inc.php', "<?php\n{$info};\n{$strings};\n");
         $this->_contentdiv->content("<div>Created translation file for {$lang}</div>");
     }
     $ds = model_datasource($GLOBALS['CONFIG']['translation']['sync']['datasource']);
     $ds->ExecuteSql("TRUNCATE TABLE wdf_unknown_strings");
     $this->_contentdiv->content("<div>Cleared the unknown strings table</div>");
     foreach (cache_list_keys() as $key) {
         if (starts_with($key, 'lang_')) {
             cache_del($key);
         }
     }
     $this->_contentdiv->content("<div>Cleared the string cache</div>");
 }
Esempio n. 10
0
 function __wakeup_extended()
 {
     $name = explode("::", $this->_storage_id, 2);
     if (count($name) < 2) {
         $name = array($this->_storage_id, $this->_storage_id);
     }
     $ds = model_datasource($name[1]);
     $this->_storage_id = $ds->_storage_id;
     $this->_dsn = $ds->_dsn;
     $this->_username = $ds->_username;
     $this->_password = $ds->_password;
     $this->_pdo = $ds->_pdo;
     $this->Driver = $ds->Driver;
     log_debug($this->_storage_id . " -> " . $this->Database(), "HOOK::__wakeup_extended");
 }
Esempio n. 11
0
 function __construct($datasource = null)
 {
     $this->_className = get_class($this);
     $this->_isInherited = $this->_className != "Model";
     if (!$datasource) {
         if (!self::$DefaultDatasource) {
             $aliases = array_keys($GLOBALS['MODEL_DATABASES']);
             self::$DefaultDatasource = model_datasource(array_pop($aliases));
         }
         if (self::$DefaultDatasource) {
             $this->__initialize(self::$DefaultDatasource);
         } else {
             $this->__initialize();
         }
     } else {
         $this->__initialize($datasource);
     }
 }
Esempio n. 12
0
 /**
  * @attribute[RequestParam('table','string',false)]
  * @attribute[RequestParam('action','string',false)]
  * @attribute[RequestParam('model','array',false)]
  * @attribute[RequestParam('row','string',false)]
  */
 function DelProduct($table, $action, $model, $row)
 {
     $this->_login();
     // require admin to be logged in
     // we use the ajax confirm features of the framework which require some translated string, so we set them up here
     // normally we would start the sysadmin and create some, but for this sample we ignore that.
     default_string('TITLE_DELPRODUCT', 'Delete Product');
     default_string('TXT_DELPRODUCT', 'Do you really want to remove this product? This cannot be undone!');
     if (!AjaxAction::IsConfirmed('DELPRODUCT')) {
         return AjaxAction::Confirm('DELPRODUCT', 'Admin', 'DelProduct', array('model' => $model));
     }
     // load and delete the product dataset
     $ds = model_datasource('system');
     $prod = $ds->Query('products')->eq('id', $model['id'])->current();
     $prod->Delete();
     // delete the image too if present
     if ($prod->image) {
         $image = __DIR__ . '/../images/' . $prod->image;
         if (file_exists($image)) {
             unlink($image);
         }
     }
     return AjaxResponse::Redirect('Admin');
 }
Esempio n. 13
0
 function __constrruct()
 {
     parent::__construct();
     $this->ds = model_datasource($CONFIG['session']['datasource']);
 }
Esempio n. 14
0
 /**
  * @override
  */
 public function HandleReturnFromPP($ipndata)
 {
     global $CONFIG;
     foreach (array("totalAmount", "currency", "responseTimeStamp", "PPP_TransactionID", "Status", "productId", "advanceResponseChecksum") as $k => $v) {
         if (!isset($ipndata[$v])) {
             log_error("Gate2Shop: Missing IPN parameter: {$v}");
             return false;
         }
     }
     // check checksum
     $checksum = md5($CONFIG["payment"]["gate2shop"]["secret_key"] . $ipndata["totalAmount"] . $ipndata["currency"] . $ipndata["responseTimeStamp"] . $ipndata["PPP_TransactionID"] . $ipndata["Status"] . $ipndata["productId"]);
     //		log_debug($checksum." -> ".$CONFIG["payment"]["gate2shop"]["secret_key"]."-".$ipndata["ppp_status"]."-".$ipndata["PPP_TransactionID"]);
     if ($checksum != $ipndata["advanceResponseChecksum"]) {
         log_error("Gate2Shop: Checksum don't consist with response");
         return false;
     }
     $order_id = $ipndata["invoice_id"];
     if (starts_with($order_id, $CONFIG["invoices"]["invoice_id_prefix"])) {
         $order_id = trim(str_replace($CONFIG["invoices"]["invoice_id_prefix"], "", $order_id));
     }
     $ds = model_datasource('system');
     $order = $ds->CreateInstance("ShopOrder");
     if (!$order->Load("id=?", $order_id)) {
         return "Order id {$order_id} not found";
     }
     // order not found
     return $this->HandlePayment($order, $ipndata);
 }
Esempio n. 15
0
/**
 * @internal Used to add some new/unknown strings to the translation system
 */
function translation_add_unknown_strings($unknown_constants)
{
    global $CONFIG;
    if ($CONFIG['translation']['sync']['datasource']) {
        $ds = model_datasource($CONFIG['translation']['sync']['datasource']);
        $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS wdf_unknown_strings (\n\t\t\tterm VARCHAR(150) NOT NULL,\n\t\t\tlast_hit DATETIME NOT NULL,\n\t\t\thits INT DEFAULT 0,\n\t\t\tdefault_val TEXT,\n\t\t\tPRIMARY KEY (term))");
        $now = $ds->Driver->Now();
        $sql1 = "INSERT OR IGNORE INTO wdf_unknown_strings(term,last_hit,hits,default_val)VALUES(?,{$now},0,?);";
        $sql2 = "UPDATE wdf_unknown_strings SET last_hit={$now}, hits=hits+1 WHERE term=?;";
        foreach ($unknown_constants as $uc) {
            $def = cfg_getd('translation', 'default_strings', $uc, '');
            $ds->Execute($sql1, array($uc, $def));
            $ds->Execute($sql2, $uc);
        }
    } else {
        log_debug("Unknown text constants: " . render_var(array_values($unknown_constants)));
    }
}
Esempio n. 16
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;
     }
 }
 function ParticipantsCountries()
 {
     $chart = new gvGeoChart();
     $chart->setTitle("Participants countries")->setDataHeader("Country", "Participants")->setSize(800, 400)->opt('is3D', true);
     $country_names = Localization::get_country_names();
     foreach (model_datasource('system')->ExecuteSql("SELECT country, count(*) as cnt FROM participants GROUP BY country ORDER BY cnt DESC") as $row) {
         $chart->addDataRow($country_names[$row['country']], intval($row['cnt']));
     }
     return $chart;
 }
Esempio n. 18
0
 /**
  * Persists current basket to the database and starts checkout process.
  * @attribute[RequestParam('fname','string')]
  * @attribute[RequestParam('lname','string')]
  * @attribute[RequestParam('street','string')]
  * @attribute[RequestParam('zip','string')]
  * @attribute[RequestParam('city','string')]
  * @attribute[RequestParam('email','string')]
  * @attribute[RequestParam('provider','string')]
  */
 function StartCheckout($fname, $lname, $street, $zip, $city, $email, $provider)
 {
     log_debug("StartCheckout({$fname},{$lname},{$street},{$zip},{$city},{$email},{$provider})");
     if (!$fname || !$lname || !$street || !$zip || !$city || !$email) {
         redirect('Basket', 'Index', array('error' => 'Missing some data'));
     }
     // create a new customer. note that we do not check for existance or stuff.
     // this should be part of a real shop system!
     $cust = new SampleCustomer();
     $cust->fname = $fname;
     $cust->lname = $lname;
     $cust->street = $street;
     $cust->zip = $zip;
     $cust->city = $city;
     $cust->email = $email;
     $cust->price_total = 0;
     $cust->Save();
     // create a new order and assign the customer (from above)
     $order = new SampleShopOrder();
     $order->customer_id = $cust->id;
     $order->created = 'now()';
     $order->Save();
     // now loop thru the basket-items and add them to the order...
     $ds = model_datasource('system');
     foreach ($_SESSION['basket'] as $id => $amount) {
         //... by creating a dataset for each item
         $prod = $ds->Query('products')->eq('id', $id)->current();
         $item = new SampleShopOrderItem();
         $item->order_id = $order->id;
         $item->price = $prod->price;
         $item->amount = $amount;
         $item->title = $prod->title;
         $item->tagline = $prod->tagline;
         $item->body = $prod->body;
         $item->Save();
         $order->price_total += $amount * $prod->price;
     }
     // save the order again to persist the total amount
     $order->Save();
     $_SESSION['basket'] = array();
     // finally start the checkout process using the given payment provider
     log_debug("Handing control over to payment provider '{$provider}'");
     $p = new $provider();
     $p->StartCheckout($order, buildQuery('Basket', 'PostPayment'));
 }
 /**
  * Sets the <DataSource> to be used
  * 
  * @param mixed $datasource Optional <DataSource> to use. This may also be the name of the <DataSource> to use as `string`.
  * @return GoogleVisualization `$this`
  */
 function setDataSource($datasource)
 {
     if (is_string($datasource)) {
         $this->_ds = model_datasource($datasource);
     } elseif ($datasource instanceof DataSource) {
         $this->_ds = $datasource;
     }
     return $this;
 }