Ejemplo n.º 1
0
 public function log()
 {
     $ar = func_get_args();
     $cn = \bbn\str\text::encode_filename(str_replace('\\', '_', get_class($this)));
     foreach ($ar as $a) {
         \bbn\tools::log($a, $cn);
     }
 }
Ejemplo n.º 2
0
 /**
  * Empties the structure tables for a given database and refill them with the current structure
  * 
  * @param string $db
  * @return void
  */
 public function update($db = '')
 {
     apc_clear_cache();
     apc_clear_cache("user");
     if (empty($db)) {
         $db = $this->db->current;
     }
     if (\bbn\str\text::check_name($db)) {
         $change = $this->db->current === $db ? false : $this->db->current;
         if ($change) {
             $this->db->change($db);
         }
         $schema = $this->db->modelize();
         if ($change) {
             $this->db->change($change);
         }
         /*
         $projects = [];
         $r1 = $this->db->query("SELECT *
         FROM `{$this->admin_db}`.`{$this->prefix}projects`
         WHERE `db` LIKE '$db'");
         while ( $d1 = $r1->get_row() ){
         	$projects[$d1['id']] = $d1;
         	$projects[$d1['id']]['forms'] = [];
         	$r2 = $this->db->query("
         		SELECT id
         		FROM `{$this->admin_db}`.`{$this->prefix}forms`
         		WHERE `id_project` = ?",
         		$d1['id']);
         	while ( $d2 = $r2->get_row() ){
         		$projects[$d1['id']]['forms'][$d2['id']] = $this->get_form_config();
         	}
         }
         */
         $this->db->query("DELETE IGNORE FROM `{$this->prefix}dbs` WHERE id LIKE '{$db}.%'");
         $this->db->query("DELETE IGNORE FROM `{$this->prefix}tables` WHERE id LIKE '{$db}.%'");
         $this->db->query("DELETE IGNORE FROM `{$this->prefix}columns` WHERE id LIKE '{$db}.%'");
         $this->db->query("DELETE IGNORE FROM `{$this->prefix}keys` WHERE id LIKE '{$db}.%'");
         $this->db->raw_query("\n        INSERT IGNORE INTO `{$this->admin_db}`.`{$this->prefix}dbs`\n        (`id`, `host`, `db`)\n        VALUES\n        ('{$db}', '{$this->db->host}', '{$db}')");
         $has_history = false;
         if (\bbn\appui\history::$is_used && isset($schema[\bbn\appui\history::$htable])) {
             $has_history = 1;
         }
         foreach ($schema as $t => $vars) {
             if (strpos($t, '.' . $this->prefix) === false) {
                 $tmp = explode(".", $t);
                 $db = $tmp[0];
                 $table = $tmp[1];
                 $this->db->insert_update($this->admin_db . '.' . $this->prefix . 'tables', ['id' => $t, 'db' => $db, 'table' => $table]);
                 foreach ($vars['fields'] as $col => $f) {
                     $config = new \stdClass();
                     if ($has_history && array_key_exists(\bbn\appui\history::$hcol, $vars['fields']) && $col !== \bbn\appui\history::$hcol) {
                         $config->history = 1;
                     }
                     if (isset($f['default'])) {
                         $config->default = $f['default'];
                     }
                     if (!empty($f['extra'])) {
                         $config->extra = $f['extra'];
                     }
                     if (isset($f['signed']) && $f['signed'] == 1) {
                         $config->signed = 1;
                     }
                     if (isset($f['null']) && $f['null'] == '1') {
                         $config->null = 1;
                     }
                     if (isset($f['maxlength']) && $f['maxlength'] > 0) {
                         $config->maxlength = (int) $f['maxlength'];
                     }
                     if (isset($f['keys'])) {
                         $config->keys = [];
                         foreach ($f['keys'] as $key) {
                             $config->keys[$key] = $vars['keys'][$key];
                         }
                     }
                     $this->db->insert_update($this->admin_db . '.' . $this->prefix . 'columns', ['id' => $t . '.' . $col, 'table' => $t, 'column' => $col, 'position' => $f['position'], 'type' => $f['type'], 'null' => $f['null'], 'key' => $f['key'], 'config' => json_encode($config)]);
                 }
             }
         }
         foreach ($schema as $t => $vars) {
             if (strpos($t, '.' . $this->prefix) === false) {
                 if (is_array($vars['keys'])) {
                     foreach ($vars['keys'] as $k => $arr) {
                         $pos = 1;
                         foreach ($arr['columns'] as $c) {
                             $this->db->insert_update($this->admin_db . '.' . $this->prefix . 'keys', ['id' => $t . '.' . $c . '.' . $k, 'key' => $k, 'column' => $t . '.' . $c, 'position' => $pos, 'ref_column' => is_null($arr['ref_column']) ? null : $arr['ref_db'] . '.' . $arr['ref_table'] . '.' . $arr['ref_column']]);
                             $pos++;
                         }
                     }
                 } else {
                     \bbn\tools::log($t);
                     \bbn\tools::log($vars['keys']);
                 }
             }
         }
         /*
         			foreach ( $projects as $i => $p ){
         				$this->db->insert($this->admin_db.'.'.$this->prefix.'projects',[
         					'id' => $i,
         					'id_client' => $p['id_client'],
         					'db' => $p['db'],
         					'name' => $p['name'],
         					'config' => $p['config']]);
         				foreach ( $p['forms'] as $j => $form ){
         					$this->db->insert($this->admin_db.'.'.$this->prefix.'forms',[
         						'id' => $j,
         						'id_project' => $i
         					]);
         					foreach ( $form as $field ){
         						$this->db->insert_ignore($this->admin_db.'.'.$this->prefix.'fields',[
         							'id' => $field['id'],
         							'id_form' => $j,
         							'column' => $field['column'],
         							'title' => $field['title'],
         							'position' => $field['position'],
         							'configuration' => json_encode($field['configuration'])
         						]);
         					}
         				}
         			}
         * 
         */
     }
 }
