123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716 |
- <?php
- defined('GNUSOCIAL') || die();
- abstract class Managed_DataObject extends Memcached_DataObject
- {
-
- public static function schemaDef()
- {
- throw new MethodNotImplementedException(__METHOD__);
- }
-
- public static function getKV($k, $v = null)
- {
- return parent::getClassKV(get_called_class(), $k, $v);
- }
-
- public static function pkeyGet(array $kv)
- {
- return parent::pkeyGetClass(get_called_class(), $kv);
- }
- public static function pkeyCols()
- {
- return parent::pkeyColsClass(get_called_class());
- }
-
- public static function multiGet(
- string $keyCol,
- array $keyVals,
- bool $skipNulls = true,
- bool $preserve = false
- ): object {
- return parent::multiGetClass(
- get_called_class(),
- $keyCol,
- $keyVals,
- $skipNulls,
- $preserve
- );
- }
-
- public static function pivotGet($keyCol, array $keyVals, array $otherCols = [])
- {
- return parent::pivotGetClass(get_called_class(), $keyCol, $keyVals, $otherCols);
- }
-
- public static function listFind($keyCol, array $keyVals)
- {
- return parent::listFindClass(get_called_class(), $keyCol, $keyVals);
- }
-
- public static function listGet($keyCol, array $keyVals)
- {
- return parent::listGetClass(get_called_class(), $keyCol, $keyVals);
- }
-
- public function table()
- {
- $table = static::schemaDef();
- return array_map(array($this, 'columnBitmap'), $table['fields']);
- }
-
- public function keys()
- {
- return array_keys($this->keyTypes());
- }
-
- public function sequenceKey()
- {
- $table = static::schemaDef();
- foreach ($table['fields'] as $name => $column) {
- if ($column['type'] == 'serial') {
-
-
- return array($name, true, false);
- }
- }
-
- return array(false, false, false);
- }
-
- public function keyTypes()
- {
- $table = static::schemaDef();
- $keys = array();
- if (!empty($table['unique keys'])) {
- foreach ($table['unique keys'] as $idx => $fields) {
- foreach ($fields as $name) {
- $keys[$name] = 'U';
- }
- }
- }
- if (!empty($table['primary key'])) {
- foreach ($table['primary key'] as $name) {
- $keys[$name] = 'K';
- }
- }
- return $keys;
- }
-
- public function columnBitmap($column)
- {
- $type = $column['type'];
-
- $intTypes = [
- 'int',
- 'float',
- 'serial',
- 'numeric'
- ];
- if (in_array($type, $intTypes)) {
- $style = DB_DATAOBJECT_INT;
- } else {
- $style = DB_DATAOBJECT_STR;
- }
-
- $formatStyles = [
- 'blob' => DB_DATAOBJECT_BLOB,
- 'text' => DB_DATAOBJECT_TXT,
- 'bool' => DB_DATAOBJECT_BOOL,
- 'date' => DB_DATAOBJECT_DATE,
- 'time' => DB_DATAOBJECT_TIME,
- 'datetime' => DB_DATAOBJECT_DATE | DB_DATAOBJECT_TIME,
- ];
- if (isset($formatStyles[$type])) {
- $style |= $formatStyles[$type];
- }
-
- if (!empty($column['not null'])) {
- $style |= DB_DATAOBJECT_NOTNULL;
- }
- return $style;
- }
- public function links()
- {
- $links = array();
- $table = static::schemaDef();
- foreach ($table['foreign keys'] as $keyname => $keydef) {
- if (count($keydef) == 2 && is_string($keydef[0]) && is_array($keydef[1]) && count($keydef[1]) == 1) {
- if (isset($keydef[1][0])) {
- $links[$keydef[1][0]] = $keydef[0].':'.$keydef[1][1];
- }
- }
- }
- return $links;
- }
-
- public function _allCacheKeys()
- {
- $table = static::schemaDef();
- $ckeys = array();
- if (!empty($table['unique keys'])) {
- $keyNames = $table['unique keys'];
- foreach ($keyNames as $idx => $fields) {
- $val = array();
- foreach ($fields as $name) {
- $val[$name] = self::valueString($this->$name);
- }
- $ckeys[] = self::multicacheKey($this->tableName(), $val);
- }
- }
- if (!empty($table['primary key'])) {
- $fields = $table['primary key'];
- $val = array();
- foreach ($fields as $name) {
- $val[$name] = self::valueString($this->$name);
- }
- $ckeys[] = self::multicacheKey($this->tableName(), $val);
- }
- return $ckeys;
- }
-
- public static function getByPK(array $vals)
- {
- $classname = get_called_class();
- $pkey = static::pkeyCols();
- if (is_null($pkey)) {
- throw new ServerException("Failed to get primary key columns for class '{$classname}'");
- }
- $object = new $classname();
- foreach ($pkey as $col) {
- if (!array_key_exists($col, $vals)) {
- throw new ServerException("Missing primary key column '{$col}' for ".get_called_class()." among provided keys: ".implode(',', array_keys($vals)));
- } elseif (is_null($vals[$col])) {
- throw new ServerException("NULL values not allowed in getByPK for column '{$col}'");
- }
- $object->$col = $vals[$col];
- }
- if (!$object->find(true)) {
- throw new NoResultException($object);
- }
- return $object;
- }
-
- public static function getByKeys(array $vals)
- {
- $classname = get_called_class();
- $object = new $classname();
- $keys = $object->keys();
- if (is_null($keys)) {
- throw new ServerException("Failed to get key columns for class '{$classname}'");
- }
- foreach ($keys as $col) {
- if (!array_key_exists($col, $vals)) {
- continue;
- } elseif (is_null($vals[$col])) {
- throw new ServerException("NULL values not allowed in getByKeys for column '{$col}'");
- }
- $object->$col = $vals[$col];
- }
- if (!$object->find(true)) {
- throw new NoResultException($object);
- }
- return $object;
- }
- public static function getByID($id)
- {
- if (!property_exists(get_called_class(), 'id')) {
- throw new ServerException('Trying to get undefined property of dataobject class.');
- }
- if (empty($id)) {
- throw new EmptyPkeyValueException(get_called_class(), 'id');
- }
-
-
- return static::getByPK(array('id' => $id));
- }
- public static function getByUri($uri)
- {
- if (!property_exists(get_called_class(), 'uri')) {
- throw new ServerException('Trying to get undefined property of dataobject class.');
- }
- if (empty($uri)) {
- throw new EmptyPkeyValueException(get_called_class(), 'uri');
- }
- $class = get_called_class();
- $obj = new $class();
- $obj->uri = $uri;
- if (!$obj->find(true)) {
- throw new NoResultException($obj);
- }
- return $obj;
- }
-
- public function getID()
- {
-
- if (!isset($this->id)) {
- throw new Exception('No ID set.');
- } elseif (empty($this->id)) {
- throw new Exception('Empty ID for object! (not inserted yet?).');
- }
- return intval($this->id);
- }
-
- public function isNull(string $key): bool
- {
- if (array_key_exists($key, get_object_vars($this))
- && is_null($this->$key)) {
-
- return true;
- } elseif (is_object($this->$key)
- && $this->$key instanceof DB_DataObject_Cast
- && $this->$key->type === 'sql') {
-
- return (strcasecmp($this->$key->value, 'NULL') == 0);
- } elseif (DB_DataObject::_is_null($this, $key)) {
-
-
- return true;
- }
- return false;
- }
-
- public function getAliases()
- {
- return array_keys($this->getAliasesWithIDs());
- }
- public function getAliasesWithIDs()
- {
- $aliases = array();
- $aliases[$this->getUri()] = $this->getID();
- try {
- $aliases[$this->getUrl()] = $this->getID();
- } catch (InvalidUrlException $e) {
-
- }
- if (common_config('fix', 'fancyurls')) {
-
- foreach ($aliases as $alias=>$id) {
- try {
-
- $alt_url = common_fake_local_fancy_url($alias);
-
- $aliases[$alt_url] = $id;
- } catch (Exception $e) {
-
- }
- try {
-
- $alt_url = common_fake_local_nonfancy_url($alias);
-
- $aliases[$alt_url] = $id;
- } catch (Exception $e) {
-
- }
- }
- }
- return $aliases;
- }
-
- private function updateAutoTimestamps(): void
- {
- $table = static::schemaDef();
- foreach ($table['fields'] as $name => $col) {
- if ($col['type'] === 'timestamp'
- && !array_key_exists('default', $col)
- && !isset($this->$name)) {
- $this->$name = common_sql_now();
- }
- }
- }
-
- public function updateWithKeys(Managed_DataObject $orig, ?string $pid = null)
- {
- if (!$orig instanceof $this) {
- throw new ServerException('Tried updating a DataObject with a different class than itself.');
- }
- if ($this->N <1) {
- throw new ServerException('DataObject must be the result of a query (N>=1) before updateWithKeys()');
- }
- $this->onUpdateKeys($orig);
-
- $this->query('START TRANSACTION');
-
-
- $this->updateAutoTimestamps();
- $parts = [];
- foreach ($this->keys() as $k) {
- $v = $this->table()[$k];
- if ($this->$k !== $orig->$k) {
- if (is_object($this->$k) && $this->$k instanceof DB_DataObject_Cast) {
- $value = $this->$k->toString($v, $this->getDatabaseConnection());
- } elseif (DB_DataObject::_is_null($this, $k)) {
- $value = 'NULL';
- } elseif ($v & DB_DATAOBJECT_STR) {
- $value = $this->_quote((string) $this->$k);
- } else {
- $value = (int) $this->$k;
- }
- $parts[] = "{$k} = {$value}";
- }
- }
- if (count($parts) == 0) {
-
- if ($this->update($orig) === false) {
- common_log_db_error($this, 'UPDATE', __FILE__);
-
- $this->query('ROLLBACK');
- throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
- }
- $orig->decache();
- $this->encache();
-
- $this->query('COMMIT');
-
- return true;
- }
- if ($pid === null) {
- $schema = static::schemaDef();
- $pid = $schema['primary key'];
- unset($schema);
- }
- $pidWhere = [];
- foreach ((array) $pid as $pidCol) {
- $pidWhere[] = sprintf('%1$s = %2$s', $pidCol, $this->_quote($orig->$pidCol));
- }
- if (empty($pidWhere)) {
- throw new ServerException('No primary ID column(s) set for updateWithKeys');
- }
- $qry = sprintf(
- 'UPDATE %1$s SET %2$s WHERE %3$s',
- $this->escapedTableName(),
- implode(', ', $parts),
- implode(' AND ', $pidWhere)
- );
- $result = $this->query($qry);
- if ($result === false) {
- common_log_db_error($this, 'UPDATE', __FILE__);
-
- $this->query('ROLLBACK');
- throw new ServerException("Could not UPDATE key fields for {$this->tableName()}");
- }
-
-
-
- if ($this->update($orig) === false) {
- common_log_db_error($this, 'UPDATE', __FILE__);
-
- $this->query('ROLLBACK');
- throw new ServerException("Could not UPDATE non-keys for {$this->tableName()}");
- }
- $orig->decache();
- $this->encache();
-
- $this->query('COMMIT');
-
- return $result;
- }
- public static function beforeSchemaUpdate()
- {
-
- }
- public static function newUri(Profile $actor, Managed_DataObject $object, $created = null)
- {
- if (is_null($created)) {
- $created = common_sql_now();
- }
- return TagURI::mint(
- strtolower(get_called_class()) . ':%d:%s:%d:%s',
- $actor->getID(),
- ActivityUtils::resolveUri($object->getObjectType(), true),
- $object->getID(),
- common_date_iso8601($created)
- );
- }
- protected function onInsert()
- {
-
- }
- protected function onUpdate($dataObject=false)
- {
-
- }
- protected function onUpdateKeys(Managed_DataObject $orig)
- {
-
- }
- public function insert()
- {
- $this->onInsert();
- $result = parent::insert();
-
-
-
- if ($result) {
- $this->updateAutoTimestamps();
- }
- return $result;
- }
- public function update($dataObject = false)
- {
- $this->onUpdate($dataObject);
-
-
- $this->updateAutoTimestamps();
- return parent::update($dataObject);
- }
- }
|