/** * * Generate code using given parameters * @param array $paramsArray */ public function generate(OTCConfig $config = null) { if ($config === null) { $config = new OTCConfig(); } $paramsArray = $config->paramsArray; if (isset($paramsArray['r'])) { throw new RuntimeException("Key 'r' is not allowed to be present in \$paramsArray. Please remove or rename it."); } $paramsArray['r'] = generateRandomString(12); $keyValArray = array(); $keysUniqueCheckArray = array(); foreach ($paramsArray as $key => $value) { if (preg_match("/[:;]/", $key) or preg_match("/[:;]/", $value)) { throw new RuntimeException("Invalid characters in \$paramsArray. No ; or : characters are allowed!"); } if (in_array($key, $keysUniqueCheckArray)) { throw new RuntimeException("Duplicate key '{$key}' in \$paramsArray. It's not allowed!"); } array_push($keysUniqueCheckArray, $key); array_push($keyValArray, "{$key}:{$value}"); } $stringToEncrypt = implode(";", $keyValArray); $encryptedString = AES256::encrypt($stringToEncrypt); if (strlen($encryptedString) > static::CODE_MAX_LENGTH) { throw new RuntimeException("Resulting code is longer than allowed " . static::CODE_MAX_LENGTH . " characters!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_ONE_TIME_CODES'))->values(array("code" => $encryptedString, "multi" => $config->multiUse ? 1 : 0, "usage_limit" => $config->usageLimit ? $config->usageLimit : new Literal("NULL"), "not_cleanable" => $config->notCleanable ? 1 : 0, "valid_until" => $config->validityTime ? new Func('FROM_UNIXTIME', $qb->expr()->sum(new Func('UNIX_TIMESTAMP', new Func('NOW')), $config->validityTime)) : new Literal("NULL"))); $this->query->exec($qb->getSQL()); return $encryptedString; }
/** * Block given IP * @param string $ip */ public function blockIP($ip = null) { if ($ip === null) { $ip = $_SERVER['REMOTE_ADDR']; } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_SECURITY_FLOODER_IPS'))->values(array('ip' => $ip)); $this->query->exec($qb->getSQL()); }
public function addPermissionToGroup(Permission $perm, UserGroup $group, $args = null) { $qb = new QueryBuilder(); $values = array('group_id' => $group->id, 'permission_id' => $perm->id); if ($args !== null) { $values['args'] = serialize($args); } $qb->insert(Tbl::get('TBL_GROUPS_PERMISSIONS', 'UserManager'))->values($values); return $this->query->exec($qb->getSQL())->affected(); }
public function addGroup(TextsGroup $group) { if (empty($group->name)) { throw new InvalidArgumentException("You have to specify name for new group"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_TEXTS_GROUPS'))->values(array("name" => $group->name)); $this->query->exec($qb->getSQL()); return $this->query->affected(); }
public static function logCustom($name, $value) { $remoteIP = ""; if (isset($_SERVER['REMOTE_ADDR'])) { $remoteIP = $_SERVER['REMOTE_ADDR']; } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_MIXED_LOG'))->values(array("session_id" => session_id(), "name" => $name, "value" => $value, "ip" => $remoteIP)); Reg::get('sql')->exec($qb->getSQL()); }
public function fillUsersGps($userId, $leafId) { $qb = new QueryBuilder(); $qb->delete(Tbl::get('TBL_USERS_GPS'))->where($qb->expr()->equal(new Field('user_id'), $userId)); $this->query->exec($qb->getSQL()); $gpsTree = $this->getNodeTree($leafId); foreach ($gpsTree as $treeNode) { $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_USERS_GPS'))->values(array('user_id' => $userId, 'node_id' => $treeNode["node_id"])); $this->query->exec($qb->getSQL()); } }
public static function setControllerTemplateByHost(Host $host, $controller, $template) { $sql = MySqlDbManager::getQueryObject(); $qb = new QueryBuilder(); if (!empty($controller) or !empty($template)) { $qb->insert(Tbl::get('TBL_HOST_CONTROLLER_TEMPLATE'))->values(array('host_id' => $host->id, 'controller' => $controller, 'template' => $template))->onDuplicateKeyUpdate()->set(new Field('controller'), $controller)->set(new Field('template'), $template); } else { $qb->delete(Tbl::get('TBL_HOST_CONTROLLER_TEMPLATE'))->where($qb->expr()->equal(new Field('host_id'), $host->id)); } $sql->exec($qb->getSQL()); return $sql->affected(); }
/** * Insert ChatMessage object to database * * @param ChatMessage $chatMessage * @return int inserted message Id */ public function insertMessage(ChatMessage $chatMessage) { if (empty($chatMessage->senderUser->userId) or !is_numeric($chatMessage->senderUser->userId)) { throw new InvalidArgumentException("Invalid senderUser specified!"); } if (empty($chatMessage->receiverUser->userId) or !is_numeric($chatMessage->receiverUser->userId)) { throw new InvalidArgumentException("Invalid receiverUser specified!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_CHAT_MESSAGES'))->values(array("sender_user_id" => $chatMessage->senderUser->userId, "receiver_user_id" => $chatMessage->receiverUser->userId, "message" => $chatMessage->message, "is_system" => $chatMessage->is_system)); $this->query->exec($qb->getSQL()); return $this->query->getLastInsertId(); }
public function insertInvitation(ChatInvitation $invitation) { if (empty($invitation->inviterUser->userId) or !is_numeric($invitation->inviterUser->userId)) { throw new InvalidArgumentException("Invalid inviterUser specified!"); } if (empty($invitation->invitedUser->userId) or !is_numeric($invitation->invitedUser->userId)) { throw new InvalidArgumentException("Invalid invitedUser specified!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_CHAT_INVITATIONS'))->values(array("sender_user_id" => $invitation->inviterUser->userId, "receiver_user_id" => $invitation->invitedUser->userId, "invitation_message" => $invitation->invitationMessage, "status" => $invitation->status)); $this->query->exec($qb->getSQL()); return $this->query->getLastInsertId(); }
public static function logRequest($dbInstanceKey = null) { $sql = MySqlDbManager::getQueryObject($dbInstanceKey); $userId = "NULL"; $userObjectSerialized = "''"; $userObj = Reg::get(ConfigManager::getConfig("Users", "Users")->ObjectsIgnored->User); if ($userObj->isAuthorized()) { $userId = $userObj->id; $userObjectSerialized = "'" . mysql_real_escape_string(serialize($userObj)) . "'"; } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_REQUEST_LOG'))->values(array("user_id" => $userId, "user_obj" => $userObjectSerialized, "session_id" => session_id(), "get" => serialize($_GET), "post" => serialize($_POST), "server" => serialize($_SERVER), "cookies" => serialize($_COOKIE), "session" => serialize($_SESSION), "response" => ob_get_contents())); $sql->exec($qb->getSQL()); }
public static function addHost(Host $host) { if (empty($host->host)) { throw new InvalidArgumentException("Host name is empty!"); } $values = array("host" => $host->host); if (!empty($host->subdomain)) { $values["subdomain"] = $host->subdomain; } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_HOSTS', 'Host'))->values($values); $sql = MySqlDbManager::getQueryObject(); $sql->exec($qb->getSQL()); $host->id = $sql->getLastInsertId(); }
public function addText(Text $text, TextsGroup $group) { if (empty($text->name)) { throw new InvalidArgumentException("You have to specify name for new text"); } if (empty($group->id)) { throw new InvalidArgumentException("Group ID have to be specified"); } if (!is_numeric($group->id)) { throw new InvalidArgumentException("Group ID have to be integer"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_TEXTS'))->values(array('group_id' => $group->id, 'name' => $text->name, 'description' => $text->description)); $this->query->exec($qb->getSQL()); return $this->query->affected(); }
/** * * @param array $file e.g. $_FILES['photo'] * @return ConversationAttachment */ public function addAttachment($file) { $systemFilename = self::findNewFileName($this->config->uploadDir); $attachsImgUpConfig = $this->config->imageUploaderConfig; $attachsImgUpConfig->uploadDir = $this->config->uploadDir; if (in_array($file["type"], $attachsImgUpConfig->acceptedMimeTypes->toArray())) { ImageUploader::upload($file, $systemFilename, $attachsImgUpConfig); } else { FileUploader::upload($file, $systemFilename, $this->config->uploadDir); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_CONVERSATION_ATTACHEMENTS'))->values(array('system_filename' => $systemFilename, 'filename' => $file['name'], 'mime_type' => $file['type'])); $attachmentId = $this->query->exec($qb->getSQL())->getLastInsertId(); $filter = new ConversationAttachmentFilter(); $filter->setId($attachmentId); return $this->getAttachment($filter); }
public function addPhoto(UserPhoto $photo) { if (empty($photo)) { throw new InvalidArgumentException("\$photo is empty!"); } if (empty($photo->fileName)) { throw new InvalidArgumentException("photo fileName is have to been non empty string!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_USERS_PHOTOS'))->values(array("user_id" => $photo->userId, "filename" => $photo->fileName, "status" => $photo->status)); $this->query->exec($qb->getSQL()); $photoId = $this->query->getLastInsertId(); if ($photo->status == self::MODERATION_STATUS_APPROVED) { $this->correctDefaultPhoto($photo->userId); } return $photoId; }
public function hookInvalidLoginAttempt($params) { if ($this->config->AuxConfig->loginBruteForceProtectionEnabled) { if (isset($_SERVER['REMOTE_ADDR'])) { $sql = MySqlDbManager::getQueryObject(); $qb = new QueryBuilder(); $sql->exec($qb->select(new Field('count'))->from(Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG', 'RequestLimiter'))->where($qb->expr()->equal(new Field('ip'), $_SERVER['REMOTE_ADDR']))->getSQL()); $failedAuthCount = $sql->fetchField('count'); $newFailedAuthCount = $failedAuthCount + 1; if ($newFailedAuthCount >= $this->config->AuxConfig->failedLoginLimit) { Reg::get(ConfigManager::getConfig("Security", "RequestLimiter")->Objects->RequestLimiter)->blockIP(); $qb = new QueryBuilder(); $sql->exec($qb->delete(Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG', 'RequestLimiter'))->where($qb->expr()->equal(new Field('ip'), $_SERVER['REMOTE_ADDR']))->getSQL()); throw new RequestLimiterTooManyAuthTriesException("Too many unsucessful authorization tries."); } $qb = new QueryBuilder(); $sql->exec($qb->insert(Tbl::get('TBL_SECURITY_INVALID_LOGINS_LOG', 'RequestLimiter'))->values(array('ip' => $_SERVER['REMOTE_ADDR']))->onDuplicateKeyUpdate()->set(new Field('count'), $qb->expr()->sum(new Field('count'), 1))->getSQL()); } } }
public function addAlias(TextAlias $alias) { if (empty($alias->textValue) or !is_a($alias->textValue, "TextValue")) { throw new InvalidArgumentException("You have to specify valid TextValue object"); } if (!empty($alias->hostLanguageId) and is_numeric($alias->hostLanguageId)) { $hostLanguageId = $alias->hostLanguageId; } else { if (empty($alias->host) or !is_a($alias->host, "Host")) { throw new InvalidArgumentException("You have to specify valid Host object"); } if (empty($alias->language) or !is_a($alias->language, "Language")) { throw new InvalidArgumentException("You have to specify valid Language object"); } $hostLanguageId = HostLanguageManager::getHostLanguageId($alias->host, $alias->language); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_TEXTS_ALIASES'))->values(array("value_id" => $alias->textValue->id, "host_language" => $hostLanguageId)); $this->query->exec($qb->getSQL()); return $this->query->affected(); }
public function addEvent($name, $selfUserId, $userId = null, $data = array()) { if (empty($name)) { throw new InvalidArgumentException("\$name have to be non empty string"); } if (empty($selfUserId) or !is_numeric($selfUserId)) { throw new InvalidArgumentException("\$selfUserId have to be non zero integer"); } if ($userId !== null and (empty($userId) or !is_numeric($userId))) { throw new InvalidArgumentException("\$userId have to be non zero integer"); } if (!is_array($data)) { throw new InvalidArgumentException("\$data have to be array"); } $qb = new QueryBuilder(); $values = array('name' => $name, 'self_user_id' => $selfUserId, 'data' => serialize($data)); if ($userId !== null) { $values['user_id'] = $userId; } $qb->insert(Tbl::get('TBL_COMET_EVENTS'))->values($values); return $this->query->exec($qb->getSQL())->affected(); }
/** * Save custom entered field * * @param int $user_id * @param int $field_id * @param string $value * @return bool */ public function saveField($user_id, $field_id, $value) { $value = addslashes($value); $qb = new QueryBuilder(); $qb->delete(Tbl::get('TBL_CUST_SAVE'))->where($qb->expr()->equal(new Field('user_id'), $user_id))->andWhere($qb->expr()->equal(new Field('field_id'), $field_id)); $this->query->exec($qb->getSQL()); $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_CUST_SAVE'))->values(array('user_id' => $user_id, 'field_id' => $field_id, 'text' => $value)); if ($this->query->exec($qb->getSQL())) { return true; } return false; }
/** * @param integer $inviterUserId * @param integer $invitedUserId * @deprecated Sessions log insertd by mysql TRIGGER chat_sessions_log */ protected function insertSessionLog($inviterUserId, $invitedUserId) { if ($inviterUserId > $invitedUserId) { $userId1 = $inviterUserId; $userId2 = $invitedUserId; } else { $userId1 = $invitedUserId; $userId2 = $inviterUserId; } $qb = new QueryBuilder(); $qb->select(new Field('id'))->from(Tbl::get('TBL_CHAT_SESSIONS_LOG')); $andClause1 = new Andx(); $andClause1->add($qb->expr()->equal(new Field('user1_id', Tbl::get('TBL_CHAT_SESSIONS_LOG')), $userId1)); $andClause1->add($qb->expr()->equal(new Field('user2_id', Tbl::get('TBL_CHAT_SESSIONS_LOG')), $userId2)); $andClause2 = new Andx(); $andClause2->add($qb->expr()->equal(new Field('user1_id', Tbl::get('TBL_CHAT_SESSIONS_LOG')), $userId2)); $andClause2->add($qb->expr()->equal(new Field('user2_id', Tbl::get('TBL_CHAT_SESSIONS_LOG')), $userId1)); $orClause = new Orx(); $orClause->add($andClause1); $orClause->add($andClause2); $qb->andWhere($orClause); $this->query->exec($qb->getSQL()); $qb = new QueryBuilder(); if ($this->query->countRecords()) { $sesionId = $this->query->fetchField("id"); $qb->update(Tbl::get('TBL_CHAT_SESSIONS_LOG'))->set(new Field('datetime'), date(DEFAULT_DATETIME_FORMAT))->where($qb->expr()->equal(new Field('id'), $sesionId)); } else { $qb->insert(Tbl::get('TBL_CHAT_SESSIONS_LOG'))->values(array('user1_id' => $userId1, 'user2_id' => $userId2, 'datetime' => date(DEFAULT_DATETIME_FORMAT))); } $this->query->exec($qb->getSQL()); return $this->query->affected(); }
/** * Save crop settings for given Image * * @param Image $image * @param string $modelName * @param integer $x * @param integer $y * @param integer $width * @param integer $height * @throws InvalidArgumentException * @throws ImageModificatorException */ public function saveCropSettings(Image $image, $modelName, Config $cropSettings) { if (!isset($this->config->imageModels->{$modelName})) { throw new InvalidArgumentException("There is no such image model with name {$modelName}"); } if (empty($image->fileName)) { throw new ImageModificatorException("Image is not initialized!"); } list($imageW, $imageH) = $image->getDimensions(); list($ratioW, $ratioH) = explode(":", $this->config->imageModels->{$modelName}->actions->{self::ACTION_CROP}->ratio); if ($cropSettings->x + $cropSettings->width > $imageW or $cropSettings->y + $cropSettings->height > $imageH) { throw new InvalidArgumentException("Crop window is not fitting into image!"); } if ($cropSettings->height == 0 or round($cropSettings->width / $cropSettings->height) != round($ratioW / $ratioH)) { throw new InvalidArgumentException("Given crop window is not at needed ratio!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get("TBL_CROP_SETTINGS"))->values(array('model_name' => $modelName, 'filename' => $image->fileName, 'x' => $cropSettings->x, 'y' => $cropSettings->y, 'width' => $cropSettings->width, 'height' => $cropSettings->height))->onDuplicateKeyUpdate()->set(new Field('x'), $cropSettings->x)->set(new Field('y'), $cropSettings->y)->set(new Field('width'), $cropSettings->width)->set(new Field('height'), $cropSettings->height); $this->query->exec($qb->getSQL()); }
/** * Add new Alias for current db config * @param ConfigDB $configDB * @param Integer $aliasHostLangId new aliases value host lang id * @throws InvalidArgumentException */ public static function addDBConfigAlias(ConfigDB $configDB, $aliasHostLangId) { if (empty($configDB)) { throw new InvalidArgumentException("ConfigDB object is empty!"); } if (!is_numeric($configDB->id)) { throw new InvalidArgumentException("ConfigDB object's id is not numeric!"); } if (!is_numeric($aliasHostLangId)) { throw new InvalidArgumentException("ConfigDB object's id is not numeric!"); } $qb = new QueryBuilder(); $arrayValues = array("location" => implode(":", $configDB->location), "name" => $configDB->name, "value" => $configDB->value, "host_lang_id" => $aliasHostLangId, "alias_of" => $configDB->id); $qb->insert(Tbl::get("TBL_CONFIGS"))->values($arrayValues); $sql = MySqlDbManager::getQueryObject(); $sql->exec($qb->getSQL()); }
/** * Set user answers by their ids * * @param array $answers an array containing user's answers */ public function setAnswersByIds($answers) { if (is_array($answers)) { $qb = new QueryBuilder(); $qb->delete(Tbl::get('TBL_PROFILE_SAVE'))->where($qb->expr()->equal(new Field("user_id"), $this->userId)); $this->query->exec($qb->getSQL()); foreach ($answers as $answer) { if (is_numeric($answer)) { $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_PROFILE_SAVE'))->values(array("user_id" => $this->userId, "profile_id" => $answer)); $this->query->exec($qb->getSQL()); } } $this->initUserAnswers(); } else { throw new UnexpectedValueException("\$answers have to array"); } }
public function addUserToGroup(User $user, UserGroup $group) { $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_USERS_GROUPS', 'UserManager'))->values(array('user_id' => $user->id, 'group_id' => $group->id)); return $this->query->exec($qb->getSQL())->affected(); }
public function newdata($table) { $value = $this->nameChampbyTable($table); if (!isset($_GET['insert' . $value[1]])) { return; } $set = false; for ($i = 1; $i < count($value); $i++) { if ($_GET['insert' . $value[$i]] == '') { $set = true; } } if ($set) { ?> <script type="text/javascript"> alert("tous les champs doivent être rempli !!!!!!!"); </script><?php return; } $builder = new QueryBuilder($this->database); for ($i = 1; $i < count($value); $i++) { $datainsert[$value[$i]] = addslashes($_GET["insert" . $value[$i]]); } $sql = $builder->insert($table, $datainsert); $this->database->query($sql); return; }
/** * Blacklist given country * * @param string $countryCode * @throws InvalidArgumentException * @throws RuntimeException */ public function blackListCountry($countryCode) { if (!Reg::get(ConfigManager::getConfig('GeoIP', 'GeoIP')->Objects->GeoIP)->isValidCountryCode($countryCode)) { throw new InvalidArgumentException("Invalid country code specified for blacklisting"); } $qb = new QueryBuilder(); $qb->select($qb->expr()->count('*', 'count'))->from(Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES', 'IpFilter'))->where($qb->expr()->equal(new Field('country'), $countryCode)); $this->query->exec($qb->getSQL()); if ($this->query->fetchField('count') != 0) { throw new RuntimeException("Sorry, this country already blacklisted!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_SECURITY_BLACKLISTED_COUNTRIES', 'IpFilter'))->values(array("country" => $countryCode)); $this->query->exec($qb->getSQL()); }
/** * Insert query string generator * * @param array $pageInfo * @param int $langId * @param int $hostId * @param sring $module * @param string $page * @return string */ private static function insertQueryString(array $pageInfo, $langId = null, $hostId = null, $module = null, $page = null) { $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_PAGE_INFO', 'PageInfo'))->values(array("lang_id" => $langId === null ? new Literal('NULL') : $langId, "host_id" => $hostId === null ? new Literal('NULL') : $hostId, "module" => $module === null ? new Literal('NULL') : $module, "page" => $page === null ? new Literal('NULL') : $page, "title" => $pageInfo['title'], "meta_keywords" => $pageInfo['keywords'], "meta_description" => $pageInfo['description'])); return $qb->getSQL(); }
/** * Generated from @assert insert('user', array('id' => 1, 'name' => 'test'))->text() [==] "INSERT INTO `user` (`id`, `name`) VALUES (:id, :name)". * * @covers Kotchasan\Database\QueryBuilder::insert */ public function testInsert() { $this->assertEquals("INSERT INTO `user` (`id`, `name`) VALUES (:id, :name)", $this->object->insert('user', array('id' => 1, 'name' => 'test'))->text()); }
/** * Move finished Job from active jobs table to archive table * Helper function * @access private * @param JobQueueObj $job * */ private function moveJobToArchive(JobQueueObj $job) { if (!is_numeric($job->id)) { throw JobQueueException("Job id is not numeric!"); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_JOB_QUEUE_ARCHIVE'))->values(array("name" => $job->name, "properties" => serialize($job->properties), "status" => $job->status, "start_date" => $job->startDate, "log_message" => $job->logMessage)); $this->query->exec($qb->getSQL()); $qb = new QueryBuilder(); $qb->delete(Tbl::get('TBL_JOB_QUEUE'))->where($qb->expr()->equal(new Field('id'), $job->id)); $this->query->exec($qb->getSQL()); }
public function addTextValue(TextValue $textValue) { if (empty($textValue->text) or !is_a($textValue->text, "Text")) { throw new InvalidArgumentException("You have to specify valid Text object for adding TextValue"); } if (empty($textValue->value)) { throw new InvalidArgumentException("You have to specify Value attribute for adding TextValue"); } if (is_null($textValue->display) or !is_numeric($textValue->display)) { throw new InvalidArgumentException("You have to specify valid Display attribute for adding TextValue"); } if (!empty($textValue->hostLanguageId) and is_numeric($textValue->hostLanguageId)) { $hostLanguageId = $textValue->hostLanguageId; } else { if (empty($textValue->host) or !is_a($textValue->host, "Host")) { throw new InvalidArgumentException("You have to specify valid Host object"); } if (empty($textValue->language) or !is_a($textValue->language, "Language")) { throw new InvalidArgumentException("You have to specify valid Language object"); } $hostLanguageId = HostLanguageManager::getHostLanguageId($textValue->host, $textValue->language); } $qb = new QueryBuilder(); $qb->insert(Tbl::get('TBL_TEXTS_VALUES'))->values(array("text_id" => $textValue->text->id, "value" => $textValue->value, "host_language" => $hostLanguageId, "display" => $textValue->display)); $this->query->exec($qb->getSQL()); return $this->query->affected(); }
public function save() { if (empty($this->modified_data) && !$this->new) { return true; } if ($this->validate()) { $data = array_intersect_key($this->data, array_flip(static::$fields)); if ($this->new) { $sql = QueryBuilder::insert(get_called_class()); $sql->values($data); } else { $pk = static::$primary_key; $data = array_intersect_key($data, array_flip($this->modified_data)); $sql = QueryBuilder::update(get_called_class()); $sql->set($data); $sql->where(array($pk => $this->{$pk})); } if (method_exists($this, 'before_save')) { if (!$this->before_save($sql)) { $this->errors[] = "before_save failed"; return false; } } if (!$sql->execute()) { $this->error[] = "Save failed on SQL-Level!"; return false; } if (method_exists($this, 'after_create') && $this->new) { $this->after_create(); } elseif (method_exists($this, 'after_update')) { $this->after_update(); } if (method_exists($this, 'after_save')) { $this->after_save(); } return true; } else { $this->errors[] = "validation failed"; return false; } }