Ejemplo n.º 3
0
 /**
  * @return mixed
  */
 private function _identify($credentials)
 {
     if ($this->check_session()) {
         $this->close_session();
     }
     if (isset($credentials['user'], $credentials['pass'])) {
         // Table structure
         $arch =& $this->cfg['arch'];
         // Database Query
         if ($d = $this->db->rselect($this->cfg['tables']['users'], $this->fields, \bbn\tools::merge_arrays($this->cfg['conditions'], [$arch['users']['status'] => 1], [$arch['users']['login'] => $credentials['user']]))) {
             $this->id = $d['id'];
             $this->_user_info($d);
             // Canceling authentication if num_attempts > max_attempts
             if (!$this->check_attempts()) {
                 $this->error = 4;
             }
             $pass = $this->db->select_one($this->cfg['tables']['passwords'], $arch['passwords']['pass'], [$arch['passwords']['id_user'] => $this->id], [$arch['passwords']['added'] => 'DESC']);
             if ($this->_check_password($credentials['pass'], $pass)) {
                 $this->auth = 1;
                 $this->_login();
             } else {
                 $this->record_attempt();
                 $this->error = 6;
             }
         } else {
             $this->error = 6;
         }
     }
     return $this->auth;
 }
Ejemplo n.º 4
0
 public function log($st)
 {
     $args = func_get_args();
     foreach ($args as $a) {
         \bbn\tools::log($a, 'db');
     }
 }
