commit() public static method

Commits statements in a transaction - Monostate for Dibi\Connection::commit($savepoint = NULL).
public static commit ( $savepoint = NULL ) : void
return void
Beispiel #1
0
/**
 * Metainformation catalogue
 * --------------------------------------------------
 *
 * MICKA_LIB_INSERT.PHP for MicKa
 *
 * @link       http://www.bnhelp.cz
 * @package    Micka
 * @category   Metadata
 * @version    20101120
 * @authors		 DZ
 */
function deleteMd($user, $type, $value, $mode, $par = NULL)
{
    setMickaLog('micka_lib_insert.php (deleteMd)', 'DEBUG', "user={$user}, {$type}={$value}, mode={$mode}, par={$par}");
    $rs = FALSE;
    // autorizace
    if ($user == 'guest' || !canAction()) {
        return $rs;
    }
    $record = getMdHeader($type, $value, $col = '', $fetch = array('all', '='));
    if (isset($record[0]['RECNO']) && $record[0]['RECNO'] > -1) {
        if (!getMdRight('edit', $user, $record[0]['DATA_TYPE'], $record[0]['CREATE_USER'], $record[0]['EDIT_GROUP'], $record[0]['VIEW_GROUP'])) {
            return $rs;
        } else {
            $sql = array();
            if ($mode == 'all') {
                array_push($sql, 'DELETE FROM [md_values] WHERE [recno]=%i;', $record[0]['RECNO']);
                array_push($sql, 'DELETE FROM [md] WHERE [recno]=%i;', $record[0]['RECNO']);
            } elseif ($mode == 'value') {
                array_push($sql, 'DELETE FROM [md_values] WHERE [recno]=%i  AND md_id<>38;', $record[0]['RECNO']);
            }
            dibi::begin();
            try {
                dibi::query($sql);
                dibi::commit();
                $rs = TRUE;
            } catch (DibiException $e) {
                setMickaLog($e, 'ERROR', 'micka_lib_insert.php (deleteMd)');
                dibi::rollback();
            }
        }
    }
    //Debug::dump($rs);
    setMickaLog('micka_lib_insert.php (deleteMd)', 'DEBUG', "return={$rs}");
    return $rs;
}
Beispiel #2
0
 static function createOrder($values, $id_product_params, $id_lang, $user)
 {
     dibi::begin();
     //		print_r($values);exit;
     dibi::query("INSERT INTO [order]", $values);
     $order_id = dibi::insertId();
     foreach ($id_product_params as $id_product_param => $count) {
         self::insertProduct($id_product_param, $count, $order_id, $id_lang, $user);
     }
     dibi::commit();
     return $order_id;
 }
Beispiel #3
0
 public function render($args = NULL)
 {
     parent::render($args);
     $this->template->database = $this->context->database;
     $this->template->subjects = $this->subjects->fetchAd($this->strict);
     $this->template->type = $this->type;
     $this->template->setFile(__DIR__ . "/BannerSubjects.latte");
     dibi::begin();
     foreach ($this->subjects as $key => $value) {
         dibi::query('update subject set ad_show_count=ad_show_count+1 where id=' . $key);
     }
     dibi::commit();
     $this->template->render();
 }
Beispiel #4
0
 /**
  * update user roles [delete & insert]
  *
  * @param int User id
  * @param int Role id
  */
 public function updateUserRoles($userId, $roles)
 {
     try {
         dibi::begin();
         dibi::delete(self::ACL_USERS_2_ROLES_TABLE)->where('user_id = %i', $userId)->execute();
         foreach ($roles as $role) {
             dibi::insert(self::ACL_USERS_2_ROLES_TABLE, array('user_id' => $userId, 'role_id' => $role))->execute();
         }
         dibi::commit();
     } catch (DibiDriverException $e) {
         dibi::rollback();
         throw $e;
     }
 }
