/** * Retrieves a manufacturer by its name. * * @param string $name The name of the manufacturer to retrieve * @throws Doctrine\ORM\NoResultException If the manufacturer was not found */ public function getManufacturerByName($name) { $dql = "SELECT m FROM PartKeepr\\Manufacturer\\Manufacturer m WHERE m.name = :name"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("name", $name); return $query->getSingleResult(); }
/** * Sets up the default units * @throws \Exception */ public function setupUnits() { $count = 0; $skipped = 0; $data = Setup::loadYAML(self::UNIT_DATA_FILE); $aUnits = array(); foreach ($data as $unitName => $unitData) { if (UnitManager::getInstance()->unitExists($unitName)) { $skipped++; continue; } $unit = new Unit(); $unit->setName($unitName); $unit->setSymbol($unitData["symbol"]); if (array_key_exists("prefixes", $unitData)) { if (!is_array($unitData["prefixes"])) { throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array."); } foreach ($unitData["prefixes"] as $prefix) { $siPrefix = SiPrefixManager::getInstance()->getSiPrefixBySymbol($prefix); if ($siPrefix === false) { throw new \Exception("Unable to find prefix " . $prefix); } $unit->getPrefixes()->add($siPrefix); } } PartKeepr::getEM()->persist($unit); $count++; } $this->entityManager->flush(); $this->logMessage(sprintf("Imported %d Units, skipped %d because they already exist", $count, $skipped)); }
/** * Get all entries which are notified by the event. */ public function getNotifiedListeners() { $session = SessionManager::getCurrentSession(); $query = PartKeepr::getEM()->createQuery("SELECT l FROM PartKeepr\\EventNotification\\LastNotification l JOIN l.session s JOIN l.event e WHERE s.id = ?1 AND e.lastOccured > l.lastNotify"); $query->setParameter(1, $session->getId()); return $query->getResult(); }
/** * A fallback search in case no fulltext search engine is available. This directly queries the database, which is * slow. */ protected function fallbackSearch() { $qb = PartKeepr::getEM()->createQueryBuilder(); $qb->select("q.id")->from($this->getEntityName(), "q")->where("1=1"); $dqlChunks = array(); foreach ($this->query as $id => $queryString) { $partDqlChunks = array(); foreach ($this->getFields() as $field) { $partDqlChunks[] = "LOWER(q." . $field . ") LIKE :filter" . $id; } $dqlChunks[] = "(" . implode(" OR ", $partDqlChunks) . ")"; $qb->setParameter("filter" . $id, "%" . str_replace("%", "\\%", strtolower($queryString)) . "%"); } $qb->andWhere(implode(" AND ", $dqlChunks)); $query = $qb->getQuery(); $result = $query->getArrayResult(); if (count($result) > 0) { $results = array(); foreach ($result as $value) { $results[] = $value["id"]; } return $results; } else { return array(0); } }
/** * Returns a list of manufacturer ic logos. * * @param int $start Start of the list, default 0 * @param int $limit Number of users to list, default 10 * @param string $sort The field to sort by, default "name" * @param string $dir The direction to sort (ASC or DESC), default ASC * @param string $filter The manufacturer id */ public function getManufacturerICLogos($start = 0, $limit = 10, $sort = "name", $dir = "asc", $filter = "") { $qb = PartKeepr::getEM()->createQueryBuilder(); $qb->select("st.id, maf.id AS manufacturer_id")->from("PartKeepr\\Manufacturer\\ManufacturerICLogo", "st")->leftJoin('st.manufacturer', "maf"); if ($filter != "") { $manufacturer = Manufacturer::loadById($filter); $qb = $qb->where("st.manufacturer = :manufacturer"); $qb->setParameter("manufacturer", $manufacturer); } if ($limit > -1) { $qb->setMaxResults($limit); $qb->setFirstResult($start); } $qb->orderBy("st." . $sort, $dir); $query = $qb->getQuery(); $result = $query->getResult(); $totalQueryBuilder = PartKeepr::getEM()->createQueryBuilder(); $totalQueryBuilder->select("COUNT(st.id)")->from("PartKeepr\\Manufacturer\\ManufacturerICLogo", "st"); if ($filter != "") { $totalQueryBuilder = $totalQueryBuilder->where("st.manufacturer = :manufacturer"); $totalQueryBuilder->setParameter("manufacturer", $manufacturer); } $totalQuery = $totalQueryBuilder->getQuery(); return array("data" => $result, "totalCount" => $totalQuery->getSingleScalarResult()); }
/** * Retrieves a distributor by its name. * * @param string $name The name of the distributor to retrieve * @throws Doctrine\ORM\NoResultException If the distributor was not found */ public function getDistributorByName($name) { $dql = "SELECT d FROM PartKeepr\\Distributor\\Distributor d WHERE d.name = :name"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("name", $name); return $query->getSingleResult(); }
/** * Returns a list of project attachments * * @param int $start Start of the list, default 0 * @param int $limit Number of users to list, default 10 * @param string $sort The field to sort by, default "name" * @param string $dir The direction to sort (ASC or DESC), default ASC * @param string $filter The project id */ public function getProjectAttachments($start = 0, $limit = 10, $sort = "name", $dir = "asc", $filter = "") { $qb = PartKeepr::getEM()->createQueryBuilder(); $qb->select("st")->from("PartKeepr\\Project\\ProjectAttachment", "st")->leftJoin('st.project', "fp"); if ($filter != "") { $project = Project::loadById($filter); $qb = $qb->where("st.project = :project"); $qb->setParameter("project", $project); } if ($limit > -1) { $qb->setMaxResults($limit); $qb->setFirstResult($start); } $qb->orderBy("st." . $sort, $dir); $query = $qb->getQuery(); $result = $query->getResult(); $totalQueryBuilder = PartKeepr::getEM()->createQueryBuilder(); $totalQueryBuilder->select("COUNT(st.id)")->from("PartKeepr\\Project\\ProjectAttachment", "st"); if ($filter != "") { $totalQueryBuilder = $totalQueryBuilder->where("st.project = :project"); $totalQueryBuilder->setParameter("project", $project); } $totalQuery = $totalQueryBuilder->getQuery(); $aData = array(); foreach ($result as $item) { $aData[] = $item->serialize(); } return array("data" => $aData, "totalCount" => $totalQuery->getSingleScalarResult()); }
/** * Marks all tips as unread for the current user */ public function markAllTipsAsUnread() { $dql = "DELETE FROM PartKeepr\\TipOfTheDay\\TipOfTheDayHistory th WHERE th.user = :user"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("user", $this->getUser()); $query->execute(); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::update() */ public function update() { $this->requireParameter("id"); $stockEntry = StockEntry::loadById($this->getParameter("id")); if (!SessionManager::getCurrentSession()->getUser()->isAdmin() && !(SessionManager::getCurrentSession()->getUser() && $stockEntry->getUser() && SessionManager::getCurrentSession()->getUser()->getId() == $stockEntry->getUser()->getId())) { throw new \Exception("Permission denied"); } /* It's not allowed to edit a price for a removal */ if (!$stockEntry->isRemoval()) { $stockEntry->setPrice(abs($this->getParameter("price"))); } /** * Only an admin user may correct the in&out stock levels */ if (SessionManager::getCurrentSession()->getUser()->isAdmin()) { if ($this->getParameter("direction") == "out") { $stockEntry->setStockLevel(-abs($this->getParameter("stockLevel"))); } else { $stockEntry->setStockLevel($this->getParameter("stockLevel")); } } if (SessionManager::getCurrentSession()->getUser()->isAdmin()) { try { $stockEntry->setUser(User::loadById($this->getParameter("user_id"))); } catch (\Exception $e) { $stockEntry->setUser(null); } } $stockEntry->setComment($this->getParameter("comment")); PartKeepr::getEM()->flush(); return array("data" => $stockEntry->serialize()); }
/** * Returns sampled statistics from the database. * * This call takes a start and an end time, and calculates a set of statistics * for each interval. * * The sampleSize, which has a default of 50, specifies how many single statistic * points in the given date interval will be returned. * * This function interpolates the statistics if there are not enough statistic samples available. */ public function getSampledStatistics() { $fooStart = microtime(true); $this->requireParameter("startDateTime"); $this->requireParameter("endDateTime"); $start = \DateTime::createFromFormat("Y-m-d H:i:s", $this->getParameter("startDateTime")); $end = \DateTime::createFromFormat("Y-m-d H:i:s", $this->getParameter("endDateTime")); if ($start->getTimestamp() > $end->getTimestamp()) { // Swap both times list($start, $end) = array($end, $start); } if ($this->hasParameter("sampleSize")) { $sampleSize = $this->getParameter("sampleSize"); } else { $sampleSize = 25; } $intervalSize = intval(($end->getTimestamp() - $start->getTimestamp()) / $sampleSize); $queryStartTime = clone $start; $queryEndTime = clone $start; $queryEndTime->add(new \DateInterval("PT" . $intervalSize . "S")); $partUnitQuery = "SELECT pu FROM PartKeepr\\Part\\PartUnit pu"; $query = PartKeepr::getEM()->createQuery($partUnitQuery); $aPartUnits = $query->getResult(); $aRecords = array(); $dql = "SELECT AVG(sts.parts) AS parts, AVG(sts.categories) AS categories FROM PartKeepr\\Statistic\\StatisticSnapshot sts WHERE sts.dateTime >= :start AND sts.dateTime <= :end"; $mainQuery = PartKeepr::getEM()->createQuery($dql); $dql = "SELECT AVG(stsu.stockLevel) AS stockLevel FROM PartKeepr\\Statistic\\StatisticSnapshotUnit stsu JOIN stsu.statisticSnapshot sts WHERE sts.dateTime >= :start AND sts.dateTime <= :end AND stsu.partUnit = :partUnit"; $subQuery = PartKeepr::getEM()->createQuery($dql); for ($i = 0; $i < $sampleSize; $i++) { $mainQuery->setParameter("start", $queryStartTime); $mainQuery->setParameter("end", $queryEndTime); $result = $mainQuery->getResult(); $record = $result[0]; if ($record["parts"] !== null) { $record["parts"] = floatval($record["parts"]); } if ($record["categories"] !== null) { $record["categories"] = floatval($record["categories"]); } foreach ($aPartUnits as $partUnit) { $subQuery->setParameter("start", $queryStartTime); $subQuery->setParameter("end", $queryEndTime); $subQuery->setParameter("partUnit", $partUnit); $aResult = $subQuery->getResult(); if ($aResult[0]["stockLevel"] !== null) { $record["units"][$partUnit->getName()] = floatval($aResult[0]["stockLevel"]); } else { $record["units"][$partUnit->getName()] = null; } } $record["start"] = $queryStartTime->format("Y-m-d H:i:s"); if ($record["parts"] !== null) { $aRecords[] = $record; } $queryStartTime->add(new \DateInterval("PT" . $intervalSize . "S")); $queryEndTime->add(new \DateInterval("PT" . $intervalSize . "S")); } return array("status" => "ok", "data" => $aRecords); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::destroy() */ public function destroy() { $this->requireParameter("id"); $file = ProjectAttachment::loadById($this->getParameter("id")); PartKeepr::getEM()->remove($file); PartKeepr::getEM()->flush(); return array("data" => null); }
public function destroy() { $this->requireParameter("id"); $logo = ManufacturerICLogo::loadById($this->getParameter("id")); PartKeepr::getEM()->remove($logo); PartKeepr::getEM()->flush(); return array("data" => null); }
/** * Gets an existing event by its name. * @param unknown $name */ public function getByName($name) { $obj = PartKeepr::getEM()->getRepository('PartKeepr\\EventNotification\\Event')->findOneByName($name); if (!$obj) { throw new ObjectNotFoundException('PartKeepr\\EventNotification\\Event', "name={$name}"); } return $obj; }
/** * Authenticates the given user. If successful, an instance * of the user is returned. * * @param User $user The user to authenticate * @throws InvalidLoginDataException Thrown if the user's credentials are not valid */ public function authenticate(User $user) { $result = PartKeepr::getEM()->getRepository("PartKeepr\\User\\User")->findOneBy(array("username" => $user->getUsername(), "password" => $user->getHashedPassword())); if ($result == null) { throw new InvalidLoginDataException(); } else { return $result; } }
public function moveFootprint() { $this->requireParameter("targetCategory"); $this->requireParameter("id"); $footprint = Footprint::loadById($this->getParameter("id")); $category = FootprintCategory::loadById($this->getParameter("targetCategory")); $footprint->setCategory($category); PartKeepr::getEM()->flush(); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::update() */ public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $distributor = Distributor::loadById($this->getParameter("id")); $distributor->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $distributor->serialize()); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::update() */ public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $manufacturer = ManufacturerManager::getInstance()->getManufacturer($this->getParameter("id")); $manufacturer->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $manufacturer->serialize()); }
/** * (non-PHPdoc) * @see PartKeepr\Service.RestfulService::update() */ public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $entity = ProjectManager::getInstance()->getEntity($this->getParameter("id")); $entity->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $entity->serialize()); }
/** * (non-PHPdoc) * @see \PartKeepr\Service\RestfulService::update() */ public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $obj = PrintingJobConfigurationManager::getInstance()->getEntity($this->getParameter("id")); $obj->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $obj->serialize()); }
public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $obj = PageBasicLayoutManager::getInstance()->getObjectById($this->getParameter("id")); $obj->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $obj->serialize()); }
/** * This update method only supports updating the done flag! * @see \PartKeepr\Service\RestfulService::update() */ public function update() { $this->requireParameter("id"); $this->requireParameter("done"); $obj = PrintingJobManager::getInstance()->getEntity($this->getParameter("id")); $this->checkPermission($obj); $obj->setDone($this->getParameter("done") == 'true'); PartKeepr::getEM()->flush(); return array("data" => $obj->serialize()); }
/** * Checks if the schema is up-to-date. If yes, it returns "complete", if not, it returns "incomplete". * * @param none * @return string Either "complete" or "incomplete" */ protected function getSchemaStatus() { $metadatas = PartKeepr::getEM()->getMetadataFactory()->getAllMetadata(); $schemaTool = new \Doctrine\ORM\Tools\SchemaTool(PartKeepr::getEM()); $queries = $schemaTool->getUpdateSchemaSql($metadatas, true); if (count($queries) > 0) { return "incomplete"; } else { return "complete"; } }
public function hasUnacknowledgedNotices() { $dql = "SELECT COUNT(c) FROM PartKeepr\\SystemNotice\\SystemNotice c WHERE c.acknowledged = :a"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("a", false, \PDO::PARAM_BOOL); $bRetval = false; if ($query->getSingleScalarResult() > 0) { $bRetval = true; } return array("data" => array("unacknowledgedNotices" => $bRetval)); }
/** * Updates the given category. */ public function update() { $this->requireParameter("id"); $this->requireParameter("name"); $category = $this->getCategoryManager()->getCategory($this->getParameter("id")); $category->getNode()->setName($this->getParameter("name")); $category->getNode()->setDescription($this->getParameter("description", "")); PartKeepr::getEM()->persist($category->getNode()); $this->getCategoryManager()->updateCategoryPaths($category); return array("data" => $this->serializeCategory($category)); }
public function siPrefixExists($prefix) { $dql = "SELECT COUNT(sip) FROM PartKeepr\\SiPrefix\\SiPrefix sip WHERE sip.prefix = :prefix"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("prefix", $prefix); if ($query->getSingleScalarResult() == 0) { return false; } else { return true; } }
/** * Updates the user informations. * @see PartKeepr\Service.RestfulService::update() */ public function update() { if (!SessionManager::getCurrentSession()->getUser()->isAdmin()) { throw new \Exception("Permission denied"); } $this->requireParameter("id"); $this->requireParameter("username"); $user = UserManager::getInstance()->getUser($this->getParameter("id")); $user->deserialize($this->getParameters()); PartKeepr::getEM()->flush(); return array("data" => $user->serialize()); }
public function start() { session_start(); session_regenerate_id(); session_destroy(); unset($_SESSION); session_start(); $query = PartKeepr::getEM()->createQuery("DELETE FROM PartKeepr\\Session\\Session s WHERE s.sessionid = :session"); $query->setParameter("session", session_id()); $query->execute(); $this->sessionid = session_id(); }
/** * Updates the tip database. Expects an array of page names. * * This method clears all page names and re-creates them. This saves * alot of engineering, because we don't need to match contents * within the database against contents in an array. * * @param array $aPageNames The page names as array. Page names are stored as string. */ private static function updateTipDatabase(array $aPageNames) { $dql = "DELETE FROM PartKeepr\\TipOfTheDay\\TipOfTheDay"; $query = PartKeepr::getEM()->createQuery($dql); $query->execute(); foreach ($aPageNames as $pageName) { $tip = new TipOfTheDay(); $tip->setName($pageName); PartKeepr::getEM()->persist($tip); } PartKeepr::getEM()->flush(); }
public function getOrCreateStorageLocation($storageLocation) { if (is_int($storageLocation)) { try { return $this->getStorageLocation($storageLocation); } catch (StorageLocationNotFoundException $e) { } } $sl = new StorageLocation(); $sl->setName($storageLocation); PartKeepr::getEM()->persist($sl); return $sl; }
/** * Returns a list of entities. * * @param ManagerFilter $filter The filter settings for this query */ public function getList(ManagerFilter $filter) { $qb = PartKeepr::getEM()->createQueryBuilder(); $qb->select("COUNT(q.id)")->from($this->getEntityName(), "q"); $this->applyFiltering($qb, $filter); $this->applyCustomQuery($qb, $filter); $totalQuery = $qb->getQuery(); $this->applyResultFields($qb, $filter); $this->applyPagination($qb, $filter); $this->applySorting($qb, $filter); $query = $qb->getQuery(); return array("data" => $this->getResult($query), "totalCount" => $totalQuery->getSingleScalarResult()); }