Ejemplo n.º 5
0
 /**
  * The function used by the \bbn\db\connection trigger
  * This will basically execute the history query if it's configured for.
  * 
  * @param string $table The table for which the history is called
  * @param string $kind The type of action: select|update|insert|delete
  * @param string $moment The moment according to the db action: before|after
  * @param array $values key/value array of fields names and fields values selected/inserted/updated
  * @param array $where key/value array of fields names and fields values identifying the row
  * 
  * @return bool returns true
  */
 public static function trigger($table, $kind, $moment, $values = [], $where = [])
 {
     if (self::$enabled && self::check($table)) {
         $table = self::$db->table_full_name($table);
         if (!isset(self::$hstructures[$table])) {
             self::get_table_cfg($table);
         }
         if (isset(self::$hstructures[$table], self::$hstructures[$table]['history']) && self::$hstructures[$table]['history']) {
             $s =& self::$hstructures[$table];
             if (!isset($s['primary'])) {
                 \bbn\tools::dump($s);
                 die("You need to have a primary key on a single column in your table {$table} in order to use the history class");
             }
             $date = self::$date ? self::$date : date('Y-m-d H:i:s');
             if (count($values) === 1 && array_keys($values)[0] === self::$hcol) {
                 $kind = array_values($values)[0] === 1 ? 'restore' : 'delete';
             }
             switch ($kind) {
                 case 'select':
                     break;
                 case 'insert':
                     if ($moment === 'before' && isset($values[$s['primary']])) {
                         if (self::$db->select_one($table, self::$hcol, [$s['primary'] => $values[$s['primary']]]) === 0) {
                             self::$db->update($table, [self::$hcol = 1], [$s['primary'] => $values[$s['primary']]]);
                         }
                     } else {
                         if ($moment === 'after') {
                             $id = self::$db->last_id();
                             self::$db->insert(self::$htable, ['operation' => 'INSERT', 'line' => $id, 'column' => $table . '.' . $s['primary'], 'old' => null, 'last_mod' => $date, 'id_user' => self::$huser]);
                             self::$db->set_last_insert_id($id);
                         }
                     }
                     break;
                 case 'restore':
                     if ($moment === 'after') {
                         self::$db->insert(self::$htable, ['operation' => 'RESTORE', 'line' => $where[$s['primary']], 'column' => $table . '.' . self::$hcol, 'old' => '0', 'last_mod' => $date, 'id_user' => self::$huser]);
                     }
                     break;
                 case 'update':
                     if ($moment === 'before') {
                         self::$last_rows = self::$db->rselect_all($table, array_keys($values), $where);
                     } else {
                         if ($moment === 'after') {
                             if (is_array(self::$last_rows)) {
                                 foreach (self::$last_rows as $upd) {
                                     foreach ($values as $c => $v) {
                                         if (!isset($upd[$c])) {
                                             $upd[$c] = null;
                                         }
                                         if ($v !== $upd[$c] && $c !== self::$hcol && isset($s['fields'][$c]['config']['history'])) {
                                             self::$db->insert(self::$htable, ['operation' => 'UPDATE', 'line' => $where[$s['primary']], 'column' => $table . '.' . $c, 'old' => $upd[$c], 'last_mod' => $date, 'id_user' => self::$huser]);
                                         }
                                     }
                                 }
                             } else {
                                 $id = self::$db->last_id();
                                 self::$db->insert(self::$htable, ['operation' => 'INSERT', 'line' => $id, 'column' => $table . '.' . $s['primary'], 'old' => '', 'last_mod' => $date, 'id_user' => self::$huser]);
                                 self::$db->set_last_insert_id($id);
                             }
                             self::$last_rows = false;
                         }
                     }
                     break;
                 case 'delete':
                     if ($moment === 'before') {
                         // Looking for foreign constraints
                         // Nothing is really deleted, the hcol is just set to 0
                         if ($r = self::$db->query(self::$db->get_update($table, [self::$hcol], $where), 0, array_values($where)[0])) {
                             self::$db->insert(self::$htable, ['operation' => 'DELETE', 'line' => $where[$s['primary']], 'column' => $table . '.' . self::$hcol, 'old' => 1, 'last_mod' => $date, 'id_user' => self::$huser]);
                             return ['trig' => false, 'value' => $r];
                             /* For each value of this key which is deleted (hopefully one)
                                $to_check = self::$db->get_rows("
                                  SELECT k.`column` AS id, c1.`column` AS to_change, c2.`column` AS from_change,
                                  c1.`null`, t.`table`
                                  FROM `".self::$admin_db."`.`".self::$prefix."keys` AS k
                                    JOIN `".self::$prefix."columns` AS c1
                                      ON c1.`id` LIKE k.`column`
                                    JOIN `".self::$prefix."columns` AS c2
                                      ON c2.`id` LIKE k.`ref_column`
                                    JOIN `".self::$prefix."tables` AS t
                                      ON t.`id` LIKE c1.`table`
                                  WHERE k.`ref_column` LIKE ?",
                                  $table.'.%%');
                                $to_select = [self::$primary];
                                foreach ( $to_check as $c ){
                                  array_push($to_select, $c['from_change']);
                                }
                                // The values from the constrained rows that should have been deleted
                                $delete = self::$db->select_all($table, array_unique($to_select), $where);
                                foreach ( $delete as $del ){
                                  $del = (array) $del;
                                  // For each table having a constrain
                                  foreach ( $to_check as $c ){
                                    // If it's nullable we set it to null
                                    if ( $c['null'] == 1 ){
                                      self::$db->query("
                                        UPDATE `$c[table]`
                                        SET `$c[to_change]` = NULL
                                        WHERE `$c[to_change]` = ?",
                                        $del[$c['from_change']]);
                                    }
                                    // Then we "delete" it on the same manner
                                    self::$db->delete($c['table'], [ $c['to_change'] => $del[$c['from_change']] ], $date);
                                  }
                                  // Inserting a new history row for each deleted value
                                  self::$db->insert(self::$htable, [
                                    'operation' => 'DELETE',
                                    'line' => $del[$s['primary']],
                                    'column' => $table.'.'.self::$hcol,
                                    'old' => 1,
                                    'last_mod' => $date,
                                    'id_user' => self::$huser]);
                                }
                                 * 
                                 */
                         }
                     }
                     break;
             }
         }
     }
     return 1;
 }