Beispiel #5
0
 /**
  * Save given order
  * @param order
  * @param array
  * @return bool
  */
 public function save(order $order, array $products, array $visited)
 {
     // order data
     $data = $order->__toArray();
     $data['at'] = date('Y-m-d H:i:s', time());
     $data['delivery_type_id'] = $data['delivery_type']->getId();
     unset($data['delivery_type']);
     $data['payment_type_id'] = $data['payment_type']->getId();
     unset($data['payment_type']);
     $data['status_id'] = $data['status']->getId();
     unset($data['status']);
     // start transaction
     dibi::begin();
     try {
         $this->insert($data);
         $order_id = dibi::query('SELECT LAST_INSERT_ID()')->fetchSingle();
         $order->setId($order_id);
         $order->dirty(order::UNDIRT);
         foreach (mapper::products()->findByIds(array_keys($products)) as $product) {
             dibi::query('INSERT INTO [:prefix:orders_products]', array('order_id' => $order_id, 'product_id' => $product->getId(), 'price' => $product->getPrice(), 'amount' => $products[$product->getId()]));
         }
         foreach ($visited as $_) {
             $values = array('order_id' => $order_id);
             $values['product_id'] = $_[0]->getId();
             $values['visited_at'] = date('Y-m-d H:i:s', $_[1]);
             dibi::query('INSERT INTO [:prefix:order_visited_products]', $values);
         }
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopEmail%'))->addTo(Environment::expand('%shopEmail%'))->setSubject(__('New order'))->setBody(__('Hello, new order arrived'))->send();
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopEmail%'))->addTo($data['email'])->setSubject(__('Your order at %s has been accepted', Environment::expand('%shopName%')))->setBody(str_replace('\\n', "\n", __('Hello, your order has been accepted.')))->send();
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
     dibi::commit();
     return TRUE;
 }
 public function upgradeDB()
 {
     $confDriver = ConfService::getConfStorageImpl();
     $authDriver = ConfService::getAuthDriverImpl();
     $logger = AJXP_Logger::getInstance();
     if (is_a($confDriver, "sqlConfDriver")) {
         $conf = AJXP_Utils::cleanDibiDriverParameters($confDriver->getOption("SQL_DRIVER"));
         if (!is_array($conf) || !isset($conf["driver"])) {
             return "Nothing to do";
         }
         switch ($conf["driver"]) {
             case "sqlite":
             case "sqlite3":
                 $ext = ".sqlite";
                 break;
             case "postgre":
                 $ext = ".pgsql";
                 break;
             case "mysql":
                 $ext = is_file($this->workingFolder . "/" . $this->dbUpgrade . ".mysql") ? ".mysql" : ".sql";
                 break;
             default:
                 return "ERROR!, DB driver " . $conf["driver"] . " not supported yet in __FUNCTION__";
         }
         $file = $this->dbUpgrade . $ext;
         if (!is_file($this->workingFolder . "/" . $file)) {
             return "Nothing to do.";
         }
         $sqlInstructions = file_get_contents($this->workingFolder . "/" . $file);
         $parts = array_map("trim", explode("/* SEPARATOR */", $sqlInstructions));
         $results = array();
         $errors = array();
         dibi::connect($conf);
         dibi::begin();
         foreach ($parts as $sqlPart) {
             if (empty($sqlPart)) {
                 continue;
             }
             try {
                 dibi::nativeQuery($sqlPart);
                 $results[] = $sqlPart;
             } catch (DibiException $e) {
                 $errors[] = $sqlPart . " (" . $e->getMessage() . ")";
             }
         }
         dibi::commit();
         dibi::disconnect();
         if (!count($errors)) {
             return "Database successfully upgraded";
         } else {
             return "Database upgrade failed. <br>The following statements were executed : <br>" . implode("<br>", $results) . ",<br><br> The following statements failed : <br>" . implode("<br>", $errors) . "<br><br> You should manually upgrade your DB.";
         }
     }
 }
 public static function runCreateTablesQuery($p, $file)
 {
     switch ($p["driver"]) {
         case "sqlite":
         case "sqlite3":
             if (!file_exists(dirname($p["database"]))) {
                 @mkdir(dirname($p["database"]), 0755, true);
             }
             $ext = ".sqlite";
             break;
         case "mysql":
             $ext = ".mysql";
             break;
         case "postgre":
             $ext = ".pgsql";
             break;
         default:
             return "ERROR!, DB driver " . $p["driver"] . " not supported yet in __FUNCTION__";
     }
     $result = array();
     $file = dirname($file) . "/" . str_replace(".sql", $ext, basename($file));
     $sql = file_get_contents($file);
     $separators = explode("/** SEPARATOR **/", $sql);
     $allParts = array();
     foreach ($separators as $sep) {
         $explode = explode("\n", trim($sep));
         $firstLine = array_shift($explode);
         if ($firstLine == "/** BLOCK **/") {
             $allParts[] = $sep;
         } else {
             $parts = explode(";", $sep);
             $remove = array();
             for ($i = 0; $i < count($parts); $i++) {
                 $part = $parts[$i];
                 if (strpos($part, "BEGIN") && isset($parts[$i + 1])) {
                     $parts[$i] .= ';' . $parts[$i + 1];
                     $remove[] = $i + 1;
                 }
             }
             foreach ($remove as $rk) {
                 unset($parts[$rk]);
             }
             $allParts = array_merge($allParts, $parts);
         }
     }
     dibi::connect($p);
     dibi::begin();
     foreach ($allParts as $createPart) {
         $sqlPart = trim($createPart);
         if (empty($sqlPart)) {
             continue;
         }
         try {
             dibi::nativeQuery($sqlPart);
             $resKey = str_replace("\n", "", substr($sqlPart, 0, 50)) . "...";
             $result[] = "OK: {$resKey} executed successfully";
         } catch (DibiException $e) {
             $result[] = "ERROR! {$sqlPart} failed";
         }
     }
     dibi::commit();
     dibi::disconnect();
     $message = implode("\n", $result);
     if (strpos($message, "ERROR!")) {
         return $message;
     } else {
         return "SUCCESS:" . $message;
     }
 }
 public function onSendMailFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     $active = FALSE;
     try {
         dibi::begin();
         $active = TRUE;
         mapper::order_emails()->insertOne(array('order_id' => $form['order_id']->getValue(), 'subject' => $form['subject']->getValue(), 'body' => $form['body']->getValue()));
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopName% <%shopEmail%>'))->addTo($form['to']->getValue())->setSubject($form['subject']->getValue())->setBody($form['body']->getValue())->send();
         adminlog::log(__('Sent e-mail to "%s" with subject "%s"'), $form['to']->getValue(), $form['subject']->getValue());
         $this->redirect('this');
         $this->terminate();
     } catch (RedirectingException $e) {
         dibi::commit();
         throw $e;
     } catch (Exception $e) {
         if ($active) {
             dibi::rollback();
         }
         $form->addError(__('Cannot send e-mail.'));
     }
 }
