/** * @brief returns true if and only if a user with the given uuid exists in the LDAP * @param string a unique user identifier * @return a boolean value */ public function uuidExists($uuid) { //check backend status if (!$this->enabled) { return false; } //check tables $query = \OCP\DB::prepare('SELECT COUNT(*) FROM *PREFIX*ldap_user_mapping WHERE owncloud_name = ?'); $result = $query->execute(array($uuid)); if (!\OCP\DB::isError($result)) { $count = $result->fetchAll(\PDO::FETCH_COLUMN, 0); if ($count[0] === 1) { return true; } } //check primary LDAP server $this->connect(); $uuid = $this->access->escapeFilterPart($uuid); $filter = \OCP\Util::mb_str_replace('%uid', $uuid, $this->access->connection->ldapLoginFilter, 'UTF-8'); $result = $this->access->fetchListOfUsers($filter, $this->connection->ldapUuidAttribute); if (count($result) === 1 && $result[0]['count'] === 1) { return true; } return false; }
/** * Background scanner main job * @return null */ public function run() { if (!$this->initFS()) { return; } // locate files that are not checked yet $dirMimetypeId = \OC::$server->getMimeTypeLoader()->getId('httpd/unix-directory'); $sql = 'SELECT `*PREFIX*filecache`.`fileid`, `*PREFIX*storages`.*' . ' FROM `*PREFIX*filecache`' . ' LEFT JOIN `*PREFIX*files_antivirus` ON `*PREFIX*files_antivirus`.`fileid` = `*PREFIX*filecache`.`fileid`' . ' JOIN `*PREFIX*storages` ON `*PREFIX*storages`.`numeric_id` = `*PREFIX*filecache`.`storage`' . ' WHERE `mimetype` != ?' . ' AND (`*PREFIX*storages`.`id` LIKE ? OR `*PREFIX*storages`.`id` LIKE ?)' . ' AND (`*PREFIX*files_antivirus`.`fileid` IS NULL OR `mtime` > `check_time`)' . ' AND `path` LIKE ?'; $stmt = \OCP\DB::prepare($sql, 5); try { $result = $stmt->execute(array($dirMimetypeId, 'local::%', 'home::%', 'files/%')); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); return; } } catch (\Exception $e) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return; } $view = new \OC\Files\View('/'); while ($row = $result->fetchRow()) { $path = $view->getPath($row['fileid']); if (!is_null($path)) { $item = new Item($this->l10n, $view, $path, $row['fileid']); $scanner = $this->scannerFactory->getScanner(); $status = $scanner->scan($item); $status->dispatch($item, true); } } \OC_Util::tearDownFS(); }
protected function shareFileOrFolderWithGroup($params) { // User performing the share $subject = 'shared_sharing_group_self'; $this->shareNotificationForSharer($subject, $params['shareWith'], $params['fileSource'], $params['itemType']); // Members of the new group $affectedUsers = array(); $usersInGroup = Data::readGroupUsers($params['shareWith']); foreach ($usersInGroup as $user) { $affectedUsers[$user] = $params['fileTarget']; } // Remove the triggering user, we already managed his notifications unset($affectedUsers[$this->currentUser]); if (empty($affectedUsers)) { return; } $filteredStreamUsersInGroup = $this->userSettings->filterUsersBySetting($usersInGroup, 'stream', Files_Sharing::TYPE_SHARED); $filteredEmailUsersInGroup = $this->userSettings->filterUsersBySetting($usersInGroup, 'email', Files_Sharing::TYPE_SHARED); // Check when there was a naming conflict and the target is different // for some of the users $query = DB::prepare('SELECT `share_with`, `file_target` FROM `*PREFIX*share` WHERE `parent` = ? '); $result = $query->execute(array($params['id'])); if (DB::isError($result)) { Util::writeLog('OCA\\Activity\\Hooks::shareFileOrFolderWithGroup', DB::getErrorMessage($result), Util::ERROR); } else { while ($row = $result->fetchRow()) { $affectedUsers[$row['share_with']] = $row['file_target']; } } foreach ($affectedUsers as $user => $path) { if (empty($filteredStreamUsersInGroup[$user]) && empty($filteredEmailUsersInGroup[$user])) { continue; } $this->addNotificationsForUser($user, 'shared_with_by', array($path, $this->currentUser), $path, $params['itemType'] === 'file', !empty($filteredStreamUsersInGroup[$user]), !empty($filteredEmailUsersInGroup[$user]) ? $filteredEmailUsersInGroup[$user] : 0); } }
/** * @brief Find which users can access a shared item * @param $path to the file * @param $user owner of the file * @param include owner to the list of users with access to the file * @return array * @note $path needs to be relative to user data dir, e.g. 'file.txt' * not '/admin/data/file.txt' */ public static function getUsersSharingFile($path, $user, $includeOwner = false) { $shares = array(); $publicShare = false; $source = -1; $cache = false; $view = new \OC\Files\View('/' . $user . '/files/'); $meta = $view->getFileInfo(\OC\Files\Filesystem::normalizePath($path)); if ($meta !== false) { $source = $meta['fileid']; $cache = new \OC\Files\Cache\Cache($meta['storage']); } while ($source !== -1) { // Fetch all shares of this file path from DB $query = \OC_DB::prepare('SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ?'); $result = $query->execute(array($source, self::SHARE_TYPE_USER)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { while ($row = $result->fetchRow()) { $shares[] = $row['share_with']; } } // We also need to take group shares into account $query = \OC_DB::prepare('SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ?'); $result = $query->execute(array($source, self::SHARE_TYPE_GROUP)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { while ($row = $result->fetchRow()) { $usersInGroup = \OC_Group::usersInGroup($row['share_with']); $shares = array_merge($shares, $usersInGroup); } } //check for public link shares if (!$publicShare) { $query = \OC_DB::prepare('SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ?'); $result = $query->execute(array($source, self::SHARE_TYPE_LINK)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { if ($result->fetchRow()) { $publicShare = true; } } } // let's get the parent for the next round $meta = $cache->get((int) $source); if ($meta !== false) { $source = (int) $meta['parent']; } else { $source = -1; } } // Include owner in list of users, if requested if ($includeOwner) { $shares[] = $user; } return array("users" => array_unique($shares), "public" => $publicShare); }
public static function updateDBProperties($contactid, $vcard = null) { $stmt = \OCP\DB::prepare('DELETE FROM `' . self::ContactsProbTable . '` WHERE `contactid` = ?'); try { $stmt->execute(array($contactid)); } catch (\Exception $e) { \OCP\Util::writeLog(self::$appname, __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog(self::$appname, __METHOD__ . ', id: ' . $id, \OCP\Util::DEBUG); throw new \Exception(App::$l10n->t('There was an error deleting properties for this contact.')); } if (is_null($vcard)) { return; } $stmt = \OCP\DB::prepare('INSERT INTO `' . self::ContactsProbTable . '` ' . '(`userid`, `contactid`,`name`,`value`,`preferred`) VALUES(?,?,?,?,?)'); foreach ($vcard->children as $property) { if (!in_array($property->name, self::$index_properties)) { continue; } $preferred = 0; foreach ($property->parameters as $parameter) { if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') { $preferred = 1; break; } } try { $result = $stmt->execute(array(\OCP\User::getUser(), $contactid, $property->name, $property->getValue(), $preferred)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog(self::$appname, __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog(self::$appname, __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return false; } } }
/** * Find which users can access a shared item * @param string $path to the file * @param string $ownerUser owner of the file * @param boolean $includeOwner include owner to the list of users with access to the file * @param boolean $returnUserPaths Return an array with the user => path map * @param boolean $recursive take all parent folders into account (default true) * @return array * @note $path needs to be relative to user data dir, e.g. 'file.txt' * not '/admin/data/file.txt' */ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = false, $returnUserPaths = false, $recursive = true) { Filesystem::initMountPoints($ownerUser); $shares = $sharePaths = $fileTargets = array(); $publicShare = false; $remoteShare = false; $source = -1; $cache = false; $view = new \OC\Files\View('/' . $ownerUser . '/files'); $meta = $view->getFileInfo($path); if ($meta) { $path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files')); } else { // if the file doesn't exists yet we start with the parent folder $meta = $view->getFileInfo(dirname($path)); } if ($meta !== false) { $source = $meta['fileid']; $cache = new \OC\Files\Cache\Cache($meta['storage']); } while ($source !== -1) { // Fetch all shares with another user if (!$returnUserPaths) { $query = \OC_DB::prepare('SELECT `share_with`, `file_source`, `file_target` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_USER)); } else { $query = \OC_DB::prepare('SELECT `share_with`, `file_source`, `file_target` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique)); } if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { $shares[] = $row['share_with']; if ($returnUserPaths) { $fileTargets[(int) $row['file_source']][$row['share_with']] = $row; } } } // We also need to take group shares into account $query = \OC_DB::prepare('SELECT `share_with`, `file_source`, `file_target` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_GROUP)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { $usersInGroup = \OC_Group::usersInGroup($row['share_with']); $shares = array_merge($shares, $usersInGroup); if ($returnUserPaths) { foreach ($usersInGroup as $user) { if (!isset($fileTargets[(int) $row['file_source']][$user])) { // When the user already has an entry for this file source // the file is either shared directly with him as well, or // he has an exception entry (because of naming conflict). $fileTargets[(int) $row['file_source']][$user] = $row; } } } } } //check for public link shares if (!$publicShare) { $query = \OC_DB::prepare(' SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1); $result = $query->execute(array($source, self::SHARE_TYPE_LINK)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { if ($result->fetchRow()) { $publicShare = true; } } } //check for remote share if (!$remoteShare) { $query = \OC_DB::prepare(' SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1); $result = $query->execute(array($source, self::SHARE_TYPE_REMOTE)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { if ($result->fetchRow()) { $remoteShare = true; } } } // let's get the parent for the next round $meta = $cache->get((int) $source); if ($recursive === true && $meta !== false) { $source = (int) $meta['parent']; } else { $source = -1; } } // Include owner in list of users, if requested if ($includeOwner) { $shares[] = $ownerUser; } if ($returnUserPaths) { $fileTargetIDs = array_keys($fileTargets); $fileTargetIDs = array_unique($fileTargetIDs); if (!empty($fileTargetIDs)) { $query = \OC_DB::prepare('SELECT `fileid`, `path` FROM `*PREFIX*filecache` WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'); $result = $query->execute(); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR); } else { while ($row = $result->fetchRow()) { foreach ($fileTargets[$row['fileid']] as $uid => $shareData) { $sharedPath = $shareData['file_target']; $sharedPath .= substr($path, strlen($row['path']) - 5); $sharePaths[$uid] = $sharedPath; } } } } if ($includeOwner) { $sharePaths[$ownerUser] = $path; } else { unset($sharePaths[$ownerUser]); } return $sharePaths; } return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare); }
/** * inserts a new user or group into the mappings table * @param string $dn the record in question * @param string $ocName the name to use in ownCloud * @param bool $isUser is it a user or a group? * @return bool true on success, false otherwise * * inserts a new user or group into the mappings table */ private function mapComponent($dn, $ocName, $isUser = true) { $table = $this->getMapTable($isUser); $sqlAdjustment = ''; $dbType = \OCP\Config::getSystemValue('dbtype'); if ($dbType === 'mysql' || $dbType == 'oci') { $sqlAdjustment = 'FROM DUAL'; } $insert = \OCP\DB::prepare(' INSERT INTO `' . $table . '` (`ldap_dn`, `owncloud_name`, `directory_uuid`) SELECT ?,?,? ' . $sqlAdjustment . ' WHERE NOT EXISTS ( SELECT 1 FROM `' . $table . '` WHERE `ldap_dn` = ? OR `owncloud_name` = ?) '); //feed the DB $insRows = $insert->execute(array($dn, $ocName, $this->getUUID($dn, $isUser), $dn, $ocName)); if (\OCP\DB::isError($insRows)) { return false; } if ($insRows === 0) { return false; } if ($isUser) { //make sure that email address is retrieved prior to login, so user //will be notified when something is shared with him $this->userManager->get($ocName)->update(); } return true; }
public static function deleteUser($loginName) { $query = \OCP\DB::prepare('DELETE FROM *PREFIX*shibboleth_user WHERE login_name = ?'); $result = $query->execute(array($loginName)); if (\OCP\DB::isError($result)) { return false; } return true; }
/** * Find which users can access a shared item * @param string $path to the file * @param string $ownerUser owner of the file * @param boolean $includeOwner include owner to the list of users with access to the file * @param boolean $returnUserPaths Return an array with the user => path map * @return array * @note $path needs to be relative to user data dir, e.g. 'file.txt' * not '/admin/data/file.txt' */ public static function getUsersSharingFile($path, $ownerUser, $includeOwner = false, $returnUserPaths = false) { $shares = $sharePaths = $fileTargets = array(); $publicShare = false; $source = -1; $cache = false; $view = new \OC\Files\View('/' . $ownerUser . '/files'); if ($view->file_exists($path)) { $meta = $view->getFileInfo($path); $path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files')); } else { // if the file doesn't exists yet we start with the parent folder $meta = $view->getFileInfo(dirname($path)); } if ($meta !== false) { $source = $meta['fileid']; $cache = new \OC\Files\Cache\Cache($meta['storage']); } while ($source !== -1) { // Fetch all shares with another user $query = \OC_DB::prepare('SELECT `share_with`, `file_source`, `file_target` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_USER)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { while ($row = $result->fetchRow()) { $shares[] = $row['share_with']; if ($returnUserPaths) { $fileTargets[(int) $row['file_source']][$row['share_with']] = $row; } } } // We also need to take group shares into account $query = \OC_DB::prepare('SELECT `share_with`, `file_source`, `file_target` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_GROUP)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { while ($row = $result->fetchRow()) { $usersInGroup = \OC_Group::usersInGroup($row['share_with']); $shares = array_merge($shares, $usersInGroup); if ($returnUserPaths) { foreach ($usersInGroup as $user) { $fileTargets[(int) $row['file_source']][$user] = $row; } } } } //check for public link shares if (!$publicShare) { $query = \OC_DB::prepare('SELECT `share_with` FROM `*PREFIX*share` WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'); $result = $query->execute(array($source, self::SHARE_TYPE_LINK)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { if ($result->fetchRow()) { $publicShare = true; } } } // let's get the parent for the next round $meta = $cache->get((int) $source); if ($meta !== false) { $source = (int) $meta['parent']; } else { $source = -1; } } // Include owner in list of users, if requested if ($includeOwner) { $shares[] = $ownerUser; if ($returnUserPaths) { $sharePaths[$ownerUser] = $path; } } if ($returnUserPaths) { $fileTargetIDs = array_keys($fileTargets); $fileTargetIDs = array_unique($fileTargetIDs); if (!empty($fileTargetIDs)) { $query = \OC_DB::prepare('SELECT `fileid`, `path` FROM `*PREFIX*filecache` WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'); $result = $query->execute(); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } else { while ($row = $result->fetchRow()) { foreach ($fileTargets[$row['fileid']] as $uid => $shareData) { $sharedPath = $shareData['file_target']; $sharedPath .= substr($path, strlen($row['path']) - 5); $sharePaths[$uid] = $sharedPath; } } } } return $sharePaths; } return array("users" => array_unique($shares), "public" => $publicShare); }
private function prepareEvents() { $sql = "SELECT \n\t\t\t\t\tDATEDIFF(obj.startdate, obj.enddate) as diff, \n\t\t\t\t\tcal.displayname as calendar, \n\t\t\t\t\tobj.summary as title, \n\t\t\t\t\tcal.calendarcolor as color, \n\t\t\t\t\tIF(obj.repeating=0,obj.startdate,rep.startdate) as eventStart, \n\t\t\t\t\tIF(repeating=0,obj.enddate,rep.enddate) as eventEnd,\n\t\t\t\t\tobj.calendardata as data\n\t\t\t\tFROM \n\t\t\t\t\t`*PREFIX*clndr_objects` obj \n\t\t\t\t\t\tLEFT JOIN \n\t\t\t\t\t`*PREFIX*clndr_repeat` rep ON obj.id = rep.eventid\n\t\t\t\t\t\tJOIN\n\t\t\t\t\t`*PREFIX*clndr_calendars` cal on cal.id = obj.calendarid\n\t\t\t\tWHERE obj.objecttype = 'VEVENT' AND\n\t\t\t\t\tuserid = ? AND \n\t\t\t\t\t(\n\t\t\t\t\t\tDATE(obj.enddate) >= CURRENT_DATE\n\t\t\t\t\tOR \n\t\t\t\t\t\tDATE(rep.enddate) >= CURRENT_DATE\n\t\t\t\t\t)\n\t\t\t\tORDER BY\n\t\t\t\t\teventStart\n\t\t\t\tLIMIT " . $this->numEvents; $params = array($this->user); $query = \OCP\DB::prepare($sql); $result = $query->execute($params); if (\OCP\DB::isError($result)) { $this->errorMsg = "SQL Error"; \OCP\Util::writeLog('ocDashboard', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } while ($row = $result->fetchRow()) { // with timezone $row['start'] = strtotime($row['eventStart']) + $this->timezoneAdd * 60 * 60; $row['end'] = strtotime($row['eventEnd']) + $this->timezoneAdd * 60 * 60; //withour timezone $row['origStart'] = strtotime($row['eventStart']); $row['origEnd'] = strtotime($row['eventEnd']); $this->events[] = $row; } }
/** * Delete all entries we dealt with * * @param array $affectedUsers * @param int $maxTime */ public function deleteSentItems($affectedUsers, $maxTime) { $placeholders = implode(',', array_fill(0, sizeof($affectedUsers), '?')); $queryParams = $affectedUsers; array_unshift($queryParams, (int) $maxTime); $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*activity_mq` ' . ' WHERE `amq_timestamp` <= ? ' . ' AND `amq_affecteduser` IN (' . $placeholders . ')'); $result = $query->execute($queryParams); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('Activity', \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); } }
/** * deletes a given saved LDAP/AD server configuration. * @param string $prefix the configuration prefix of the config to delete * @return bool true on success, false otherwise */ public function deleteServerConfiguration($prefix) { if (!in_array($prefix, self::getServerConfigurationPrefixes())) { return false; } $saveOtherConfigurations = ''; if (empty($prefix)) { $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; } $query = \OCP\DB::prepare(' DELETE FROM `*PREFIX*appconfig` WHERE `configkey` LIKE ? ' . $saveOtherConfigurations . ' AND `appid` = \'user_ldap\' AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\') '); $delRows = $query->execute(array($prefix . '%')); if (\OCP\DB::isError($delRows)) { return false; } if ($delRows === 0) { return false; } return true; }
/** * @brief inserts a new user or group into the mappings table * @param $dn the record in question * @param $ocname the name to use in ownCloud * @param $isUser is it a user or a group? * @returns true on success, false otherwise * * inserts a new user or group into the mappings table */ private function mapComponent($dn, $ocname, $isUser = true) { $table = $this->getMapTable($isUser); $sqlAdjustment = ''; $dbtype = \OCP\Config::getSystemValue('dbtype'); if ($dbtype === 'mysql') { $sqlAdjustment = 'FROM DUAL'; } $insert = \OCP\DB::prepare(' INSERT INTO `' . $table . '` (`ldap_dn`, `owncloud_name`, `directory_uuid`) SELECT ?,?,? ' . $sqlAdjustment . ' WHERE NOT EXISTS ( SELECT 1 FROM `' . $table . '` WHERE `ldap_dn` = ? OR `owncloud_name` = ?) '); //feed the DB $insRows = $insert->execute(array($dn, $ocname, $this->getUUID($dn, $isUser), $dn, $ocname)); if (\OCP\DB::isError($insRows)) { return false; } if ($insRows === 0) { return false; } return true; }
/** * @param $id * @return mixed */ public function delete($id) { try { $query = 'SELECT COUNT(*) as `count` FROM `*PREFIX*contacts_cards` WHERE `id` = ? AND `addressbookid` = ?'; $stmt = \OCP\DB::prepare($query); $result = $stmt->execute(array($id, $this->id)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } if ((int) $result['count'] === 0) { \OCP\Util::writeLog('contacts', __METHOD__ . 'Contact with id ' . $id . 'doesn\'t belong to addressbook with id ' . $this->id, \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return false; } return VCard::delete($id); }
/** * Update the contact property index. * * If vcard is null the properties for that contact will be purged. * If it is a valid object the old properties will first be purged * and the current properties indexed. * * @param string $contactId * @param VCard|null $vCard */ public static function updateIndex($contactId, $vCard = null) { self::purgeIndexes(array($contactId)); if (is_null($vCard)) { return; } if (!isset(self::$updateindexstmt)) { self::$updateindexstmt = \OCP\DB::prepare('INSERT INTO `' . self::$indexTableName . '` ' . '(`userid`, `contactid`,`name`,`value`,`preferred`) VALUES(?,?,?,?,?)'); } foreach ($vCard->children as $property) { if (!in_array($property->name, self::$indexProperties)) { continue; } $preferred = 0; foreach ($property->parameters as $parameter) { if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') { $preferred = 1; break; } } try { $result = self::$updateindexstmt->execute(array(\OC::$server->getUserSession()->getUser()->getUId(), $contactId, $property->name, substr($property->getValue(), 0, 254), $preferred)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return false; } } }
/** * Truncate's the given mapping table * * @param string $mapping either 'user' or 'group' * @return bool true on success, false otherwise */ public static function clearMapping($mapping) { if ($mapping === 'user') { $table = '`*PREFIX*ldap_user_mapping`'; } else { if ($mapping === 'group') { $table = '`*PREFIX*ldap_group_mapping`'; } else { return false; } } $dbtype = \OCP\Config::getSystemValue('dbtype'); if (strpos($dbtype, 'sqlite') !== false || $dbtype === 'oci') { $query = \OCP\DB::prepare('DELETE FROM ' . $table); } else { $query = \OCP\DB::prepare('TRUNCATE ' . $table); } $res = $query->execute(); if (\OCP\DB::isError($res)) { return false; } return true; }
private function setHashAndStatus($data) { $hash = sha1(json_encode($data)); // hash exists in DB ? $sql = 'SELECT * FROM `*PREFIX*ocDashboard_usedHashs` WHERE usedHash = ? AND widget = ? AND user = ? LIMIT 1;'; $params = Array($hash,$this->id,$this->user); $query = \OCP\DB::prepare($sql); $result = $query->execute($params)->fetchRow(); //if (\OCP\DB::isError($result)) { // \OCP\Util::writeLog('ocDashboard',"Could not find hash in db.", \OCP\Util::WARN); // \OCP\Util::writeLog('ocDashboard', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); //} $all = $query->execute($params)->fetchAll(); //var_dump($all); $resultNum = count($all); // if not in DB, write to DB if( $resultNum == 0 ) { $sql2 = 'INSERT INTO `*PREFIX*ocDashboard_usedHashs` (usedHash,widget,user,timestamp) VALUES (?,?,?,?); '; $params = Array($hash,$this->id,$this->user,time()); $query2 = \OCP\DB::prepare($sql2); $result2 = $query2->execute($params); if (\OCP\DB::isError($result2)) { \OCP\Util::writeLog('ocDashboard',"Could not write hash to db.", \OCP\Util::WARN); \OCP\Util::writeLog('ocDashboard', \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } $this->status = 2; } else { $this->status = 0; } }
/** * Process the result and return the activities * * @param \OC_DB_StatementWrapper|int $result * @param \OCA\Activity\GroupHelper $groupHelper * @return array */ public function getActivitiesFromQueryResult($result, GroupHelper $groupHelper) { if (DB::isError($result)) { Util::writeLog('Activity', DB::getErrorMessage($result), Util::ERROR); } else { while ($row = $result->fetchRow()) { $groupHelper->addActivity($row); } } return $groupHelper->getActivities(); }
/** * @NoAdminRequired * @NoCSRFRequired * @PublicPage */ public function createAccount($token) { $email = $this->pendingreg->findEmailByToken($token); if (\OCP\DB::isError($email)) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('Invalid verification URL. No registration request with this verification URL is found.'), 'hint' => ''))), 'error'); } elseif ($email) { $username = $this->request->getParam('username'); $password = $this->request->getParam('password'); try { $user = $this->usermanager->createUser($username, $password); } catch (\Exception $e) { return new TemplateResponse('registration', 'form', array('email' => $email, 'entered_data' => array('username' => $username), 'errormsgs' => array($e->getMessage()), 'token' => $token), 'guest'); } if ($user === false) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('Unable to create user, there are problems with user backend.'), 'hint' => ''))), 'error'); } else { // Set user email try { $this->config->setUserValue($user->getUID(), 'settings', 'email', $email); } catch (\Exception $e) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('Unable to set user email: ' . $e->getMessage()), 'hint' => ''))), 'error'); } // Add user to group $registered_user_group = $this->config->getAppValue($this->appName, 'registered_user_group', 'none'); if ($registered_user_group !== 'none') { try { $group = $this->groupmanager->get($registered_user_group); $group->addUser($user); } catch (\Exception $e) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $e->message))), 'error'); } } // Delete pending reg request $res = $this->pendingreg->delete($email); if (\OCP\DB::isError($res)) { return new TemplateResponse('', 'error', array('errors' => array(array('error' => $this->l10n->t('Failed to delete pending registration request'), 'hint' => ''))), 'error'); } } return new TemplateResponse('registration', 'message', array('msg' => str_replace('{link}', $this->urlgenerator->getAbsoluteURL('/'), $this->l10n->t('Your account has been successfully created, you can <a href="{link}">log in now</a>.'))), 'guest'); } }
/** * @param string $pattern * @param string[] $searchProperties * @param $options * @return array|false */ public function search($pattern, $searchProperties, $options) { $propTable = '*PREFIX*conplus_cards_properties'; $contTable = '*PREFIX*conplus_cards'; $addrTable = '*PREFIX*conplus_addressbooks'; $results = array(); /** * This query will fetch all contacts which match the $searchProperties * It will look up the addressbookid of the contact and the user id of the owner of the contact app */ $query = <<<SQL \t\t\tSELECT \t\t\t\tDISTINCT \t\t\t\t`{$propTable}`.`contactid`, \t\t\t\t`{$contTable}`.`addressbookid`, \t\t\t\t`{$addrTable}`.`userid` \t\t\tFROM \t\t\t\t`{$propTable}` \t\t\tINNER JOIN \t\t\t\t`{$contTable}` \t\t\tON `{$contTable}`.`id` = `{$propTable}`.`contactid` \t\t\t\tINNER JOIN `{$addrTable}` \t\t\tON `{$addrTable}`.id = `{$contTable}`.addressbookid \t\t\tWHERE \t\t\t\t(`{$contTable}`.addressbookid = ?) AND \t\t\t\t( SQL; $params = array(); $params[] = $this->getKey(); foreach ($searchProperties as $property) { $params[] = $property; $params[] = '%' . $pattern . '%'; $query .= '(`name` = ? AND `value` ILIKE ?) OR '; } $query = substr($query, 0, strlen($query) - 4); $query .= ')'; $stmt = \OCP\DB::prepare($query); $result = $stmt->execute($params); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contactsplus', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } $j = []; while ($row = $result->fetchRow()) { $id = $row['contactid']; //$addressbookKey = $row['addressbookid']; $vcard = App::getContactVCard($id); $contact = VCard::structureContact($vcard); $j['data'] = $contact; $j['data']['id'] = $id; $j['data']['metadata'] = $row; $j['data']['photo'] = false; if (isset($vcard->BDAY)) { $j['data']['birthday'] = $vcard->BDAY; } if (isset($vcard->PHOTO) || isset($vcard->LOGO)) { $j['data']['photo'] = true; $url = \OC::$server->getURLGenerator()->linkToRoute('contactsplus.contacts.getContactPhoto', array('id' => $id)); $url = \OC::$server->getURLGenerator()->getAbsoluteURL($url); $j['data']['PHOTO'] = "uri:{$url}"; } $results[] = $this->convertToSearchResult($j); } return $results; }
private function createAddressBookURI($displayname, $userid = null) { $userid = $userid ? $userid : \OCP\User::getUser(); $name = str_replace(' ', '_', strtolower($displayname)); try { $stmt = \OCP\DB::prepare('SELECT `uri` FROM `' . $this->addressBooksTableName . '` WHERE `userid` = ? '); $result = $stmt->execute(array($userid)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return $name; } } catch (Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ' exception: ' . $e->getMessage(), \OCP\Util::ERROR); return $name; } $uris = array(); while ($row = $result->fetchRow()) { $uris[] = $row['uri']; } $newname = $name; $i = 1; while (in_array($newname, $uris)) { $newname = $name . $i; $i = $i + 1; } return $newname; }
/** * Create a unique URI based on the display name. * * @param string $displayName * @return string */ private function createAddressBookURI($displayName) { $name = str_replace(' ', '_', strtolower($displayName)); try { $stmt = $this->getPreparedQuery('addressbookuris'); $result = $stmt->execute(array($this->userid)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return $name; } } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ' exception: ' . $e->getMessage(), \OCP\Util::ERROR); return $name; } $uris = array(); while ($row = $result->fetchRow()) { $uris[] = $row['uri']; } $newname = $name; $i = 1; while (in_array($newname, $uris)) { $newname = $name . $i; $i = $i + 1; } return $newname; }
/** * @brief Move card(s) to an address book * @param integer $aid Address book id * @param $id Array or integer of cards to be moved. * @return boolean * */ public static function moveToAddressBook($aid, $id, $isAddressbook = false) { $addressbook = Addressbook::find($aid); if ($addressbook['userid'] != \OCP\User::getUser()) { $sharedAddressbook = \OCP\Share::getItemSharedWithBySource(App::SHAREADDRESSBOOK, App::SHAREADDRESSBOOKPREFIX . $aid); if (!$sharedAddressbook || !($sharedAddressbook['permissions'] & \OCP\PERMISSION_CREATE)) { throw new \Exception(App::$l10n->t('You don\'t have permissions to move contacts into this address book')); } } if (is_array($id)) { // NOTE: This block is currently not used and need rewrite if used! foreach ($id as $index => $cardId) { $card = self::find($cardId); if (!$card) { unset($id[$index]); } $oldAddressbook = Addressbook::find($card['addressbookid']); if ($oldAddressbook['userid'] != \OCP\User::getUser()) { $sharedContact = \OCP\Share::getItemSharedWithBySource(App::SHARECONTACT, App::SHARECONTACTPREFIX . $cardId, \OCP\Share::FORMAT_NONE, null, true); if (!$sharedContact || !($sharedContact['permissions'] & \OCP\PERMISSION_DELETE)) { unset($id[$index]); } } } $id_sql = join(',', array_fill(0, count($id), '?')); $prep = 'UPDATE `' . App::ContactsTable . '` SET `addressbookid` = ? WHERE `id` IN (' . $id_sql . ')'; try { $stmt = \OCP\DB::prepare($prep); //$aid = array($aid); $vals = array_merge((array) $aid, $id); $result = $stmt->execute($vals); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog(App::$appname, __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); throw new \Exception(App::$l10n->t('Database error during move.')); } } catch (\Exception $e) { \OCP\Util::writeLog(App::$appname, __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog(App::$appname, __METHOD__ . ', ids: ' . join(',', $vals), \OCP\Util::DEBUG); \OCP\Util::writeLog(App::$appname, __METHOD__ . ', SQL:' . $prep, \OCP\Util::DEBUG); throw new \Exception(App::$l10n->t('Database error during move.')); } } else { $stmt = null; if ($isAddressbook) { $stmt = \OCP\DB::prepare('UPDATE `' . App::ContactsTable . '` SET `addressbookid` = ? WHERE `addressbookid` = ?'); } else { $card = self::find($id); if (!$card) { throw new \Exception(App::$l10n->t('Error finding card to move.')); } $oldAddressbook = Addressbook::find($card['addressbookid']); if ($oldAddressbook['userid'] != \OCP\User::getUser()) { $sharedAddressbook = \OCP\Share::getItemSharedWithBySource(App::SHAREADDRESSBOOK, App::SHAREADDRESSBOOKPREFIX . $oldAddressbook['id']); if (!$sharedAddressbook || !($sharedAddressbook['permissions'] & \OCP\PERMISSION_DELETE)) { throw new \Exception(App::$l10n->t('You don\'t have permissions to move contacts from this address book')); } } Addressbook::touch($oldAddressbook['id']); $stmt = \OCP\DB::prepare('UPDATE `' . App::ContactsTable . '` SET `addressbookid` = ? WHERE `id` = ?'); } try { $result = $stmt->execute(array($aid, $id)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog(App::$appname, __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); throw new \Exception(App::$l10n->t('Database error during move.')); } } catch (\Exception $e) { \OCP\Util::writeLog(App::$appname, __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::DEBUG); \OCP\Util::writeLog(App::$appname, __METHOD__ . ' id: ' . $id, \OCP\Util::DEBUG); throw new \Exception(App::$l10n->t('Database error during move.')); } } //\OC_Hook::emit('\OCA\Contacts\VCard', 'post_moveToAddressbook', array('aid' => $aid, 'id' => $id)); Addressbook::touch($aid); return true; }
foreach ($files as $file) { $filesById[$file['fileid']] = $file; } try { $conn = \OC_DB::getConnection(); $chunks = array_chunk(array_keys($filesById), 900, false); foreach ($chunks as $chunk) { $result = $conn->executeQuery('SELECT `category`, `categoryid`, `objid` ' . 'FROM `' . '*PREFIX*vcategory_to_object' . '` r, `' . '*PREFIX*vcategory' . '` ' . 'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)', array($_SESSION['user_id'], 'files', $chunk), array(null, null, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY)); while ($row = $result->fetch()) { $objId = (int) $row['objid']; if (!isset($entries[$objId])) { $entry = $entries[$objId] = array(); } $entry = $entries[$objId][] = $row['category']; } if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('filefilter', __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } } catch (\Exception $e) { \OCP\Util::writeLog('filefilter', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return false; } //将tags赋值给files数组 if (isset($entries)) { foreach ($entries as $fileId => $fileTags) { $filesById[$fileId]['tags'] = $fileTags; } } //将最后值变为filelist
/** * get some information from a given share * @param int $shareID * @return array with: item_source, share_type, share_with, item_type, permissions */ private static function getShareFromId($shareID) { $sql = 'SELECT `file_source`, `item_source`, `share_type`, `share_with`, `item_type`, `permissions`, `stime` FROM `*PREFIX*share` WHERE `id` = ?'; $args = array($shareID); $query = \OCP\DB::prepare($sql); $result = $query->execute($args); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_sharing', \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return null; } if ($share = $result->fetchRow()) { return $share; } return null; }
public static function scan($id, $path, $storage) { $fileStatus = \OCA\Files_Antivirus\Scanner::scanFile($storage, $path); $result = $fileStatus->getNumericStatus(); //TODO: Fix undefined $user here switch ($result) { case \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED: \OCP\Util::writeLog('files_antivirus', 'File "' . $path . '" with id "' . $id . '": is not checked', \OCP\Util::ERROR); break; case \OCA\Files_Antivirus\Status::SCANRESULT_INFECTED: $infected_action = \OCP\Config::getAppValue('files_antivirus', 'infected_action', 'only_log'); if ($infected_action == 'delete') { \OCP\Util::writeLog('files_antivirus', 'File "' . $path . '" with id "' . $id . '": is infected, file deleted', \OCP\Util::ERROR); $storage->unlink($path); } else { \OCP\Util::writeLog('files_antivirus', 'File "' . $path . '" with id "' . $id . '": is infected', \OCP\Util::ERROR); } break; case \OCA\Files_Antivirus\Status::SCANRESULT_CLEAN: try { $stmt = \OCP\DB::prepare('DELETE FROM `*PREFIX*files_antivirus` WHERE `fileid` = ?'); $result = $stmt->execute(array($id)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return; } $stmt = \OCP\DB::prepare('INSERT INTO `*PREFIX*files_antivirus` (`fileid`, `check_time`) VALUES (?, ?)'); $result = $stmt->execute(array($id, time())); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return; } } catch (\Exception $e) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); } break; } }
public function parseResponse($rawResponse, $result = null) { $matches = array(); if (is_null($result)) { // Daemon or socket mode // Load rules $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*files_antivirus_status` WHERE `status_type`=? and `status`=?'); try { $infectedResult = $query->execute(array(self::STATUS_TYPE_MATCH, self::SCANRESULT_INFECTED)); if (\OCP\DB::isError($infectedResult)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($infectedResult), \OCP\Util::ERROR); return; } $infectedRules = $infectedResult->fetchAll(); $uncheckedResult = $query->execute(array(self::STATUS_TYPE_MATCH, self::SCANRESULT_UNCHECKED)); if (\OCP\DB::isError($uncheckedResult)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($uncheckedResult), \OCP\Util::ERROR); return; } $uncheckedRules = $uncheckedResult->fetchAll(); $cleanResult = $query->execute(array(self::STATUS_TYPE_MATCH, self::SCANRESULT_CLEAN)); if (\OCP\DB::isError($cleanResult)) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($cleanResult), \OCP\Util::ERROR); return; } $cleanRules = $cleanResult->fetchAll(); } catch (\Exception $e) { \OCP\Util::writeLog('files_antivirus', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return; } $infectedRules = $infectedRules ? $infectedRules : array(); $uncheckedRules = $uncheckedRules ? $uncheckedRules : array(); $cleanRules = $cleanRules ? $cleanRules : array(); $isMatched = false; // order: clean, infected, try to guess error $allRules = array_merge($cleanRules, $infectedRules, $uncheckedRules); foreach ($allRules as $rule) { if (preg_match($rule['match'], $rawResponse, $matches)) { $isMatched = true; $this->numericStatus = $rule['status']; if ($rule['status'] == self::SCANRESULT_CLEAN) { $this->details = ''; } else { $this->details = isset($matches[1]) ? $matches[1] : 'unknown'; } break; } } if (!$isMatched) { $this->numericStatus = self::SCANRESULT_UNCHECKED; $this->details = 'No matching rules. Please check antivirus rules.'; } } else { // Executable mode $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*files_antivirus_status` WHERE `status_type`=? and `result`=?'); $queryResult = $query->execute(array(self::STATUS_TYPE_CODE, $result)); $scanStatus = $queryResult->fetchRow(); if (is_array($scanStatus) && count($scanStatus)) { $this->numericStatus = $scanStatus['status']; } switch ($this->numericStatus) { case self::SCANRESULT_INFECTED: $report = array(); $rawResponse = explode("\n", $rawResponse); foreach ($rawResponse as $line) { if (preg_match('/.*: (.*) FOUND\\s*$/', $line, $matches)) { $report[] = $matches[1]; } } $this->details = implode(', ', $report); break; case self::SCANRESULT_UNCHECKED: $this->details = isset($scanStatus['description']) ? $scanStatus['description'] : 'No matching rule for exit code ' . $this->numericStatus . '. Please check antivirus rules configuration.'; } } //Log switch ($this->numericStatus) { case self::SCANRESULT_CLEAN: \OCP\Util::writeLog('files_antivirus', 'Result CLEAN!', \OCP\Util::DEBUG); break; case self::SCANRESULT_INFECTED: \OCP\Util::writeLog('files_antivirus', 'Virus(es) found: ' . $this->details, \OCP\Util::WARN); break; default: \OCP\Util::writeLog('files_antivirus', 'File could not be scanned. Details: ' . $this->details, \OCP\Util::WARN); } }
/** * Delete tags from the database. * * @param string[]|integer[] $names An array of tags (names or IDs) to delete * @return bool Returns false on error */ public function delete($names) { if (!is_array($names)) { $names = array($names); } $names = array_map('trim', $names); array_filter($names); \OCP\Util::writeLog('core', __METHOD__ . ', before: ' . print_r($this->tags, true), \OCP\Util::DEBUG); foreach ($names as $name) { $id = null; if (is_numeric($name)) { $key = $this->getTagById($name); } else { $key = $this->getTagByName($name); } if ($key !== false) { $tag = $this->tags[$key]; $id = $tag->getId(); unset($this->tags[$key]); $this->mapper->delete($tag); } else { \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name . ': not found.', \OCP\Util::ERROR); } if (!is_null($id) && $id !== false) { try { $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` ' . 'WHERE `categoryid` = ?'; $stmt = \OCP\DB::prepare($sql); $result = $stmt->execute(array($id)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('core', __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog('core', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); return false; } } } return true; }
/** * get owner of the shared files. * @param int $id ID of a share * @return string owner */ public function getOwnerFromSharedFile($id) { $query = \OCP\DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1); $result = $query->execute(array($id)); $source = null; if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('Encryption library', \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); } else { $source = $result->fetchRow(); } $fileOwner = false; if ($source && isset($source['parent'])) { $parent = $source['parent']; while (isset($parent)) { $query = \OCP\DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1); $result = $query->execute(array($parent)); $item = null; if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('Encryption library', \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); } else { $item = $result->fetchRow(); } if ($item && isset($item['parent'])) { $parent = $item['parent']; } else { $fileOwner = $item['uid_owner']; break; } } } else { $fileOwner = $source['uid_owner']; } return $fileOwner; }
/** * Add an album to the database * * @param string $name * @param integer $artist * @return integer the album_id of the added artist */ public function addAlbum($name, $artist) { $name = trim($name); if ($name == '') { return 0; } //check if the album is already in the database $albumId = self::getAlbumId($name, $artist); if ($albumId != 0) { return $albumId; } else { $stmt = \OCP\DB::prepare('INSERT INTO `*PREFIX*media_albums` (`album_name` ,`album_artist`) VALUES (?, ?)'); if (!\OCP\DB::isError($stmt)) { $result = $stmt->execute(array($name, $artist)); if (\OCP\DB::isError($result)) { \OC_Log::write('OC_MEDIA_COLLECTION', 'could not add album: ' . \OC_DB::getErrorMessage($result), \OC_Log::ERROR); } } else { \OC_Log::write('OC_MEDIA_COLLECTION', 'could not add album: ' . \OC_DB::getErrorMessage($stmt), \OC_Log::ERROR); } return $this->getAlbumId($name, $artist); } }