Ejemplo n.º 6
0
 public static function sync(\bbn\db\connection $db, $dbs = '', $dbs_table = '', $num_try = 0)
 {
     if (!$num_try) {
         self::define($dbs, $dbs_table);
         self::first_call();
         self::disable();
         $mode_db = self::$db->get_error_mode();
         $mode_dbs = self::$dbs->get_error_mode();
         self::$db->set_error_mode("continue");
         self::$dbs->set_error_mode("continue");
     }
     $num_try++;
     $to_log = ['deleted_sync' => 0, 'deleted_real' => 0, 'updated_sync' => 0, 'updated_real' => 0, 'inserted_sync' => 0, 'inserted_real' => 0, 'num_problems' => 0, 'problems' => []];
     $retry = false;
     $start = ($test = self::$dbs->get_one("\n      SELECT MIN(moment)\n      FROM " . self::$dbs->escape(self::$dbs_table) . "\n      WHERE db NOT LIKE ?\n      AND state = 0", self::$db->current)) ? $test : date('Y-m-d H:i:s');
     // Deleting the entries prior to this sync we produced and have been seen by the twin process
     $to_log['deleted_sync'] = self::$dbs->delete(self::$dbs_table, [['db', 'LIKE', self::$db->current], ['state', '=', 1], ['moment', '<', $start]]);
     // Selecting the entries inserted
     $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'vals', 'moment'], [['db', 'NOT LIKE', self::$db->current], ['state', '=', 0], ['action', 'LIKE', 'insert']], ['moment' => 'ASC', 'id' => 'ASC']);
     // They just have to be inserted
     foreach ($ds as $i => $d) {
         if (isset(self::$methods['cbf1'])) {
             self::cbf1($d);
         }
         $vals = json_decode($d['vals'], 1);
         if (!is_array($vals)) {
             $to_log['num_problems']++;
             array_push($to_log['problems'], "Hey, look urgently at the row {$d['id']}!");
         } else {
             if (self::$db->insert($d['tab'], $vals)) {
                 if (isset(self::$methods['cbf2'])) {
                     self::cbf2($d);
                 }
                 $to_log['inserted_sync']++;
                 self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
             } else {
                 if (self::$db->select($d['tab'], [], $vals)) {
                     self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
                 } else {
                     if ($num_try > self::$max_retry) {
                         $to_log['num_problems']++;
                         array_push($to_log['problems'], "Problem while syncing (insert), check data with status 5 and ID " . $d['id']);
                         self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
                     }
                     $retry = 1;
                 }
             }
         }
     }
     // Selecting the entries modified and deleted in the twin DB,
     // ordered by table and rows (so the same go together)
     $ds = self::$dbs->rselect_all(self::$dbs_table, ['id', 'tab', 'action', 'rows', 'vals', 'moment'], [['db', 'NOT LIKE', self::$db->current], ['state', '=', 0], ['rows', 'NOT LIKE', '[]'], ['action', 'NOT LIKE', 'insert']], ['tab' => 'ASC', 'rows' => 'ASC', 'moment' => 'ASC', 'id' => 'ASC']);
     foreach ($ds as $i => $d) {
         // Executing the first callback
         if (isset(self::$methods['cbf1'])) {
             self::cbf1($d);
         }
         // Proceeding to the actions: delete is before
         if ($d['action'] === 'delete') {
             if (self::$db->delete($d['tab'], json_decode($d['rows'], 1))) {
                 self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
                 $to_log['deleted_real']++;
             } else {
                 if (!self::$db->select($d['tab'], [], json_decode($d['rows'], 1))) {
                     self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
                 } else {
                     if ($num_try > self::$max_retry) {
                         self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
                         $to_log['num_problems']++;
                         array_push($to_log['problems'], "Problem while syncing (delete), check data with status 5 and ID " . $d['id']);
                     }
                     $retry = 1;
                 }
             }
         }
         // Checking if there is another change done to this record and when in the twin DB
         $next_time = isset($ds[$i + 1]) && $ds[$i + 1]['tab'] === $d['tab'] && $ds[$i + 1]['rows'] === $d['rows'] ? $ds[$i + 1]['moment'] : date('Y-m-d H:i:s');
         // Looking for the actions done on this specific record in our database
         // between the twin change and the next (or now if there is no other change)
         $each = self::$dbs->rselect_all(self::$dbs_table, ['id', 'moment', 'action', 'vals'], [['db', 'LIKE', self::$db->current], ['tab', 'LIKE', $d['tab']], ['rows', 'LIKE', $d['rows']], ['moment', '>=', $d['moment']], ['moment', '<', $next_time]]);
         if (count($each) > 0) {
             $to_log['num_problems']++;
             array_push($to_log['problems'], "Conflict!", $d);
             foreach ($each as $i => $e) {
                 // If it's deleted locally and updated on the twin we restore
                 if ($e['action'] === 'delete') {
                     if ($d['action'] === 'update') {
                         if (!self::$db->insert_update($d['tab'], \bbn\tools::merge_arrays(json_decode($e['vals'], 1), json_decode($d['vals'], 1)))) {
                             $to_log['num_problems']++;
                             array_push($to_log['problems'], "insert_update number 1 had a problem");
                         }
                     }
                 } else {
                     if ($e['action'] === 'update') {
                         if ($d['action'] === 'delete') {
                             if (!self::$db->insert_update($d['tab'], \bbn\tools::merge_arrays(json_decode($d['vals'], 1), json_decode($e['vals'], 1)))) {
                                 $to_log['num_problems']++;
                                 array_push($to_log['problems'], "insert_update had a problem");
                             }
                         } else {
                             if ($d['action'] === 'update') {
                                 $d['vals'] = json_encode(\bbn\tools::merge_arrays(json_decode($d['vals'], 1), json_decode($e['vals'], 1)));
                             }
                         }
                     }
                 }
             }
         }
         // Proceeding to the actions update is after in case we needed to restore
         if ($d['action'] === 'update') {
             if (self::$db->update($d['tab'], json_decode($d['vals'], 1), json_decode($d['rows'], 1))) {
                 self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
                 $to_log['updated_real']++;
             } else {
                 if (self::$db->select($d['tab'], [], \bbn\tools::merge_arrays(json_decode($d['rows'], 1), json_decode($d['vals'], 1)))) {
                     self::$dbs->update(self::$dbs_table, ["state" => 1], ["id" => $d['id']]);
                 } else {
                     if ($num_try > self::$max_retry) {
                         self::$dbs->update(self::$dbs_table, ["state" => 5], ["id" => $d['id']]);
                         $to_log['num_problems']++;
                         array_push($to_log['problems'], "Problem while syncing (update), check data with status 5 and ID " . $d['id']);
                     }
                     $retry = 1;
                 }
             }
         }
         // Callback number 2
         if (isset(self::$methods['cbf2'])) {
             self::cbf2($d);
         }
     }
     $res = [];
     foreach ($to_log as $k => $v) {
         if (!empty($v)) {
             $res[$k] = $v;
         }
     }
     if ($retry && $num_try <= self::$max_retry) {
         $res = \bbn\tools::merge_arrays($res, self::sync($db, $dbs, $dbs_table, $num_try));
     } else {
         self::$db->set_error_mode($mode_db);
         self::$dbs->set_error_mode($mode_dbs);
         self::enable();
     }
     return $res;
 }
