Example #1
0
 function import()
 {
     switch ($this->appinfo->version) {
         default:
             // All versions of the app have had the same db structure, so all can use the same import function
             $query = $this->content->prepare('SELECT * FROM contacts_addressbooks WHERE userid = ?');
             $results = $query->execute(array($this->olduid));
             $idmap = array();
             $app = new \OCA\Contacts\App($this->uid);
             while ($row = $results->fetchRow()) {
                 // Import each addressbook
                 $addressbookquery = \OCP\DB::prepare('INSERT INTO `*PREFIX*contacts_addressbooks` ' . '(`userid`, `displayname`, `uri`, `description`, `ctag`) VALUES (?, ?, ?, ?, ?)');
                 $addressbookquery->execute(array($this->uid, $row['displayname'], $row['uri'], $row['description'], $row['ctag']));
                 // Map the id
                 $idmap[$row['id']] = \OCP\DB::insertid('*PREFIX*contacts_addressbooks');
                 // Make the addressbook active
                 $addressbook = $app->getAddressBook('local', $idmap[$row['id']]);
                 $addressbook->setActive(true);
             }
             // Now tags
             foreach ($idmap as $oldid => $newid) {
                 $query = $this->content->prepare('SELECT * FROM contacts_cards WHERE addressbookid = ?');
                 $results = $query->execute(array($oldid));
                 while ($row = $results->fetchRow()) {
                     // Import the contacts
                     $contactquery = \OCP\DB::prepare('INSERT INTO `*PREFIX*contacts_cards` ' . '(`addressbookid`, `fullname`, `carddata`, `uri`, `lastmodified`) VALUES (?, ?, ?, ?, ?)');
                     $contactquery->execute(array($newid, $row['fullname'], $row['carddata'], $row['uri'], $row['lastmodified']));
                 }
             }
             // All done!
             break;
     }
     return true;
 }