Beispiel #9
0
 public function setCategories($place_id, $data)
 {
     dibi::begin();
     dibi::query('DELETE FROM [subject_x_category] WHERE [subject_id]=%i', $place_id);
     foreach ($data as $k => $n) {
         dibi::query('INSERT INTO [subject_x_category] SET [subject_id]=%i', $place_id, ', [category_id]=%i', $n);
     }
     dibi::commit();
 }
Beispiel #10
0
        echo "Upgrading MYSQL database ...";
        $parts = array_map("trim", explode("/* SEPARATOR */", $dbInst));
        $results = array();
        $errors = array();
        require_once AJXP_BIN_FOLDER . "/dibi.compact.php";
        dibi::connect($test);
        dibi::begin();
        foreach ($parts as $sqlPart) {
            if (empty($sqlPart)) {
                continue;
            }
            try {
                dibi::nativeQuery($sqlPart);
                echo "<div class='upgrade_result success'>{$sqlPart} ... OK</div>";
            } catch (DibiException $e) {
                $errors[] = $e->getMessage();
                echo "<div class='upgrade_result success'>{$sqlPart} ... FAILED (" . $e->getMessage() . ")</div>";
            }
        }
        dibi::commit();
        dibi::disconnect();
    } else {
        if (is_array($test) && $test["driver"] != "mysql") {
            echo "Cannot auto-upgrade Sqlite or PostgreSql DB automatically, please review the update instructions.";
        } else {
            echo "Nothing to do for the DB";
        }
    }
} else {
    echo "Nothing to do for the DB";
}
Beispiel #11
0
 /**
  * Update
  */
 public function updateOne(array $values)
 {
     try {
         dibi::begin();
         $product = array();
         $product['price'] = intval($values['price']);
         if (isset($values['manufacturer_id'])) {
             $product['manufacturer_id'] = $values['manufacturer_id'] == 0 ? NULL : intval($values['manufacturer_id']);
         }
         if (isset($values['category_id'])) {
             $product['category_id'] = $values['category_id'] == 0 ? NULL : intval($values['category_id']);
         }
         $product_id = intval($values['id']);
         if (isset($values['availability_id'])) {
             $product['availability_id'] = $values['availability_id'] == 0 ? NULL : intval($values['availability_id']);
         }
         if (isset($values['code'])) {
             $product['code'] = empty($values['code']) ? NULL : $values['code'];
         }
         unset($values['price'], $values['manufacturer_id'], $values['category_id'], $values['availability_id'], $values['id'], $values['code']);
         dibi::query('UPDATE [:prefix:products] SET', $product, 'WHERE [id] = %i', $product_id);
         $change = array('product_id' => $product_id, 'price' => $product['price'], 'changed_at' => new DibiVariable('NOW()', 'sql'));
         dibi::query('INSERT INTO [:prefix:price_changes]', $change);
         if (isset($values['picture_id'])) {
             $values['picture_id'] = $values['picture_id'] == 0 ? NULL : intval($values['picture_id']);
         }
         if (isset($values['meta_keywords']) && empty($values['meta_keywords'])) {
             $values['meta_keywords'] = NULL;
         }
         if (isset($values['meta_description']) && empty($values['meta_description'])) {
             $values['meta_description'] = NULL;
         }
         if (isset($values['content']) && empty($values['content'])) {
             $values['content'] = NULL;
         }
         if (!empty($values)) {
             $where = array();
             $where['ref_id'] = $product_id;
             $where['ref_type'] = pages::PRODUCT;
             dibi::query('UPDATE [:prefix:pages] SET', $values, 'WHERE %and', $where);
         }
         dibi::commit();
         //<fulltext>
         fulltext::dirty($product_id, TRUE);
         //</fulltext>
         return TRUE;
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
 }
Beispiel #12
0
 public function insert(array $data)
 {
     if ($this->config['useAcl']) {
         // check rights
         if (!$this->user->isAllowed(Acl::RESOURCE_USER, Acl::PRIVILEGE_ADD)) {
             throw new OperationNotAllowedException();
         }
     }
     $data['token'] = md5($data['email'] . $data['username']);
     $data['registered'] = dibi::datetime();
     if (isset($data['roles'])) {
         $roles = $data['roles'];
         unset($data['roles']);
     }
     if (isset($data['client_logo'])) {
         $clientLogo = $data['client_logo'];
         unset($data['client_logo']);
     }
     // create user and update his password - needed because getHasherParamsFromUserData() requires $userId
     try {
         dibi::begin();
         // save random password temporarily
         $realPassword = $data['password'];
         $data['password'] = Basic::randomizer(40);
         $userId = parent::insert($data);
         $data['password'] = $realPassword;
         $this->update($userId, $data);
         dibi::commit();
     } catch (DibiDriverException $e) {
         dibi::rollback();
         throw $e;
     }
     if (isset($roles)) {
         $this->getRolesModel()->updateUserRoles($userId, (array) $roles);
     }
     if (!empty($clientLogo)) {
         $this->saveClientLogo($userId, $clientLogo);
     }
     return $userId;
 }
Beispiel #13
0
 public function addEditOnFormSubmitted(NAppForm $form)
 {
     $error = false;
     dibi::begin();
     // add action
     if ($this->getAction() == 'add') {
         try {
             $values = $form->getValues();
             $roles = $values['roles'];
             unset($values['password2'], $values['roles']);
             //				$values['password'] = md5($values['password']);
             //                dibi::query('INSERT INTO ['.TABLE_USERS.'] %v;', $values);
             $user_id = UserModel::insert($values);
             if (count($roles)) {
                 foreach ($roles as $role) {
                     dibi::query('INSERT INTO [' . TABLE_USERS_ROLES . '] (user_id, role_id) VALUES (%i, %i);', $user_id, $role);
                 }
             }
             $this->flashMessage('The user has been added.', 'ok');
             dibi::commit();
             if (ACL_CACHING) {
                 unset($this->cache['gui_acl']);
                 // invalidate cache
             }
             $this->redirect('Users:');
         } catch (Exception $e) {
             $error = true;
             $form->addError('The user has not been added.');
             throw $e;
         }
     } else {
         // edit action
         $id = $this->getParam('id');
         try {
             $values = $form->getValues();
             $roles = $values['roles'];
             unset($values['roles']);
             unset($values['password2']);
             //                dibi::query('UPDATE ['.TABLE_USERS.'] SET %a WHERE id=%i;', $values, $id);
             UserModel::update($id, $values);
             dibi::query('DELETE FROM [' . TABLE_USERS_ROLES . '] WHERE user_id=%i;', $id);
             if (count($roles)) {
                 foreach ($roles as $role) {
                     dibi::query('INSERT INTO [' . TABLE_USERS_ROLES . '] (user_id, role_id) VALUES (%i, %i);', $id, $role);
                 }
             }
             $this->flashMessage('The user has been edited.', 'ok');
             dibi::commit();
             if (ACL_CACHING) {
                 unset($this->cache['gui_acl']);
                 // invalidate cache
             }
             $this->redirect('Users:');
         } catch (Exception $e) {
             $error = true;
             $form->addError('The user has not been edited.');
             throw $e;
         }
     }
     if ($error) {
         dibi::rollback();
     }
 }
 /**
  * Update
  * @param array
  * @return bool
  */
 public function updateOne(array $values)
 {
     try {
         $values['initial'] = (bool) $values['initial'];
         dibi::begin();
         if ($values['initial']) {
             dibi::query('UPDATE [:prefix:order_statuses] SET [initial] = %b', FALSE);
         }
         $id = intval($values['id']);
         unset($values['id']);
         dibi::query('UPDATE [:prefix:order_statuses] SET', $values, 'WHERE [id] = %i', $id);
         dibi::commit();
         return TRUE;
     } catch (Excetion $e) {
         return FALSE;
     }
 }
Beispiel #15
0
 public function setPrimary($file_id, $event_id)
 {
     dibi::begin();
     dibi::query('UPDATE [event_x_file] SET [first] = 0 WHERE [event_id] = %i', $event_id);
     dibi::query('UPDATE [event_x_file] SET [first] = 1 WHERE [event_id] = %i', $event_id, " AND [file_id]=%i", $file_id);
     dibi::commit();
 }
Beispiel #16
0
 public function generateAllTimes($times = 30, $term_id = 0, $limit = 120)
 {
     $limit = new DibiDateTime(strtotime('+' . $limit . ' days', time()));
     dibi::begin();
     if ($term_id) {
         dibi::query('DELETE FROM event_time_all WHERE event_time_id = %i', $term_id);
         // smaze tabulku casu s daným ID termínu
         $res = dibi::select('*, DATEDIFF(event_time.date_to, event_time.date_from) AS diff_dates')->from('event_time')->where('visible', '=', '1')->where('id', '=', $term_id)->fetchAll();
     } else {
         //dibi::query('TRUNCATE TABLE event_time_all'); // smaze celou tabulku casu
         dibi::query('UPDATE event_time SET visible = 0 WHERE (DATEDIFF(event_time.date_from, CURDATE()) < 0 AND DATEDIFF(event_time.date_to, CURDATE()) < 0) OR (DATEDIFF(event_time.date_from, CURDATE()) < 0 AND isnull(`event_time`.`date_to`))');
         // prevede vsechny starsi casy do neaktivni polohy
         $res = dibi::select('*, DATEDIFF(event_time.date_to, event_time.date_from) AS diff_dates')->from('event_time')->where('visible', '=', '1')->fetchAll();
     }
     foreach ($res as $key => $event) {
         $interval = date_diff($event->date_from, date_create());
         if ($interval->days > 0 && $interval->invert) {
             $date_from = $event->date_from;
             //dump('od '.$date_from);
         } else {
             $date_from = new DibiDateTime();
             //dump('od dnes');
         }
         $nextmonday = new DibiDateTime(date('N', strtotime('today')) == 1 ? strtotime('today') : strtotime('next monday', $date_from->getTimestamp()));
         $nexttuesday = new DibiDateTime(date('N', strtotime('today')) == 2 ? strtotime('today') : strtotime('next tuesday', $date_from->getTimestamp()));
         $nextwednesday = new DibiDateTime(date('N', strtotime('today')) == 3 ? strtotime('today') : strtotime('next wednesday', $date_from->getTimestamp()));
         $nextthursday = new DibiDateTime(date('N', strtotime('today')) == 4 ? strtotime('today') : strtotime('next thursday', $date_from->getTimestamp()));
         $nextfriday = new DibiDateTime(date('N', strtotime('today')) == 5 ? strtotime('today') : strtotime('next friday', $date_from->getTimestamp()));
         $nextsaturday = new DibiDateTime(date('N', strtotime('today')) == 6 ? strtotime('today') : strtotime('next saturday', $date_from->getTimestamp()));
         $nextsunday = new DibiDateTime(date('N', strtotime('today')) == 7 ? strtotime('today') : strtotime('next sunday', $date_from->getTimestamp()));
         //dump($date_from);
         if ($event->repeat == 1) {
             if ($event->every_monday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextmonday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_tuesday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nexttuesday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_wednesday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextwednesday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_thursday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextthursday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_friday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextfriday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_saturday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextsaturday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
             if ($event->every_sunday == 1) {
                 for ($i = 0; $i < $times * 7; $i = $i + 7) {
                     $day = new DibiDateTime(strtotime('+' . $i . ' days', $nextsunday->getTimestamp()));
                     if ($day->getTimestamp() > $limit->getTimestamp()) {
                         continue;
                     }
                     $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $day . "', '" . $event->date_to . "'); \r\n";
                     dibi::query($query);
                 }
             }
         } else {
             $query = "INSERT IGNORE INTO event_time_all (event_time_id, date_from, date_to) VALUES ('" . $event->id . "', '" . $event->date_from . "', '" . $event->date_to . "'); \r\n";
             dibi::query($query);
         }
     }
     dibi::query('DELETE FROM event_time_all WHERE date_to < date_from AND date_to !="0000-00-00"');
     dibi::commit();
 }
Beispiel #17
0
 /**
  * Delete
  */
 public function deleteOne($id)
 {
     $id = intval($id);
     try {
         dibi::begin();
         $one = dibi::query('SELECT [lft], [rgt] FROM [:prefix:categories] WHERE [id] = %i', $id)->fetch();
         $ids = array();
         foreach (dibi::query('SELECT [id] FROM [:prefix:categories] WHERE [lft] >= %i', $one->lft, ' AND [rgt] <= %i', $one->rgt) as $id) {
             $ids[] = intval($id->id);
         }
         dibi::query('DELETE FROM [:prefix:pages] WHERE [ref_id] IN %l', $ids, 'AND [ref_type] = %s', pages::CATEGORY);
         dibi::query('DELETE FROM [:prefix:categories] WHERE [id] IN %l', $ids);
         dibi::query('UPDATE [:prefix:categories] SET', '[lft] = [lft] - %i', intval($one->lft) - intval($one->rgt) + 1, 'WHERE [lft] > %i', $one->rgt);
         dibi::query('UPDATE [:prefix:categories] SET', '[rgt] = [rgt] - %i', intval($one->lft) - intval($one->rgt) + 1, 'WHERE [rgt] > %i', $one->rgt);
         dibi::commit();
         return TRUE;
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
 }
Beispiel #18
0
 static function insert($values)
 {
     $user_value['name'] = @$values['name'];
     $user_value['surname'] = @$values['surname'];
     //		$user_value['email'] = $values['email'];
     $user_value['login'] = $values['login'];
     $user_value['activate'] = $values['activate'];
     $user_value['password'] = self::getHash($values['password']);
     $user_value['fbuid'] = @$values['fbuid'];
     $user_value['google_id'] = @$values['google_id'];
     $user_value['newsletter'] = @$values['newsletter'];
     $user_value['discount'] = @$values['discount'];
     unset($values['name'], $values['surname'], $values['login'], $values['password'], $values['activate'], $values['fbuid'], $values['newsletter'], $values['discount']);
     dibi::begin();
     dibi::insert(TABLE_USERS, $user_value)->execute();
     $values['user_id'] = dibi::insertId();
     dibi::insert(TABLE_USERS_INFO, $values)->execute();
     dibi::commit();
     return $values['user_id'];
 }
Beispiel #19
0
 /**
  * Static function for deleting a user.
  * Also removes associated rights, preferences and bookmarks.
  *
  * @param String $userId Login to delete.
  * @return null or -1 on error.
  */
 function deleteUser($userId)
 {
     try {
         dibi::begin();
         dibi::query('DELETE FROM [ajxp_users] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_rights] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_prefs] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_bookmarks] WHERE [login] = %s', $userId);
         dibi::commit();
     } catch (DibiException $e) {
         $this->log('Failed to delete user, Reason: ' . $e->getMessage());
         return -1;
     }
 }
Beispiel #20
0
 public function save()
 {
     $this->created = $this->created ? new DibiDateTime($this->created) : new DibiDateTime();
     $this->changed = $this->changed ? new DibiDateTime($this->changed) : NULL;
     // prevede data objektu na pole
     $data = get_object_vars($this);
     unset($data['simulation']);
     unset($data['force']);
     unset($data['file_prefix']);
     unset($data['file_sufix']);
     if ($data['user_id'] === '0') {
         unset($data['user_id']);
     }
     dibi::begin();
     // zkontroluje, zda j*z neni ulozen stejny soubor - podle code
     $res = dibi::query('SELECT * FROM [file] WHERE [code] = %s', $this->code);
     if ($res->getRowCount() > 0) {
         throw new DibiException("File already exists with this name. Please, try upload file with different name.", 0);
     }
     if ($this->id > 0 && !$this->force) {
         foreach ($data as $key => $value) {
             if ($value == null) {
                 unset($data[$key]);
             }
         }
         if ($this->simulation) {
             $res = dibi::test('UPDATE [file] SET', $data, 'WHERE [id]=%i', $this->id);
         } else {
             $res = dibi::query('UPDATE [file] SET', $data, 'WHERE [id]=%i', $this->id);
         }
     } else {
         if ($this->simulation) {
             $res = dibi::test('INSERT INTO file', $data);
             $this->id = 999999999;
         } else {
             if ($this->force) {
                 $res = dibi::query('INSERT IGNORE INTO file', $data);
             } else {
                 $res = dibi::query('INSERT INTO file', $data);
             }
             $this->id = dibi::getInsertId();
         }
     }
     dibi::commit();
 }
Beispiel #21
0
 /**
  * Inserts page
  * @param array
  * @return someting
  */
 public function insertOne(array $values)
 {
     if (empty($values['meta_keywords'])) {
         $values['meta_keywords'] = NULL;
     }
     if (empty($values['meta_description'])) {
         $values['meta_description'] = NULL;
     }
     if (empty($values['content'])) {
         $values['content'] = NULL;
     }
     if (empty($values['picture_id'])) {
         $values['picture_id'] = NULL;
     }
     try {
         dibi::begin();
         dibi::query('INSERT INTO [:prefix:actualities]', array('added_at' => new DibiVariable('NOW()', 'sql')));
         $id = intval(dibi::query('SELECT LAST_INSERT_ID()')->fetchSingle());
         $values['ref_id'] = $id;
         $values['ref_type'] = pages::ACTUALITY;
         dibi::query('INSERT INTO [:prefix:pages]', $values);
         dibi::commit();
         return TRUE;
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
 }
Beispiel #22
0
 public function onSubmit(Form $form)
 {
     $data = $form->getValues();
     // Předáme data do šablony
     $this->template->values = $data;
     $queueId = uniqid();
     \dibi::begin();
     $gallery_id = $this->gallery->insert(array("name" => $data["name"]));
     // Přesumene uploadované soubory
     foreach ($data["upload"] as $file) {
         // $file je instance HttpUploadedFile
         $newFilePath = FILESTORAGE_DIR . "/q{" . $queueId . "}__f{" . rand(10, 99) . "}__" . $file->getName();
         // V produkčním módu nepřesunujeme soubory...
         if (!Environment::isProduction()) {
             if ($file->move($newFilePath)) {
                 $this->flashMessage("Soubor " . $file->getName() . " byl úspěšně přesunut!");
             } else {
                 $this->flashMessage("Při přesouvání souboru " . $file->getName() . " nastala chyba! Pro více informací se podívejte do logů.");
             }
         }
         $this->files->insert($file);
         $this->gallery->addFile($gallery_id, $file_id);
         dump($file);
     }
     \dibi::commit();
 }
 /**
  * Function for deleting a user
  *
  * @param String $userId
  * @param Array $deletedSubUsers
  * @throws Exception
  * @return void
  */
 public function deleteUser($userId, &$deletedSubUsers)
 {
     $children = array();
     try {
         // FIND ALL CHILDREN FIRST
         $children_results = dibi::query('SELECT [login] FROM [ajxp_user_rights] WHERE [repo_uuid] = %s AND [rights] = %s', "ajxp.parent_user", $userId);
         $all = $children_results->fetchAll();
         foreach ($all as $item) {
             $children[] = $item["login"];
         }
         dibi::begin();
         //This one is done by AUTH_DRIVER, not CONF_DRIVER
         //dibi::query('DELETE FROM [ajxp_users] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_rights] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_prefs] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_user_bookmarks] WHERE [login] = %s', $userId);
         dibi::query('DELETE FROM [ajxp_roles] WHERE [role_id] = %s', 'AJXP_USR_/' . $userId);
         dibi::commit();
         foreach ($children as $childId) {
             $this->deleteUser($childId, $deletedSubUsers);
             $deletedSubUsers[] = $childId;
         }
     } catch (DibiException $e) {
         throw new Exception('Failed to delete user, Reason: ' . $e->getMessage());
     }
 }
Beispiel #24
0
 public function saveEvent(Form $form)
 {
     $values = $form->getValues();
     if ($form['save']->isSubmittedBy()) {
         $categories = $values['categories'];
         unset($values['categories']);
         if ($form->onSuccess) {
             unset($values['agree']);
             $values['user_id'] = $this->user->loggedIn ? $this->user->id : null;
             $values['subject_id'] = 1;
             // anonymní akce // anonymní subjekt
             $values['approved'] = 0;
             $values['visible'] = 1;
             $values['reviewed'] = 0;
             $pd = $this->context->createService('events')->insert($values);
             $id = $pd->id;
             $this->flashMessage('Akce uložena do zásobníku', 'success');
             \dibi::begin();
             foreach ($categories as $n) {
                 \dibi::query('INSERT INTO [event_x_category] SET [event_id]=%i', $id, ', [category_id]=%i', $n);
             }
             \dibi::commit();
         }
         $form->addError('Something bad happend.');
     }
     $this->redirect('upload-photos', array('event_id' => $id));
 }
 /**
  * Insert manufacturer
  * @param array
  */
 public function insertOne(array $values)
 {
     try {
         dibi::begin();
         dibi::query('INSERT INTO [:prefix:manufacturers] ([id]) VALUES (NULL)');
         if (empty($values['meta_keywords'])) {
             $values['meta_keywords'] = NULL;
         }
         if (empty($values['meta_description'])) {
             $values['meta_description'] = NULL;
         }
         if (empty($values['content'])) {
             $values['content'] = NULL;
         }
         if (empty($values['picture_id'])) {
             $values['picture_id'] = NULL;
         }
         $values['ref_id'] = dibi::query('SELECT LAST_INSERT_ID()')->fetchSingle();
         $values['ref_type'] = pages::MANUFACTURER;
         dibi::query('INSERT INTO [:prefix:pages]', $values);
         dibi::commit();
         return TRUE;
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
 }
Beispiel #26
0
 public function run()
 {
     $startedAt = time();
     $tagFile = fopen($this->_tagFileName, 'r');
     $tagFileNameWithoutExt = str_replace('.tags', '', basename($this->_tagFileName));
     list($edition, $this->version) = explode('-', $tagFileNameWithoutExt);
     $this->_edition = ucfirst(substr($edition, 0, 1)) . 'E';
     $types = array('c' => 'addClass', 'i' => 'addInterface', 'd' => 'addConstant', 'f' => 'addMethod', 'm' => 'addMethod');
     $done = 0;
     exec('wc -l ' . $this->_tagFileName, $wcOut);
     $lines = (int) current($wcOut);
     $ignore = 0;
     foreach ($types as $currentType => $call) {
         rewind($tagFile);
         $tagFileLineNumber = 0;
         $ignore = 0;
         while ($line = fgets($tagFile)) {
             ++$tagFileLineNumber;
             if ('!_T' == substr($line, 0, 3)) {
                 // skip comment lines
                 ++$ignore;
                 continue;
             }
             list($tag, $path, $codeLine, $type, $sourceLineNumber) = explode("\t", $line);
             $codeLine = str_replace('/^', '', $codeLine);
             $codeLine = str_replace('$/;"', '', $codeLine);
             if (0 === strpos('downloader/', $path)) {
                 // skip downloader
                 ++$ignore;
                 continue;
             }
             if (1 != strlen($type)) {
                 echo "found invalid type \"{$type}\" on line {$tagFileLineNumber}";
                 exit(1);
             }
             if ($currentType == $type) {
                 dibi::begin();
                 $this->{"_{$call}"}($tag, $path, trim($codeLine));
                 dibi::commit();
                 ++$done;
                 $called = ltrim($call, '_');
             } else {
                 $called = "(skip {$type})";
             }
             $timeLeft = '';
             if (20 < $done) {
                 $timeSpent = time() - $startedAt;
                 $secondsLeft = round($lines * $timeSpent / $done) - $timeSpent;
                 $estimatedEnd = date('H:i', time() + $secondsLeft);
                 $timeLeft = ", approx. {$secondsLeft}s left";
                 if (90 < $secondsLeft) {
                     $minutesLeft = round($secondsLeft / 60);
                     $timeLeft = ", approx. {$minutesLeft}min left";
                     if (90 < $minutesLeft) {
                         $hoursLeft = round($minutesLeft / 60);
                         $timeLeft = ", approx. {$hoursLeft}h left";
                     }
                 }
                 $timeLeft .= ' - should finish at ' . $estimatedEnd . '';
             }
             $memusage = ', ' . round(memory_get_usage() / 1000) / 1000 . 'MB';
             $percent = number_format(100 * $done / ($lines - $ignore), 3);
             echo "\r  ➜ {$done}/" . ($lines - $ignore) . " done ({$percent}%{$timeLeft}{$memusage}, tag line {$tagFileLineNumber}): {$called}      ";
         }
         echo "\r  ➜ {$done}/" . ($lines - $ignore) . " done ({$percent}%{$timeLeft}{$memusage}, tag line {$tagFileLineNumber}): finished {$call}        \n";
     }
 }
 public function addEditOnFormSubmitted(AppForm $form)
 {
     // Permission form submitted
     $id = $this->getParam('id');
     $values = $form->getValues();
     if ($values['assertion_id'] == '0') {
         $values['assertion_id'] = NULL;
     }
     // add
     if (!$id) {
         $error = FALSE;
         dibi::begin();
         try {
             foreach ($values['privilege_id'] as $privi) {
                 foreach ($values['resource_id'] as $resou) {
                     foreach ($values['role_id'] as $role) {
                         if ($resou == '0') {
                             $resou = NULL;
                         }
                         if ($privi == '0') {
                             $privi = NULL;
                         }
                         dibi::query('INSERT INTO [' . TABLE_ACL . '] (role_id, privilege_id, resource_id, assertion_id, access) VALUES (%i, %i, %i, %iN, %b);', $role, $privi, $resou, $values['assertion_id'], $values['access']);
                     }
                 }
             }
             dibi::commit();
             $this->flashMessage('Permission was successfully assigned.', 'ok');
             if (ACL_CACHING) {
                 unset($this->cache['gui_acl']);
                 // invalidate cache
             }
             $this->redirect('Permission:');
         } catch (Exception $e) {
             $error = FALSE;
             $form->addError('Permission was not successfully assigned.');
             throw $e;
         }
         if ($error) {
             dibi::rollback();
         }
     } else {
         // edit
         try {
             dibi::query('UPDATE [' . TABLE_ACL . '] SET %a WHERE id=%i;', $values, $id);
             //                dibi::query('UPDATE ['.TABLE_ACL.'] SET (role_id, privilege_id, resource_id, assertion_id, access) VALUES (%i, %i, %i, %iN, %b) WHERE id=%i;', $role, $privi, $resou, $values['assertion_id'], $values['access'], $id);
             $this->flashMessage('Permission was successfully edited.', 'ok');
             if (ACL_CACHING) {
                 unset($this->cache['gui_acl']);
                 // invalidate cache
             }
             $this->redirect('Permission:');
         } catch (Exception $e) {
             $form->addError('Permission was not successfully edited.');
             throw $e;
         }
     }
 }
Beispiel #28
0
 public function saveDescription(Nette\Forms\Controls\SubmitButton $button)
 {
     $form = $button->getForm();
     try {
         $values = $form->getValues(TRUE);
         $categories = $values['categories'];
         if (count($categories) == 1 && $categories[0] == 1) {
             $form['categories']->addError('Vyberte prosím ještě jednu kategorii kromě Zdarma. Díky!');
             throw new \Nette\InvalidArgumentException('Vyberte prosím ještě jednu kategorii kromě Zdarma. Díky!');
         }
         unset($values['categories']);
         unset($values['rewrite']);
         //unset($values['type']);
         $this->id = $values['id'];
         if ($values['user_id'] == '') {
             $values['user_id'] = $this->user->id;
         }
         if (!$this->user->isInRole('administrator')) {
             $values['reviewed'] = 0;
         }
         $event = $this->context->createService('events')->wherePrimary($this->id);
         if ($event->count() == 1) {
             $event->update($values, true);
         } else {
             $pd = $this->context->createService('events')->insert($values);
             $this->id = $pd->id;
         }
         \dibi::begin();
         \dibi::query('DELETE FROM [event_x_category] WHERE [event_id]=%i', $this->id);
         foreach ($categories as $n) {
             \dibi::query('INSERT INTO [event_x_category] SET [event_id]=%i', $this->id, ', [category_id]=%i', $n);
         }
         \dibi::commit();
     } catch (Exception $e) {
         $form->addError($e->getMessage());
     }
     if ($form->isSuccess()) {
         $session = $this->presenter->getSession(get_class($this));
         unset($session['form']);
         $cache = new Cache($this->context->getService('cacheStorage'));
         $cache->clean(array(Cache::TAGS => array('events', 'event', 'term', 'terms', 'calendar')));
         $this->presenter->flashMessage('Fantazie! Popis události luxusně uložen!', 'success');
         if (isset($form['saveNew']) && $form['saveNew']->isSubmittedBy()) {
             $this->presenter->redirect('EventsWizard:w2', array('event_id' => $this->id));
         } elseif ($form['save']->isSubmittedBy()) {
             $this->redirect('this');
         } elseif ($form['saveBack']->isSubmittedBy()) {
             if (isset($this->backlink)) {
                 $this->presenter->restoreRequest($this->backlink);
             }
             unset($this->backlink);
             $this->presenter->redirect('Events:event', array('event_id' => $this->id));
         }
     }
 }
Beispiel #29
0
 function duplicate($form)
 {
     $values = $form->getValues();
     try {
         dibi::begin();
         if ($values['sourceLang'] == $values['destLang']) {
             throw new DuplicateException('Nemôžete kopírovať do toho istého jazyku.');
         }
         if (dibi::fetchSingle("SELECT 1 FROM [menu_item] WHERE lang = %s", $values['destLang']) == 1) {
             throw new DuplicateException('V jazyku "' . $values['destLang'] . '" sa už nachádzajú položky.');
         }
         self::recursionAddMenuItem(0, $values, 0);
         dibi::commit();
     } catch (DuplicateException $e) {
         $form->addError($e->getMessage());
     }
 }
 function save(NFORM $form)
 {
     $values = $form->getValues();
     $langs = Setting::getLangs();
     $id_product = $values['id_product'];
     $table_product_cols = Tools::getCollum('product');
     $table_product_lang_cols = Tools::getCollum('product_lang');
     //ulozenie jazuka
     foreach ($langs as $l) {
         $save_val = array();
         foreach ($table_product_lang_cols as $k => $c) {
             if (isset($values[$c . CategoryFormControl::$_separator . $l['iso']])) {
                 $save_val[$c] = $values[$c . CategoryFormControl::$_separator . $l['iso']];
             }
         }
         //pridanie linky rewrite
         if ($save_val['link_rewrite'] == '') {
             $save_val['link_rewrite'] = NStrings::webalize($values['name' . CategoryFormControl::$_separator . $l['iso']]);
         } else {
             $save_val['link_rewrite'] = NStrings::webalize($save_val['link_rewrite']);
         }
         ProductModel::save($save_val, $id_product, $l['id_lang']);
     }
     //ulozenie zakladnych hodnot
     $save_val = array();
     foreach ($table_product_cols as $p) {
         if (isset($values[$p])) {
             $save_val[$p] = $values[$p];
         }
     }
     ProductModel::save($save_val, $id_product, $l['id_lang']);
     //ulozit param
     /*
      * Iba ak je product bez parametrov
      */
     $val_product_param = Tools::getValuesForTable('product_param', $values);
     //prvy parameter
     $id_product_param = dibi::fetchSingle("SELECT id_product_param FROM [product_param] WHERE id_product = %i", $id_product, "ORDER BY sequence");
     ProductModel::setProductParamValue($val_product_param, $id_product_param);
     ProductModel::saveProductAlternative($id_product, $values['product_alternative']);
     dibi::begin();
     ProductModel::deleteProductFromCategories($id_product);
     ProductModel::addProductToCategory($values['id_categories'], $id_product);
     dibi::commit();
     ProductModel::invalidateCache();
     $this->flashMessage(_('Produkt bol uložený'));
     if ($form['btn_save']->isSubmittedBy()) {
         $s = NEnvironment::getSession("Admin_Eshop");
         $back_url = $s['back_url'];
         if ($back_url != '') {
             $this->redirectUrl($back_url);
         } else {
             $this->redirect('Eshop:default');
         }
     } else {
         $this->redirect('this');
     }
 }