Ejemplo n.º 7
0
 /**
  * Returns an array of files in a directory.
  *
  * It returns the full path ie including the original directory's path.
  * If including_dirs is set to true it will also return the folders included in the path.
  *
  * <code>
  * \bbn\file\dir::get_files("C:\Docs\Test"); //Returns ['C:/DocsTest/file.txt', 'C:/DocsTest/file.doc']
  * \bbn\file\dir::get_files("C:\Docs\Test", 1); //Returns ['C:/DocsTest/test1', 'C:/DocsTest/test2', 'C:/DocsTest/file.txt', 'C:/DocsTest/file.doc']
  * </code>
  * 
  * @param string $dir The directory path.
  * @param bool $including_dirs If set to true it will also return the folders included in the path.
  * 
  * @return array|false 
  */
 public static function get_files($dir, $including_dirs = false)
 {
     $dir = self::clean($dir);
     if (is_dir($dir)) {
         $files = [];
         $fs = scandir($dir);
         foreach ($fs as $f) {
             if ($f !== '.' && $f !== '..') {
                 if ($including_dirs) {
                     array_push($files, self::cur($dir . '/') . $f);
                 } else {
                     if (is_file($dir . '/' . $f)) {
                         array_push($files, self::cur($dir . '/') . $f);
                     }
                 }
             }
         }
         \bbn\tools::sort($files);
         return $files;
     }
     return false;
 }
Ejemplo n.º 8
0
 public function info($path = '.')
 {
     if ($this->has_svn) {
         $this->auth();
         return svn_status($path, SVN_NON_RECURSIVE | SVN_ALL);
     } else {
         ob_start();
         system("svn info " . $this->args());
         $st = ob_get_contents();
         ob_end_clean();
         \bbn\tools::hdump($st);
         return $this->parseCMD($st);
     }
 }
Ejemplo n.º 9
0
 public static function monthpicker_options($val = '')
 {
     $arr = [];
     for ($i = 1; $i <= 12; $i++) {
         $arr[$i] = self::month_name($i);
     }
     return \bbn\tools::build_options($arr, $val);
 }
Ejemplo n.º 10
0
 public function run($id_cron = null)
 {
     if ($cron = $this->get_next($id_cron)) {
         $ok = 1;
         if ($this->is_running($cron['id'])) {
             $runner = $this->get_runner($cron['id']);
             $start = strtotime($runner['start']);
             $timeout = $runner['cfg']['timeout'];
             if ($start + $timeout > time()) {
                 $this->alert();
             }
             $ok = false;
         }
         if ($ok) {
             $id = $this->start($cron['id']);
             $output = $this->_exec($cron['file'], $cron['cfg']);
             $time = $this->finish($id, $output);
             \bbn\tools::dump("Execution of " . $cron['file'] . " (Journal ID: {$id}) in {$time} secs", $output);
             return 1;
         }
     }
 }