Example #2
0
    public static function add($esId, $userId)
    {
        $query = \OCP\DB::prepare('
			INSERT INTO `*PREFIX*documents_invite` (`es_id`, `uid`, `status`, `sent_on`)
			VALUES (?, ?, ?, ?)
			');
        $query->execute(array($esId, $userId, self::STATUS_SENT, time()));
        return \OCP\DB::insertid(`*PREFIX*documents_invite`);
    }
Example #3
0
 /**
  * @brief Get index of collection, if collection doesn't exist it will be created
  *
  * @param string $collectionName
  */
 public static function collectionNameToIndex($userId, $collectionName)
 {
     $query = \OCP\DB::prepare('SELECT id FROM *PREFIX*mozilla_sync_collections WHERE userid=? AND name=?');
     $result = $query->execute(array($userId, $collectionName));
     $row = $result->fetchRow();
     if ($row) {
         return $row['id'];
     }
     //
     // No collection found
     //
     $query = \OCP\DB::prepare('INSERT INTO *PREFIX*mozilla_sync_collections (userid, name) VALUES (?,?)');
     $result = $query->execute(array($userId, $collectionName));
     if ($result == false) {
         return false;
     }
     return \OCP\DB::insertid('*PREFIX*mozilla_sync_collections');
 }
Example #4
0
    /**
     * @brief Get index of collection, if collection doesn't exist it will be
     * created.
     *
     * @param string $syncId The Sync user that the collection is belonging to.
     * @param string $collectionName The name of the collection.
     */
    public static function collectionNameToIndex($syncId, $collectionName)
    {
        $query = \OCP\DB::prepare('SELECT `id` FROM
			`*PREFIX*mozilla_sync_collections` WHERE `userid` = ? AND
			`name` = ?');
        $result = $query->execute(array($syncId, $collectionName));
        // Collection found, return its ID
        $row = $result->fetchRow();
        if ($row) {
            return $row['id'];
        }
        // No collection found, create new collection
        $query = \OCP\DB::prepare('INSERT INTO
			`*PREFIX*mozilla_sync_collections` (`userid`, `name`) VALUES
			(?, ?)');
        $result = $query->execute(array($syncId, $collectionName));
        // Creation of collection failed
        if ($result === false) {
            Utils::writeLogDbError("DB: Could not create collection " . $collectionName . ".", $query);
            return false;
        }
        return \OCP\DB::insertid('*PREFIX*mozilla_sync_collections');
    }
Example #5
0
 /**
  * Used to get the id of the just inserted element
  * @param string $tableName the name of the table where we inserted the item
  * @return int the id of the inserted element
  */
 public function getInsertId($tableName)
 {
     return \OCP\DB::insertid($tableName);
 }
Example #6
0
 /**
  * @brief Creates a new calendar from the data sabredav provides
  * @param string $principaluri
  * @param string $uri
  * @param string $name
  * @param string $components
  * @param string $timezone
  * @param integer $order
  * @param string $color format: '#RRGGBB(AA)'
  * @return insertid
  */
 public static function addCalendarFromDAVData($principaluri, $uri, $name, $components, $timezone, $order, $color, $transparent)
 {
     $userid = self::extractUserID($principaluri);
     $all = self::allCalendars($userid);
     $uris = array();
     foreach ($all as $i) {
         $uris[] = $i['uri'];
     }
     $lastmodified = time();
     $uri = self::createURI($name, $uris);
     $stmt = \OCP\DB::prepare('INSERT INTO `' . App::CldCalendarTable . '` (`userid`,`displayname`,`uri`,`ctag`,`calendarorder`,`calendarcolor`,`timezone`,`components`,`transparent`) VALUES(?,?,?,?,?,?,?,?,?)');
     $result = $stmt->execute(array($userid, $name, $uri, 1, $order, $color, $timezone, $components, $transparent));
     $insertid = \OCP\DB::insertid(App::CldCalendarTable);
     \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'addCalendar', $insertid);
     return $insertid;
 }
Example #7
0
 /**
  * @brief Creates a new address book from the data sabredav provides
  * @param string $principaluri
  * @param string $uri
  * @param string $name
  * @param string $description
  * @return insertid or false
  */
 public static function addFromDAVData($principaluri, $uri, $name, $description)
 {
     $uid = self::extractUserID($principaluri);
     try {
         $stmt = \OCP\DB::prepare('INSERT INTO `*PREFIX*contacts_addressbooks` ' . '(`userid`,`displayname`,`uri`,`description`,`ctag`) VALUES(?,?,?,?,?)');
         $result = $stmt->execute(array($uid, $name, $uri, $description, 1));
         if (\OC_DB::isError($result)) {
             \OC_Log::write('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
             return false;
         }
     } catch (Exception $e) {
         \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
         \OCP\Util::writeLog('contacts', __METHOD__ . ', uid: ' . $uid, \OCP\Util::DEBUG);
         \OCP\Util::writeLog('contacts', __METHOD__ . ', uri: ' . $uri, \OCP\Util::DEBUG);
         return false;
     }
     return \OCP\DB::insertid('*PREFIX*contacts_addressbooks');
 }
Example #8
0
 /**
  * Create a new tag with the provided parameters - Return the tag ID
  * @param string $tagLang
  * @param string $tagDescr
  * @param integer $parentID Id of tag's parent
  * @param string $owner id of the owner; if NULL the actual username will be set
  * @param string $permission unix-style of the read/write permission of the tag
  * @return integer Newly inserted index, FALSE if parameters not valid
  */
 public function newTag($tagLang, $tagDescr, $parentID, $owner = NULL, $permission = 'rw----')
 {
     // Check if provided parameters are correct
     if (strlen(trim($tagLang)) !== 2 || trim($tagDescr) === '' || !is_int($parentID) || $parentID < -1) {
         return FALSE;
     }
     // Check if tag already exists
     if (count($this->searchTag($tagLang, $tagDescr)) != 0) {
         return FALSE;
     }
     // If owner is not set, assign the actual username
     if ($owner === NULL) {
         $owner = \OCP\User::getUser();
     }
     // Proceed with creation
     $result = array();
     // Insert master record
     $sql = "INSERT INTO `*PREFIX*oclife_tags` (`parent`, `owner`, `permission`) VALUES (?,?,?)";
     $args = array($parentID, $owner, $permission);
     $query = \OCP\DB::prepare($sql);
     $resRsrc = $query->execute($args);
     // Get inserted index
     $newIndex = \OCP\DB::insertid();
     // Insert human readable
     $args = array($newIndex, strtolower($tagLang), trim($tagDescr));
     $sql = "INSERT INTO `*PREFIX*oclife_humanReadable` (`tagid`, `lang`, `descr`) VALUES (?,?,?)";
     $query = \OCP\DB::prepare($sql);
     $resRsrc = $query->execute($args);
     return $newIndex;
 }
Example #9
0
    /**
     * @brief Store the folder and all its feeds into the database
     * @param folder the folder to be saved
     * @returns The id of the folder in the database table.
     */
    public function save(Folder $folder)
    {
        $query = \OCP\DB::prepare('
			INSERT INTO ' . self::tableName . '(name, parent_id, user_id, opened)
			VALUES (?, ?, ?, ?)
			');
        $name = $folder->getName();
        if (empty($name)) {
            $l = \OC_L10N::get('news');
            $name = $l->t('no name');
        }
        $parentid = $folder->getParentId();
        $params = array($name, $parentid, $this->userid, $folder->getOpened());
        $query->execute($params);
        $folderid = \OCP\DB::insertid(self::tableName);
        $folder->setId($folderid);
        return $folderid;
    }
Example #10
0
 /**
  * Creates a new contact
  *
  * In the Database and Shared backends contact be either a Contact object or a string
  * with carddata to be able to play seamlessly with the CardDAV backend.
  * If this method is called by the CardDAV backend, the carddata is already validated.
  * NOTE: It's assumed that this method is called either from the CardDAV backend, the
  * import script, or from the ownCloud web UI in which case either the uri parameter is
  * set, or the contact has a UID. If neither is set, it will fail.
  *
  * @param string $addressbookid
  * @param VCard|string $contact
  * @param array $options - Optional (backend specific options)
  * @return string|bool The identifier for the new contact or false on error.
  */
 public function createContact($addressbookid, $contact, array $options = array())
 {
     $qname = 'createcontact';
     $uri = isset($options['uri']) ? $options['uri'] : null;
     if (!$contact instanceof VCard) {
         try {
             $contact = Reader::read($contact);
         } catch (\Exception $e) {
             \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
             return false;
         }
     }
     try {
         $contact->validate(VCard::REPAIR | VCard::UPGRADE);
     } catch (\Exception $e) {
         OCP\Util::writeLog('contacts', __METHOD__ . ' ' . 'Error validating vcard: ' . $e->getMessage(), \OCP\Util::ERROR);
         return false;
     }
     $uri = is_null($uri) ? $contact->UID . '.vcf' : $uri;
     $now = new \DateTime();
     $contact->REV = $now->format(\DateTime::W3C);
     $appinfo = \OCP\App::getAppInfo('contacts');
     $appversion = \OCP\App::getAppVersion('contacts');
     $prodid = '-//ownCloud//NONSGML ' . $appinfo['name'] . ' ' . $appversion . '//EN';
     $contact->PRODID = $prodid;
     $data = $contact->serialize();
     if (!isset(self::$preparedQueries[$qname])) {
         self::$preparedQueries[$qname] = \OCP\DB::prepare('INSERT INTO `' . $this->cardsTableName . '` (`addressbookid`,`fullname`,`carddata`,`uri`,`lastmodified`) VALUES(?,?,?,?,?)');
     }
     try {
         $result = self::$preparedQueries[$qname]->execute(array($addressbookid, (string) $contact->FN, $contact->serialize(), $uri, time()));
         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;
     }
     $newid = \OCP\DB::insertid($this->cardsTableName);
     $this->touchAddressBook($addressbookid);
     \OCP\Util::emitHook('OCA\\Contacts', 'post_createContact', array('id' => $newid, 'parent' => $addressbookid, 'contact' => $contact));
     return (string) $newid;
 }
Example #11
0
 /**
  * Add an song to the database
  *
  * @param string $name
  * @param string $path
  * @param int $artist
  * @param int $album
  * @param int $length
  * @param int $track
  * @param int $size
  * @return int the song_id of the added artist
  */
 public function addSong($name, $path, $artist, $album, $length, $track, $size)
 {
     $name = trim($name);
     $path = trim($path);
     if ($name == '' or $path == '') {
         return 0;
     }
     //check if the song is already in the database
     $songId = $this->getSongId($name, $artist, $album);
     if ($songId != 0) {
         $songInfo = $this->getSong($songId);
         $this->moveSong($songInfo['song_path'], $path);
         return $songId;
     }
     if ($this->getSongCountByPath($path) !== 0) {
         $this->deleteSongByPath($path);
     }
     $query = \OCP\DB::prepare("INSERT INTO  `*PREFIX*media_songs` (`song_name` ,`song_artist` ,`song_album` ,`song_path` ,`song_user`,`song_length`,`song_track`,`song_size`,`song_playcount`,`song_lastplayed`)\n\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0)");
     $query->execute(array($name, $artist, $album, $path, $this->uid, $length, $track, $size));
     \OCP\DB::insertid(' * PREFIX * media_songs_song');
     return $this->getSongId($name, $artist, $album);
 }
Example #12
0
        } else {
            $field = 'match';
        }
        $data = array();
        $data[] = $statusType;
        $data[] = isset($_POST['match']) ? $_POST['match'] : '';
        $data[] = isset($_POST['description']) ? $_POST['description'] : '';
        $data[] = isset($_POST['status']) ? intval($_POST['status']) : 0;
        if ($ruleId) {
            $data[] = $ruleId;
            $query = \OCP\DB::prepare('UPDATE `*PREFIX*files_antivirus_status` SET `status_type`=(?),' . ' `' . $field . '`=(?), `description`=(?), `status`=(?) WHERE `id`=?');
        } else {
            $query = \OCP\DB::prepare('INSERT INTO `*PREFIX*files_antivirus_status` (`status_type`,' . ' `' . $field . '`, `description`, `status`) VALUES (?, ?, ?, ?)');
        }
        $query->execute($data);
        $result = array();
        if (!$ruleId) {
            $result['id'] = \OCP\DB::insertid('`*PREFIX*files_antivirus_status`');
        }
        \OCP\JSON::success($result);
        break;
    case 'delete':
        $ruleId = isset($_POST['id']) ? intval($_POST['id']) : 0;
        $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*files_antivirus_status` WHERE `id`=?');
        $query->execute(array($ruleId));
        \OCP\JSON::success();
        break;
    default:
        break;
}
exit;
Example #13
0
 public function createNote($FOLDER, $in_name, $in_group)
 {
     $name = str_replace("\\", "-", str_replace("/", "-", $in_name));
     $group = str_replace("\\", "-", str_replace("/", "-", $in_group));
     $now = new DateTime();
     $mtime = $now->getTimestamp();
     $uid = \OCP\User::getUser();
     $fileindb = false;
     $filedeldb = false;
     $ret = -1;
     $query = \OCP\DB::prepare("SELECT id, name, grouping, mtime, deleted FROM *PREFIX*ownnote WHERE uid=? and name=? and grouping=?");
     $results = $query->execute(array($uid, $name, $group))->fetchAll();
     foreach ($results as $result) {
         if ($result['deleted'] == 0) {
             $fileindb = true;
             $ret = $result['id'];
         } else {
             $filedeldb = true;
         }
     }
     if ($filedeldb) {
         $query = \OCP\DB::prepare("DELETE FROM *PREFIX*ownnote WHERE uid=? and name=? and grouping=?");
         $results = $query->execute(array($uid, $name, $group));
     }
     if (!$fileindb) {
         if ($FOLDER != '') {
             $tmpfile = $FOLDER . "/" . $name . ".htm";
             if ($group != '') {
                 $tmpfile = $FOLDER . "/[" . $group . "] " . $name . ".htm";
             }
             if (!\OC\Files\Filesystem::file_exists($tmpfile)) {
                 \OC\Files\Filesystem::touch($tmpfile);
             }
             if ($info = \OC\Files\Filesystem::getFileInfo($tmpfile)) {
                 $mtime = $info['mtime'];
             }
         }
         $query = \OCP\DB::prepare("INSERT INTO *PREFIX*ownnote (uid, name, grouping, mtime, note, shared) VALUES (?,?,?,?,?,?)");
         $query->execute(array($uid, $name, $group, $mtime, '', ''));
         $ret = \OCP\DB::insertid('*PREFIX*ownnote');
     }
     return $ret;
 }
Example #14
0
 /**
  * Add a new tag.
  *
  * @param string $name A string with a name of the tag
  * @return false|string the id of the added tag or false on error.
  */
 public function add($name)
 {
     $name = trim($name);
     if ($name === '') {
         \OCP\Util::writeLog('core', __METHOD__ . ', Cannot add an empty tag', \OCP\Util::DEBUG);
         return false;
     }
     if ($this->hasTag($name)) {
         \OCP\Util::writeLog('core', __METHOD__ . ', name: ' . $name . ' exists already', \OCP\Util::DEBUG);
         return false;
     }
     try {
         $result = \OCP\DB::insertIfNotExist(self::TAG_TABLE, array('uid' => $this->user, 'type' => $this->type, 'category' => $name));
         if (\OCP\DB::isError($result)) {
             \OCP\Util::writeLog('core', __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
             return false;
         } elseif ((int) $result === 0) {
             \OCP\Util::writeLog('core', __METHOD__ . ', Tag already exists: ' . $name, \OCP\Util::DEBUG);
             return false;
         }
     } catch (\Exception $e) {
         \OCP\Util::writeLog('core', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
         return false;
     }
     $id = \OCP\DB::insertid(self::TAG_TABLE);
     \OCP\Util::writeLog('core', __METHOD__ . ', id: ' . $id, \OCP\Util::DEBUG);
     $this->tags[$id] = $name;
     return $id;
 }
Example #15
0
 /**
  * @brief Adds an object with the data provided by sabredav
  * @param integer $id Calendar id
  * @param string $uri   the uri the card will have
  * @param string $data  object
  * @return insertid
  */
 public static function addFromDAVData($id, $uri, $data)
 {
     $calendar = Calendar::find($id);
     if ($calendar['userid'] != \OCP\User::getUser()) {
         $sharedCalendar = \OCP\Share::getItemSharedWithBySource(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $id);
         if (!$sharedCalendar || !($sharedCalendar['permissions'] & \OCP\PERMISSION_CREATE)) {
             throw new \Sabre\DAV\Exception\Forbidden(App::$l10n->t('You do not have the permissions to add events to this calendar.'));
         }
     }
     $object = VObject::parse($data);
     list($type, $startdate, $enddate, $summary, $repeating, $uid, $isAlarm, $relatedTo) = self::extractData($object);
     $stmt = \OCP\DB::prepare('INSERT INTO `' . App::CldObjectTable . '` (`calendarid`,`objecttype`,`startdate`,`enddate`,`repeating`,`summary`,`calendardata`,`uri`,`lastmodified`,`isalarm`,`eventuid`,`relatedto`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)');
     $stmt->execute(array($id, $type, $startdate, $enddate, $repeating, $summary, $data, $uri, time(), $isAlarm, $uid, $relatedTo));
     $object_id = \OCP\DB::insertid(App::CldObjectTable);
     Calendar::touchCalendar($id);
     $app = new Application();
     $c = $app->getContainer();
     $repeatController = $c->query('RepeatController');
     $repeatController->generateEventCache($object_id);
     //\OCP\Util::emitHook('\OCA\CalendarPlus', 'addEvent', $object_id);
     $linkTypeApp = App::$appname;
     if ($type == 'VTODO') {
         $linkTypeApp = 'tasksplus';
     }
     $link = \OC::$server->getURLGenerator()->linkToRoute($linkTypeApp . '.page.index') . '#' . urlencode($object_id);
     $params = array('mode' => 'created', 'link' => $link, 'trans_type' => App::$l10n->t($type), 'summary' => $summary, 'cal_user' => $calendar['userid'], 'cal_displayname' => $calendar['displayname']);
     ActivityData::logEventActivity($params, true);
     return $object_id;
 }
Example #16
0
    public function save(Feed $feed, $folderid)
    {
        $title = $feed->getTitle();
        $url = $feed->getUrl();
        $url_hash = md5($url);
        if (empty($title)) {
            $l = \OC_L10N::get('news');
            $title = $l->t('no title');
        }
        $favicon = $feed->getFavicon();
        //FIXME: Detect when feed contains already a database id
        $feedid = $this->findIdFromUrl($url);
        if ($feedid === null) {
            $query = \OCP\DB::prepare("\n\t\t\t\tINSERT INTO " . self::tableName . "(url, url_hash, title, favicon_link, folder_id, user_id, added, lastmodified)\n\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP())\n\t\t\t\t");
            $params = array($url, $url_hash, $title, $favicon, $folderid, $this->userid);
            $query->execute($params);
            $feedid = \OCP\DB::insertid(self::tableName);
        } else {
            //update the db. it needs to be done, since it might be the first save after a full fetch
            $stmt = \OCP\DB::prepare('
					UPDATE ' . self::tableName . ' SET favicon_link = ? , lastmodified = UNIX_TIMESTAMP() , folder_id = ?
					WHERE id = ?
					');
            $params = array($favicon, $folderid, $feedid);
            $stmt->execute($params);
        }
        $feed->setId($feedid);
        $itemMapper = new ItemMapper();
        $items = $feed->getItems();
        if ($items !== null) {
            foreach ($items as $item) {
                $itemMapper->save($item, $feedid);
            }
        }
        return $feedid;
    }
Example #17
0
 /**
  * Creates a new contact
  *
  * In the Database and Shared backends contact be either a Contact object or a string
  * with carddata to be able to play seamlessly with the CardDAV backend.
  * If this method is called by the CardDAV backend, the carddata is already validated.
  * NOTE: It's assumed that this method is called either from the CardDAV backend, the
  * import script, or from the ownCloud web UI in which case either the uri parameter is
  * set, or the contact has a UID. If neither is set, it will fail.
  *
  * @param string $addressBookId
  * @param VCard|string $contact
  * @param array $options - Optional (backend specific options)
  * @return string|bool The identifier for the new contact or false on error.
  */
 public function createContact($addressBookId, $contact, array $options = array())
 {
     //\OCP\Util::writeLog('contacts', __METHOD__.' addressBookId: ' . $addressBookId, \OCP\Util::DEBUG);
     $uri = isset($options['uri']) ? $options['uri'] : null;
     if (!$contact instanceof VCard) {
         try {
             $contact = Reader::read($contact);
         } catch (\Exception $e) {
             \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
             return false;
         }
     }
     try {
         $contact->validate(VCard::REPAIR | VCard::UPGRADE);
     } catch (\Exception $e) {
         \OCP\Util::writeLog('contacts', __METHOD__ . ' ' . 'Error validating vcard: ' . $e->getMessage(), \OCP\Util::ERROR);
         return false;
     }
     $uri = is_null($uri) ? $this->uniqueURI($addressBookId, $contact->UID . '.vcf') : $uri;
     $now = new \DateTime();
     $contact->REV = $now->format(\DateTime::W3C);
     $appinfo = \OCP\App::getAppInfo('contacts');
     $appversion = \OCP\App::getAppVersion('contacts');
     $prodid = '-//ownCloud//NONSGML ' . $appinfo['name'] . ' ' . $appversion . '//EN';
     $contact->PRODID = $prodid;
     try {
         $result = $this->getPreparedQuery('createcontact')->execute(array($addressBookId, (string) $contact->FN, $contact->serialize(), $uri, time()));
         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;
     }
     $newid = \OCP\DB::insertid($this->cardsTableName);
     $this->setModifiedAddressBook($addressBookId);
     \OCP\Util::emitHook('OCA\\Contacts', 'post_createContact', array('id' => $newid, 'parent' => $addressBookId, 'backend' => $this->name, 'contact' => $contact));
     return (string) $newid;
 }
Example #18
0
    /**
     * @brief Save the feed and all its items into the database
     * @returns The id of the feed in the database table.
     */
    public function save(Item $item, $feedid)
    {
        $guid = $item->getGuid();
        $guid_hash = md5($guid);
        $status = $item->getStatus();
        $itemid = $this->findIdFromGuid($guid_hash, $guid, $feedid);
        if ($itemid == null) {
            $title = $item->getTitle();
            $body = $item->getBody();
            $author = $item->getAuthor();
            $stmt = \OCP\DB::prepare('
				INSERT INTO ' . self::tableName . '(url, title, body, author, guid, guid_hash, pub_date, feed_id, status)
				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
				');
            if (empty($title)) {
                $l = \OC_L10N::get('news');
                $title = $l->t('no title');
            }
            if (empty($body)) {
                $l = \OC_L10N::get('news');
                $body = $l->t('no body');
            }
            $pub_date = Utils::unixtimeToDbtimestamp($item->getDate());
            $params = array($item->getUrl(), $title, $body, $author, $guid, $guid_hash, $pub_date, $feedid, $status);
            $stmt->execute($params);
            $itemid = \OCP\DB::insertid(self::tableName);
        } else {
            $this->update($item);
        }
        $item->setId($itemid);
        return $itemid;
    }
Example #19
0
 /**
  * @brief Adds a card
  * @param $aid integer Addressbook id
  * @param $card Sabre\VObject\Component  vCard file
  * @param $uri string the uri of the card, default based on the UID
  * @param $isChecked boolean If the vCard should be checked for validity and version.
  * @return insertid on success or false.
  */
 public static function add($aid, VObject\Component $card, $uri = null, $isChecked = false)
 {
     if (is_null($card)) {
         \OCP\Util::writeLog(App::$appname, __METHOD__ . ', No vCard supplied', \OCP\Util::ERROR);
         return null;
     }
     $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 do not have the permissions to add contacts to this addressbook.'));
         }
     }
     if (!$isChecked) {
         //self::updateValuesFromAdd($aid, $card);
     }
     $card->{'VERSION'} = '3.0';
     // Add product ID is missing.
     //$prodid = trim($card->getAsString('PRODID'));
     //if(!$prodid) {
     if (!isset($card->PRODID)) {
         $appinfo = \OCP\App::getAppInfo(App::$appname);
         $appversion = \OCP\App::getAppVersion(App::$appname);
         $prodid = '-//ownCloud//NONSGML ' . $appinfo['name'] . ' ' . $appversion . '//EN';
         $card->add('PRODID', $prodid);
     }
     $sComponent = 'VCARD';
     $fn = '';
     $lastname = '';
     $surename = '';
     if (isset($card->N)) {
         $temp = explode(';', $card->N);
         if (!empty($temp[0])) {
             $lastname = $temp[0];
             $surename = $temp[1];
         }
     }
     $organization = '';
     if (isset($card->ORG)) {
         $temp = explode(';', $card->ORG);
         $organization = $temp[0];
     }
     $bCompany = isset($card->{'X-ABSHOWAS'}) ? 1 : 0;
     if ($bCompany && $organization !== '') {
         $card->FN = $organization;
         $fn = $organization;
     } else {
         if ($lastname !== '') {
             $card->FN = $surename . ' ' . $lastname;
             $fn = $surename . ' ' . $lastname;
         }
     }
     $bGroup = isset($card->CATEGORIES) ? 1 : 0;
     if ($bGroup) {
         $card->CATEGORIES = stripslashes($card->CATEGORIES);
     }
     $uid = $card->UID;
     if (!isset($card->UID)) {
         $uid = substr(md5(rand() . time()), 0, 10);
         $card->UID = $uid;
     }
     $uri = isset($uri) ? $uri : $uid . '.vcf';
     $data = $card->serialize();
     //\OCP\Util::writeLog(App::$appname,'XXXX: '.$fn, \OCP\Util::DEBUG);
     if (isset($card->{'X-ADDRESSBOOKSERVER-KIND'})) {
         $sComponent = 'GROUP';
     }
     $stmt = \OCP\DB::prepare('INSERT INTO `' . App::ContactsTable . '` (`addressbookid`,`fullname`,`surename`,`lastname`,`carddata`,`uri`,`lastmodified`,`component`, `bcategory`,`organization`,`bcompany`) VALUES(?,?,?,?,?,?,?,?,?,?,?)');
     try {
         $result = $stmt->execute(array($aid, $fn, $surename, $lastname, $data, $uri, time(), $sComponent, $bGroup, $organization, $bCompany));
         if (\OCP\DB::isError($result)) {
             \OCP\Util::writeLog(App::$appname, __METHOD__ . 'DB error: ' . \OCP\DB::getErrorMessage($result), \OCP\Util::ERROR);
             return false;
         }
     } catch (\Exception $e) {
         \OCP\Util::writeLog(App::$appname, __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
         \OCP\Util::writeLog(App::$appname, __METHOD__ . ', aid: ' . $aid . ' uri' . $uri, \OCP\Util::DEBUG);
         return false;
     }
     $newid = \OCP\DB::insertid(App::ContactsTable);
     App::loadCategoriesFromVCard($newid, $card);
     App::updateDBProperties($newid, $card);
     App::cacheThumbnail($newid);
     Addressbook::touch($aid);
     //Libasys
     if ($sComponent == 'GROUP') {
         //$newCardInfo=self::find($newid,array('fullname'));
         //$stmt = \OCP\DB::prepare('INSERT INTO  `*PREFIX*vcategory` (`uid`,`type`,`category`,`color`)  VALUES(?,?,?,?) ');
         //$stmt->execute(array(\OCP\User::getUser(),'contact',$newCardInfo['fullname'],'#cccccc'));
     }
     //\OC_Hook::emit('\OCA\Kontakts\VCard', 'post_createVCard', $newid);
     return $newid;
 }
Example #20
0
 /**
  * @brief Adds a card
  * @param $aid integer Addressbook id
  * @param $card Sabre\VObject\Component  vCard file
  * @param $uri string the uri of the card, default based on the UID
  * @param $isChecked boolean If the vCard should be checked for validity and version.
  * @return insertid on success or false.
  */
 public static function add($aid, VObject\Component $card, $uri = null, $isChecked = false)
 {
     if (is_null($card)) {
         \OCP\Util::writeLog('contacts', __METHOD__ . ', No vCard supplied', \OCP\Util::ERROR);
         return null;
     }
     $addressbook = Addressbook::find($aid);
     if ($addressbook['userid'] != \OCP\User::getUser()) {
         $sharedAddressbook = \OCP\Share::getItemSharedWithBySource('addressbook', $aid);
         if (!$sharedAddressbook || !($sharedAddressbook['permissions'] & \OCP\PERMISSION_CREATE)) {
             throw new \Exception(App::$l10n->t('You do not have the permissions to add contacts to this addressbook.'));
         }
     }
     if (!$isChecked) {
         self::updateValuesFromAdd($aid, $card);
     }
     $card->{'VERSION'} = '3.0';
     // Add product ID is missing.
     //$prodid = trim($card->getAsString('PRODID'));
     //if(!$prodid) {
     if (!isset($card->PRODID)) {
         $appinfo = \OCP\App::getAppInfo('contacts');
         $appversion = \OCP\App::getAppVersion('contacts');
         $prodid = '-//ownCloud//NONSGML ' . $appinfo['name'] . ' ' . $appversion . '//EN';
         $card->add('PRODID', $prodid);
     }
     $fn = isset($card->FN) ? $card->FN : '';
     $uri = isset($uri) ? $uri : $card->UID . '.vcf';
     $data = $card->serialize();
     $stmt = \OCP\DB::prepare('INSERT INTO `*PREFIX*contacts_cards` (`addressbookid`,`fullname`,`carddata`,`uri`,`lastmodified`) VALUES(?,?,?,?,?)');
     try {
         $result = $stmt->execute(array($aid, $fn, $data, $uri, time()));
         if (\OC_DB::isError($result)) {
             \OC_Log::write('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);
         \OCP\Util::writeLog('contacts', __METHOD__ . ', aid: ' . $aid . ' uri' . $uri, \OCP\Util::DEBUG);
         return false;
     }
     $newid = \OCP\DB::insertid('*PREFIX*contacts_cards');
     App::loadCategoriesFromVCard($newid, $card);
     App::updateDBProperties($newid, $card);
     App::cacheThumbnail($newid);
     Addressbook::touch($aid);
     \OC_Hook::emit('\\OCA\\Contacts\\VCard', 'post_createVCard', $newid);
     return $newid;
 }
Example #21
0
 /**
  * Get id of the recently inserted record
  * @return mixed
  */
 public function getLastInsertId()
 {
     return \OCP\DB::insertid($this->tableName);
 }
Example #22
0
 /**
  * @brief Adds an object
  * @param integer $id Calendar id
  * @param string $data  object
  * @return insertid
  */
 public static function addSharedTask($id, $calid)
 {
     $shareevent = Object::find($id);
     $stmt = \OCP\DB::prepare('INSERT INTO `' . CalendarApp::CldObjectTable . '` (`calendarid`,`objecttype`,`startdate`,`enddate`,`repeating`,`summary`,`calendardata`,`uri`,`lastmodified`,`isalarm`,`org_objid`,`userid`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)');
     $stmt->execute(array($calid, $shareevent['objecttype'], $shareevent['startdate'], $shareevent['enddate'], $shareevent['repeating'], $shareevent['summary'], $shareevent['calendardata'], $shareevent['uri'], time(), $shareevent['isalarm'], $id, \OCP\User::getUser()));
     $object_id = \OCP\DB::insertid(CalendarApp::CldObjectTable);
     //\OCA\Calendar\App::loadCategoriesFromVCalendar($object_id, $object);
     Calendar::touchCalendar($calid);
     //\OCP\Util::emitHook('OC_Calendar', 'addEvent', $object_id);
     return $object_id;
 }