Ejemplo n.º 11
0
 /**
  * Returns a variable in a fashion that is directly usable by PHP.
  * 
  * @param mixed $o The item to be.
  * @param bool $remove_empty Default: "false".
  * @param int $lev Default: "1".
  * 
  * @return mixed
  */
 public static function export($o, $remove_empty = false, $lev = 1)
 {
     $st = '';
     if (is_object($o) && ($cls = get_class($o)) && $cls !== 'stdClass') {
         $st .= "Object " . get_class($o) . PHP_EOL;
     }
     if (is_object($o) || is_array($o)) {
         $is_assoc = is_object($o) || \bbn\tools::is_assoc($o);
         $st .= $is_assoc ? '{' : '[';
         $st .= PHP_EOL;
         foreach ($o as $k => $v) {
             if ($remove_empty && (is_string($v) && empty($v) || is_array($v) && count($v) === 0)) {
                 continue;
             }
             $st .= str_repeat('    ', $lev);
             if ($is_assoc) {
                 $st .= (is_string($k) ? "'" . \bbn\str\text::escape_squote($k) . "'" : $k) . ": ";
             }
             if (is_array($v)) {
                 $st .= self::export($v, $remove_empty, $lev + 1);
             } else {
                 if (is_object($v)) {
                     $cls = get_class($v);
                     if ($cls === 'stdClass') {
                         $st .= self::export($v, $remove_empty, $lev + 1);
                     } else {
                         $st .= "Object {$cls}";
                     }
                 } else {
                     if ($v === 0) {
                         $st .= '0';
                     } else {
                         if (is_null($v)) {
                             $st .= 'null';
                         } else {
                             if (is_bool($v)) {
                                 $st .= $v === false ? 'false' : 'true';
                             } else {
                                 if (is_int($v) || is_float($v)) {
                                     $st .= $v;
                                 } else {
                                     if (!$remove_empty || !empty($v)) {
                                         $st .= "'" . \bbn\str\text::escape_squote($v) . "'";
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             $st .= ',' . PHP_EOL;
         }
         $st .= str_repeat('    ', $lev - 1);
         $st .= $is_assoc ? '}' : ']';
         return $st;
     }
     return $o;
 }
Ejemplo n.º 12
0
 public function debug($file = 'misc')
 {
     $i = debug_backtrace();
     \bbn\tools::log(print_r($i, 1));
 }
Ejemplo n.º 13
0
 /**
  * Returns the current configuration.
  * 
  * @return array Current configuration
  */
 public function get_config()
 {
     $this->update();
     $tmp = \bbn\tools::remove_empty($this->cfg);
     if (isset($tmp['content']) && is_array($tmp['content'])) {
         foreach ($tmp['content'] as $i => $c) {
             if (is_object($c)) {
                 if (method_exists($c, 'get_config')) {
                     $tmp['content'][$i] = $c->get_config();
                 }
             }
         }
     }
     return $tmp;
 }
Ejemplo n.º 14
0
 /**
  * Generates a whole input configuration array by combining the passed and default configurations
  * @param array $cfg The input's config
  * @return array
  */
 public function input($cfg = array())
 {
     if (is_array($cfg) && isset($cfg['attr']['name'])) {
         self::give_id($cfg);
         if (isset($cfg['field'])) {
             $cfg = \bbn\tools::merge_arrays(self::specs('fields', $cfg['field']), $cfg);
         }
         /*
         if ( !isset($cfg['tag']) ){
           $cfg['tag'] = 'input';
         }
         if ( !isset($cfg['attr']['type']) ){
           $cfg['attr']['type'] = 'text';
         }
         */
         if (isset($cfg['data'])) {
             if (isset($cfg['data']['sql'], $this->_current_cfg['data']['db'])) {
                 $db =& $this->_current_cfg['data']['db'];
                 if (!isset($cfg['widget']['options']['dataSource'])) {
                     $cfg['widget']['options']['dataSource'] = [];
                 }
                 $count = ($r = $db->query($cfg['data']['sql'])) ? $r->count() : 0;
                 if ($count <= self::max_values_at_once) {
                     if ($ds = $db->get_irows($cfg['data']['sql'])) {
                         foreach ($ds as $d) {
                             if (count($d) > 1) {
                                 array_push($cfg['widget']['options']['dataSource'], ['value' => $d[0], 'text' => $d[1]]);
                             } else {
                                 array_push($cfg['widget']['options']['dataSource'], $d[0]);
                             }
                         }
                     }
                 } else {
                     $cfg['field'] = 'autocomplete';
                 }
             } else {
                 if (is_array($cfg['data']) && count($cfg['data']) > 0) {
                     if (isset($cfg['data'][0])) {
                         $cfg['widget']['options']['dataSource'] = $cfg['data'];
                     } else {
                         $cfg['widget']['options']['dataSource'] = [];
                         foreach ($cfg['data'] as $k => $v) {
                             array_push($cfg['widget']['options']['dataSource'], ['value' => $k, 'text' => $v]);
                         }
                     }
                 }
             }
             if (isset($cfg['widget']['options']['dataSource'][0]['text'])) {
                 $cfg['widget']['options']['dataTextField'] = 'text';
                 $cfg['widget']['options']['dataValueField'] = 'value';
             }
         }
         if (is_array($cfg)) {
             // Size calculation
             if (isset($cfg['attr']['maxlength']) && !isset($cfg['attr']['size'])) {
                 if ($cfg['attr']['maxlength'] <= 20) {
                     $cfg['attr']['size'] = (int) $cfg['attr']['maxlength'];
                 }
             }
             if (isset($cfg['attr']['size'], $cfg['attr']['minlength']) && $cfg['attr']['size'] < $cfg['attr']['minlength']) {
                 $cfg['attr']['size'] = (int) $cfg['attr']['minlength'];
             }
             $cfg = array_filter($cfg, function ($a) {
                 return !(is_array($a) && count($a) === 0);
             });
         }
         if (isset($cfg['null']) && $cfg['null']) {
             if (empty($cfg['attr']['value'])) {
                 $cfg['attr']['value'] = null;
                 $cfg['attr']['disabled'] = true;
                 if (isset($cfg['widget'])) {
                     if (!isset($cfg['script'])) {
                         $cfg['script'] = '';
                     }
                     /*
                                 $cfg['script'] .= 'if ( $("#'.$cfg['attr']['id'].'").data("'.$cfg['widget']['name'].'") ){
                      $("#'.$cfg['attr']['id'].'").data("'.$cfg['widget']['name'].'").enable(false);
                                 }
                                 else if ( $("#'.$cfg['attr']['id'].'").'.$cfg['widget']['name'].' ){
                      $("#'.$cfg['attr']['id'].'").'.$cfg['widget']['name'].'("enable", false);
                                 }';
                     * 
                     */
                 }
             }
         }
         $t = new \bbn\html\input($cfg);
         return $t;
     }
     return false;
 }
Ejemplo n.º 15
0
<?php

/** @var $this \bbn\mvc\controller */
// DB connection
$db =& $this->data['db'];
if (!empty($db) && !empty($this->data['id_lib'])) {
    // Get all library's versions
    $versions = $db->rselect_all('versions', [], ['library' => $this->data['id_lib']], ['date_added' => 'DESC']);
    foreach ($versions as $i => $ver) {
        // Get all versions' dependencies
        $versions[$i]['dependencies'] = $db->get_rows("\n      SELECT libraries.title, libraries.name, versions.name AS version\n      FROM dependencies\n        LEFT JOIN versions\n          ON id_master = versions.id\n        LEFT JOIN libraries\n          ON versions.library = libraries.name\n      WHERE id_slave = ?\n      GROUP BY libraries.title\n      ORDER BY libraries.name", $ver['id']);
        // Make version's files TreeView
        $versions[$i]['files_tree'] = \bbn\tools::make_tree((array) json_decode($ver['content']));
    }
    return $versions;
} else {
    if (!empty($this->data['folder']) && !empty(BBN_CDN_PATH)) {
        $ret = [];
        // Library path
        $lib_path = BBN_CDN_PATH . 'lib/' . $this->data['folder'];
        // Check if the library's subfolders are already inserted into db and use the first not included as version
        if (is_dir($lib_path) && ($dirs = \bbn\file\dir::get_dirs($lib_path))) {
            $ver = [];
            foreach ($dirs as $dir) {
                if (empty($db->select('versions', [], ['name' => basename($dir), 'library' => $this->data['folder']]))) {
                    array_push($ver, $dir);
                }
            }
            if (empty($ver)) {
                return ['error' => "All library's versions (subfolders) are existing into database."];
            }
Ejemplo n.º 16
0
 public function __construct(array $cfg)
 {
     if (isset($cfg['primary'])) {
         $this->id = isset($cfg['id']) ? $cfg['id'] : \bbn\str\text::genpwd();
         $this->primary = $cfg['primary'];
         if (!isset($cfg['builder'])) {
             $cfg['builder'] = new \bbn\html\builder();
         }
         $this->builder = $cfg['builder'];
         $this->grid = new \Kendo\UI\Grid($this->id);
         $this->dataSource = new \Kendo\Data\DataSource();
         if (isset($cfg['data'])) {
             $this->dataSource->data($cfg['data']);
         }
         $this->schema = new \Kendo\Data\DataSourceSchema();
         $this->schema->data('data');
         $this->schema->total('total');
         $this->model = new \Kendo\Data\DataSourceSchemaModel();
         $this->model->id($cfg['primary']);
         foreach ($cfg['elements'] as $e) {
             if (isset($e['attr']['name'])) {
                 $field = new \Kendo\Data\DataSourceSchemaModelField($e['attr']['name']);
                 if (isset($e['attr']['name']) && isset($e['editable']) && $e['editable']) {
                     if (isset($e['type'])) {
                         $field->type($e['type']);
                     }
                     if (isset($e['null']) && $e['null']) {
                         $field->nullable(true);
                     }
                     if (isset($e['attr']['readonly']) && $e['attr']['readonly']) {
                         $field->editable(false);
                     } else {
                         if (isset($e['validation'])) {
                             $field->validation($e['validation']);
                         }
                     }
                     $this->model->addField($field);
                 }
                 if (empty($e['editable'])) {
                     $field->editable(false);
                 }
                 if (!empty($e['default'])) {
                     $field->defaultValue($e['default']);
                 }
             }
             $col = new \Kendo\UI\GridColumn();
             if (!isset($e['field']) || $e['field'] !== 'hidden') {
                 if (isset($e['editable']) && $e['editable']) {
                     /*
                                 if ( !isset($e['editor']) ){
                      $input = $this->builder->input($e, 1);
                      $sc = $input->ele_and_script();
                      $e['editor'] = new \Kendo\JavaScriptFunction('function(container, options) {
                        '.$sc[0].'.appendTo(container)'.$sc[1].'
                      }');
                                 }
                                 $col->editor($e['editor']);
                     * 
                     */
                 }
                 if (isset($e['raw'])) {
                     $col->encoded(false);
                 }
                 if (isset($e['data'])) {
                     $col->values($e['data']);
                 }
                 if (isset($e['label'])) {
                     $col->title($e['label']);
                 }
                 if (isset($e['attr']['name'])) {
                     $col->field($e['attr']['name']);
                 }
                 if (isset($e['width'])) {
                     $col->width((int) $e['width']);
                 }
                 if (isset($e['format'])) {
                     $col->format('{0:' . $e['format'] . '}');
                 }
                 if (isset($e['hidden'])) {
                     $col->hidden(true);
                 }
                 if (isset($e['template'])) {
                     $col->template($e['template']);
                 }
                 if (isset($e['editor'])) {
                     $col->editor($e['editor']);
                 }
                 if (isset($e['encoded'])) {
                     $col->encoded($e['encoded']);
                 }
                 if (isset($e['commands'])) {
                     foreach ($e['commands'] as $c) {
                         if (isset($c['click'])) {
                             $c['click'] = new \Kendo\JavaScriptFunction($c['click']);
                         }
                         $col->addCommandItem($c);
                     }
                 }
                 if (count(\bbn\tools::to_array($col)) > 0) {
                     $this->grid->addColumn($col);
                 }
             }
         }
         if (isset($cfg['url'])) {
             $this->transport = new \Kendo\Data\DataSourceTransport();
             if (isset($cfg['all'])) {
                 $this->set_all($cfg['url']);
             } else {
                 if (isset($cfg['select'])) {
                     $this->set_select($cfg['select'] === 1 || $cfg['select'] === 'on' ? 'json/select/' . $cfg['url'] : $cfg['select']);
                 }
                 if (isset($cfg['insert'])) {
                     $this->set_insert($cfg['insert'] === 1 || $cfg['insert'] === 'on' ? 'json/insert/' . $cfg['url'] : $cfg['insert']);
                 }
                 if (isset($cfg['update'])) {
                     $this->set_update($cfg['update'] === 1 || $cfg['update'] === 'on' ? 'json/update/' . $cfg['url'] : $cfg['update']);
                 }
                 if (isset($cfg['delete'])) {
                     $this->set_delete($cfg['delete'] === 1 || $cfg['delete'] === 'on' ? 'json/delete/' . $cfg['url'] : $cfg['delete']);
                 }
             }
             $this->dataSource->transport($this->transport);
         }
         if (isset($cfg['data'])) {
             $this->dataSource->data($cfg['data']);
         }
         $this->schema->model($this->model);
         $this->dataSource->schema($this->schema)->pageSize(50);
         $this->grid->attr("class", "appui-full-height")->datasource($this->dataSource)->editable(['mode' => 'popup'])->filterable(true)->resizable(true)->sortable(true)->groupable(true)->pageable(true)->columnMenu(true)->edit(new \Kendo\JavaScriptFunction('function(){
             $(".k-edit-form-container").parent().css({
               height:"auto",
               width:720,
               "max-height":appui.v.height-100
             }).restyle().data("kendoWindow").title("' . \bbn\str\text::escape_dquotes($cfg['description']) . '").center();
            }'));
         $this->cfg['args'] = [$this->id];
         $this->cfg['datasource']['schema']['model']['id'] = $this->primary;
     }
 }