function mediashare_mediahandlerapi_getHandlerInfo($args) { $dom = ZLanguage::getModuleDomain('mediashare'); $mimeType = strtolower($args['mimeType']); $filename = strtolower($args['filename']); if (!empty($filename)) { $dotPos = strpos($filename, '.'); if ($dotPos === false) { $fileType = ''; } else { $fileType = substr($filename, $dotPos + 1); } } else { $fileType = ''; } $pntable = pnDBGetTables(); $handlersTable = $pntable['mediashare_mediahandlers']; $handlersColumn = $pntable['mediashare_mediahandlers_column']; $sql = "SELECT DISTINCT {$handlersColumn['handler']},\r\n {$handlersColumn['foundMimeType']},\r\n {$handlersColumn['foundFileType']}\r\n FROM {$handlersTable}\r\n WHERE {$handlersColumn['mimeType']} = '" . DataUtil::formatForStore($mimeType) . "'\r\n OR {$handlersColumn['fileType']} = '" . DataUtil::formatForStore($fileType) . "'\r\n\t\t\t\t\t\t\t\t\t\t\t\tAND {$handlersColumn['active']} =\t1 "; $result = DBUtil::executeSQL($sql); $errormsg = __f('Unable to locate media handler for \'%1$s\' (%2$s)', array($filename, $mimeType), $dom); if ($result === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('mediahandlerapi.getHandlerInfo', $errormsg), $dom)); } if (!$result) { return LogUtil::registerError($errormsg); } $colArray = array('handlerName', 'mimeType', 'fileType'); $handler = DBUtil::marshallObjects($result, $colArray); return $handler[0]; }
/** * Do the migration * * With this function, the actual migration is done. * * @return boolean true on sucessful migration, false else * @since 0.2 */ function EZComments_migrateapi_pnFlashGames() { // Security check if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) { return LogUtil::registerError('pnFlashGames comments migration: Not Admin'); } // Get datbase setup $tables = DBUtil::getTables(); $Commentstable = $tables['pnFlashGames_comments']; $Commentscolumn = $tables['pnFlashGames_comments_column']; $Usertable = $tables['users']; $Usercolumn = $tables['users_column']; $sql = "SELECT {$Commentscolumn['gid']},\n {$Commentscolumn['uname']},\n {$Commentscolumn['date']},\n {$Commentscolumn['comment']},\n {$Usercolumn['uid']}\n FROM {$Commentstable}\n LEFT JOIN {$Usertable}\n ON {$Commentscolumn['uname']} = {$Usercolumn['uname']}"; $result = DBUtil::executeSQL($sql); if ($result == false) { return LogUtil::registerError('pnFlashGames migration: DB Error: ' . $sql . ' -- ' . mysql_error()); } // loop through the old comments and insert them one by one into the DB $items = DBUtil::marshalObjects($result, array('gid', 'uname', 'date', 'comment', 'uid')); foreach ($items as $item) { // set the correct user id for anonymous users if (empty($item['uid'])) { $item['uid'] = 1; } $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => 'pnFlashGames', 'objectid' => DataUtil::formatForStore($item['gid']), 'url' => ModUtil::url('pnFlashGames', 'user', 'display', array('id' => $item['gid'])), 'comment' => $item['comment'], 'subject' => '', 'uid' => $item['uid'], 'date' => $item['date'])); if (!$id) { return LogUtil::registerError('pnFlashGames migration: Error creating comment'); } } return LogUtil::registerStatus('pnFlashGames migration successful'); }
/** * Search * * do the actual search and display the results * * @return output the search results */ public function search($args) { if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_READ)) { return true; } $minlen = 3; $maxlen = 30; if (strlen($args['q']) < $minlen || strlen($args['q']) > $maxlen) { return LogUtil::registerStatus($this->__f('The comments can only be searched for words that are longer than %1$s and less than %2$s characters!', array($minlen, $maxlen))); } ModUtil::dbInfoLoad('Search'); $tables = DBUtil::getTables(); // ezcomments tables $ezcommentstable = $tables['EZComments']; $ezcommentscolumn = $tables['EZComments_column']; // our own tables $searchTable = $tables['search_result']; $searchColumn = $tables['search_result_column']; // where $where = Search_Api_User::construct_where($args, array($ezcommentscolumn['subject'], $ezcommentscolumn['comment'])); $where .= " AND " . $ezcommentscolumn['url'] . " != ''"; $sessionId = session_id(); $insertSql = "INSERT INTO {$searchTable}\n ({$searchColumn['title']},\n {$searchColumn['text']},\n {$searchColumn['extra']},\n {$searchColumn['module']},\n {$searchColumn['created']},\n {$searchColumn['session']})\n VALUES\n "; $comments = DBUtil::selectObjectArray('EZComments', $where); foreach ($comments as $comment) { $sql = $insertSql . '(' . '\'' . DataUtil::formatForStore($comment['subject']) . '\', ' . '\'' . DataUtil::formatForStore($comment['comment']) . '\', ' . '\'' . DataUtil::formatForStore($comment['url']) . '\', ' . '\'' . 'EZComments' . '\', ' . '\'' . DataUtil::formatForStore($comment['date']) . '\', ' . '\'' . DataUtil::formatForStore($sessionId) . '\')'; $insertResult = DBUtil::executeSQL($sql); if (!$insertResult) { return LogUtil::registerError($this->__('Error! Could not load items.')); } } return true; }
/** * Update attributes of a block. * * @param int $args ['bid'] the ID of the block to update. * @param string $args ['title'] the new title of the block. * @param string $args ['description'] the new description of the block. * @param string $args ['positions'] the new positions of the block. * @param string $args ['url'] the new URL of the block. * @param string $args ['language'] the new language of the block. * @param string $args ['content'] the new content of the block. * * @return bool true on success, false on failure. */ public function update($args) { // Optional arguments if (!isset($args['url'])) { $args['url'] = ''; } if (!isset($args['content'])) { $args['content'] = ''; } // Argument check if (!isset($args['bid']) || !is_numeric($args['bid']) || !isset($args['content']) || !isset($args['title']) || !isset($args['description']) || !isset($args['language']) || !isset($args['collapsable']) || !isset($args['defaultstate'])) { return LogUtil::registerArgsError(); } $block = DBUtil::selectObjectByID('blocks', $args['bid'], 'bid'); // Security check // this function is called durung the init process so we have to check in _ZINSTALLVER // is set as alternative to the correct permission check if (!System::isInstalling() && !SecurityUtil::checkPermission('Blocks::', "{$block['bkey']}:{$block['title']}:{$block['bid']}", ACCESS_EDIT)) { return LogUtil::registerPermissionError(); } $item = array('bid' => isset($args['bid']) ? $args['bid'] : $block['bid'], 'content' => isset($args['content']) ? $args['content'] : $block['content'], 'title' => isset($args['title']) ? $args['title'] : $block['title'], 'description' => isset($args['description']) ? $args['description'] : $block['description'], 'filter' => isset($args['filter']) ? serialize($args['filter']) : $block['filter'], 'url' => isset($args['url']) ? $args['url'] : $block['url'], 'refresh' => isset($args['refresh']) ? $args['refresh'] : $block['refresh'], 'language' => isset($args['language']) ? $args['language'] : $block['language'], 'collapsable' => isset($args['collapsable']) ? $args['collapsable'] : $block['collapsable'], 'defaultstate' => isset($args['defaultstate']) ? $args['defaultstate'] : $block['defaultstate']); $res = DBUtil::updateObject($item, 'blocks', '', 'bid'); if (!$res) { return LogUtil::registerError($this->__('Error! Could not save your changes.')); } // leave unchanged positions as is, delete removed positions from placements table // and add placement for new positions if (isset($args['positions'])) { // Get all existing block positions. We do not use the userapi function here because we need // an associative array for the next steps: key = pid (position id) $allblockspositions = DBUtil::selectObjectArray('block_positions', null, 'pid', -1, -1, 'pid', null); foreach ($allblockspositions as $positionid => $blockposition) { if (in_array($positionid, $args['positions'])) { // position name is present in the array submitted from the user $where = "WHERE pid = '" . DataUtil::formatForStore($positionid) . '\''; $blocksinposition = DBUtil::selectObjectArray('block_placements', $where, 'sortorder', -1, -1, 'bid'); if (array_key_exists($item['bid'], $blocksinposition)) { // block is already in this position, placement did not change, this means we do nothing } else { // add the block to the given position as last entry (max(sortorder) +1 $newplacement = array('pid' => $blockposition['pid'], 'bid' => $item['bid'], 'order' => count($blocksinpositions)); $res = DBUtil::insertObject($newplacement, 'block_placements', 'bid', true); if (!$res) { return LogUtil::registerError($this->__('Error! Could not perform the insertion.')); } } } else { // position name is NOT present in the array submitted from the user // delete the block id from the placements table for this position $where = '(bid = \'' . DataUtil::formatForStore($item['bid']) . '\' AND pid = \'' . DataUtil::formatForStore($blockposition['pid']) . '\')'; $res = DBUtil::deleteWhere('block_placements', $where); if (!$res) { return LogUtil::registerError($this->__('Error! Could not save your changes.')); } } } } return true; }
/** * @param int args[uid] userid */ public function userOnline($args) { $uid = $args['uid']; $tables = DBUtil::getTables(); $columns = $tables['session_info_column']; $where = "{$columns['uid']} = '" . DataUtil::formatForStore($uid) . "'"; return DBUtil::selectObject('session_info', $where); }
/** * Set plugins */ function mediashare_adminapi_setTemplateGlobally($args) { $dom = ZLanguage::getModuleDomain('mediashare'); $new = array('template' => DataUtil::formatForStore($args['template'])); if (!DBUtil::updateObject($new, 'mediashare_albums', '1=1', 'id')) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('adminapi.setTemplateGlobally', 'Could not set the template.'), $dom)); } return true; }
/** * Listener for installer.subscriberarea.uninstalled * * @param Zikula_Event $event * * @return void */ public static function hookAreaDelete(Zikula_Event $event) { $areaId = $event['areaid']; // Database information ModUtil::dbInfoLoad('EZComments'); $tables = DBUtil::getTables(); $columns = $tables['EZComments_column']; // Get items $where = "WHERE {$columns['areaid']} = '" . DataUtil::formatForStore($areaId) . "'"; DBUtil::deleteWhere('EZComments', $where); }
function genFilter($filter = array()) { $wheres = array(); $filterFields = array('name', 'tag', 'value', 'page', 'uid', 'username', 'ip', 'impact', 'date'); foreach ($filterFields as $fieldName) { if (isset($filter[$fieldName]) && $filter[$fieldName]) { $wheres[] = "ids_" . $fieldName . " = '" . \DataUtil::formatForStore($filter[$fieldName]) . "'"; } } $where = implode(' AND ', $wheres); return $where; }
/** * Do the migration * * With this function, the actual migration is done. * * @return boolean true on sucessful migration, false else * @since 0.2 */ function EZComments_migrateapi_news() { // Security check if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) { return LogUtil::registerError('News migration: Not Admin'); } // Get datbase setup $tables = DBUtil::getTables(); $EZCommentstable = $tables['EZComments']; $EZCommentscolumn = $tables['EZComments_column']; $Commentstable = $tables['comments']; $Commentscolumn = $tables['comments_column']; if (version_compare(PN_VERSION_NUM, '1', '>=')) { EZComments_get76xcolumns_news($Commentstable, $Commentscolumn); } if (is_null($Commentstable) || is_null($Commentscolumn)) { return LogUtil::registerError('News migration: Comments tables not found'); } $Usertable = $tables['users']; $Usercolumn = $tables['users_column']; $sql = "SELECT {$Commentscolumn['tid']},\n {$Commentscolumn['sid']},\n {$Commentscolumn['date']}, \n {$Usercolumn['uid']},\n {$Commentscolumn['comment']},\n {$Commentscolumn['subject']},\n {$Commentscolumn['pid']}\n FROM {$Commentstable}\n LEFT JOIN {$Usertable}\n ON {$Commentscolumn['name']} = {$Usercolumn['uname']}"; $result = DBUtil::executeSQL($sql); if ($result == false) { return LogUtil::registerError('News migration: DB Error'); } // array to rebuild the patents $comments = array(0 => array('newid' => -1)); // loop through the old comments and insert them one by one into the DB $items = DBUtil::marshalObjects($result, array('tid', 'sid', 'date', 'uid', 'comment', 'subject', 'replyto')); foreach ($items as $item) { // set the correct user id for anonymous users if (empty($item['uid'])) { $item['uid'] = 1; } $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => 'News', 'objectid' => DataUtil::formatForStore($item['sid']), 'url' => ModUtil::url('News', 'user', 'display', array('sid' => $item['sid'])), 'comment' => $item['comment'], 'subject' => $item['subject'], 'uid' => $item['uid'], 'date' => $item['date'])); if (!$id) { return LogUtil::registerError('News migration: Error creating comment'); } $comments[$item['tid']] = array('newid' => $id, 'pid' => $item['replyto']); } // rebuild the links to the parents $tids = array_keys($comments); foreach ($tids as $tid) { if ($tid != 0) { $v = $comments[$tid]; $sql = "UPDATE {$EZCommentstable}\n SET {$EZCommentscolumn['replyto']} = '" . $comments[$v['pid']]['newid'] . "'\n WHERE {$EZCommentscolumn['id']} = '{$v['newid']}'"; $result = DBUtil::executeSQL($sql); } } // activate the ezcomments hook for the news module ModUtil::apiFunc('Modules', 'admin', 'enablehooks', array('callermodname' => 'News', 'hookmodname' => 'EZComments')); return LogUtil::registerStatus('News migration successful'); }
function deletefavourite() { $objectid = FormUtil::getPassedValue('objectid', null, 'POST'); $userid = FormUtil::getPassedValue('userid', null, 'POST'); if (!SecurityUtil::checkPermission('AddressBook::', "::", ACCESS_COMMENT)) { AjaxUtil::error($this->__('Error! No authorization to access this module.')); } $ztables = DBUtil::getTables(); $fav_column = $ztables['addressbook_favourites_column']; $where = "{$fav_column['favadr_id']} = '" . DataUtil::formatForStore($objectid) . "' AND {$fav_column['favuser_id']} = '" . DataUtil::formatForStore($userid) . "'"; DBUtil::deleteWhere('addressbook_favourites', $where); return; }
/** * Smarty function to wrap MUBoard_Form_View generated form controls with suitable form tags. * * @param array $params Parameters passed in the block tag. * @param string $content Content of the block. * @param Zikula_Form_View $view Reference to Zikula_Form_View object. * * @return string The rendered output. */ function smarty_block_muboardform($params, $content, $view) { if ($content) { PageUtil::addVar('stylesheet', 'system/Theme/style/form/style.css'); $encodingHtml = array_key_exists('enctype', $params) ? " enctype=\"{$params['enctype']}\"" : ''; $action = htmlspecialchars(System::getCurrentUri()); $classString = ''; if (isset($params['cssClass'])) { $classString = "class=\"{$params['cssClass']}\" "; } $request = new Zikula_Request_Http(); $id = $request->getGet()->filter('id', 0, FILTER_SANITIZE_NUMBER_INT); $forumid = $request->getGet()->filter('forum', 0, FILTER_SANITIZE_NUMBER_INT); // we check if the entrypoint is part of the url $stripentrypoint = ModUtil::getVar('ZConfig', 'shorturlsstripentrypoint'); // get url name $tables = DBUtil::getTables(); $modcolumn = $tables['modules_column']; $module = 'MUBoard'; $where = "{$modcolumn['name']} = '" . DataUtil::formatForStore($module) . "'"; $module = DBUtil::selectObject('modules', $where); $urlname = $module['url']; if (ModUtil::getVar('ZConfig', 'shorturls') == 0) { if (strpos($action, "func=display") !== false) { $action = 'index.php?module=' . $urlname . '&type=user&func=edit&ot=posting&answer=1'; } if (strpos($action, "func=edit&ot=posting") !== false && $forumid > 0) { $action = 'index.php?module=' . $urlname . '&type=user&func=edit&ot=posting&forum' . $forumid; } } else { if (strpos($action, $urlname . "/posting/id.") !== false) { if ($stripentrypoint == 1) { $action = $urlname . '/edit/ot/posting/answer/1'; } elseif ($stripentrypoint == 0) { $action = 'index.php/' . $urlname . '/edit/ot/posting/answer/1'; } } if (strpos($action, "edit/ot/posting/forum/") !== false && $forumid > 0) { if ($stripentrypoint == 1) { $action = $urlname . '/edit/ot/posting/forum/' . $forumid; } elseif ($stripentrypoint == 0) { $action = 'index.php/' . $urlname . '/edit/ot/posting/forum/' . $forumid; } } } $view->postRender(); $formId = $view->getFormId(); $out = "\n <form id=\"{$formId}\" {$classString}action=\"{$action}\" method=\"post\"{$encodingHtml}>\n {$content}\n <div>\n {$view->getStateHTML()}\n {$view->getStateDataHTML()}\n {$view->getIncludesHTML()}\n {$view->getCsrfTokenHtml()}\n <input type=\"hidden\" name=\"__formid\" id=\"form__id\" value=\"{$formId}\" />\n <input type=\"hidden\" name=\"FormEventTarget\" id=\"FormEventTarget\" value=\"\" />\n <input type=\"hidden\" name=\"FormEventArgument\" id=\"FormEventArgument\" value=\"\" />\n <script type=\"text/javascript\">\n <!--\n function FormDoPostBack(eventTarget, eventArgument)\n {\n var f = document.getElementById('{$formId}');\n if (!f.onsubmit || f.onsubmit())\n {\n f.FormEventTarget.value = eventTarget;\n f.FormEventArgument.value = eventArgument;\n f.submit();\n }\n }\n // -->\n </script>\n </div>\n </form>\n "; return $out; } }
/** * Search plugin main function **/ public function search($args) { ModUtil::dbInfoLoad('Search'); $dbtables = DBUtil::getTables(); $searchTable = $dbtables['search_result']; $searchColumn = $dbtables['search_result_column']; $pageTable = $dbtables['content_page']; $pageColumn = $dbtables['content_page_column']; $contentTable = $dbtables['content_content']; $contentColumn = $dbtables['content_content_column']; $contentSearchTable = $dbtables['content_searchable']; $contentSearchColumn = $dbtables['content_searchable_column']; $sessionId = session_id(); $where = Search_Api_User::construct_where($args, array($contentSearchColumn['text']), null); $wheretitle = Search_Api_User::construct_where($args, array($pageColumn['title']), $pageColumn['language']); // Direct SQL way of searching in titles and searchable content items // for Pages and Content items that are visible/active // Optimization and conversion into DBUtil calls should be done $sql = "INSERT INTO $searchTable ($searchColumn[title], $searchColumn[text], $searchColumn[module], $searchColumn[extra], $searchColumn[created], $searchColumn[session]) SELECT DISTINCT $pageColumn[title], $contentSearchColumn[text], 'Content', $pageColumn[id], $pageColumn[cr_date] AS createdDate, '" . DataUtil::formatForStore($sessionId) . "' FROM $pageTable JOIN $contentTable ON $contentColumn[pageId] = $pageColumn[id] JOIN $contentSearchTable ON $contentSearchColumn[contentId] = $contentColumn[id] WHERE ($where or $wheretitle) AND $pageColumn[active] = 1 AND ($pageColumn[activeFrom] IS NULL OR $pageColumn[activeFrom] <= NOW()) AND ($pageColumn[activeTo] IS NULL OR $pageColumn[activeTo] >= NOW()) AND $contentColumn[active] = 1 AND $contentColumn[visiblefor] " . (UserUtil::isLoggedIn() ? '<=1' : '>=1'); $dbresult = DBUtil::executeSQL($sql); if (!$dbresult) { return LogUtil::registerError($this->__('Error! Could not load any Content pages or items.')); } return true; }
/** * * @param permorder array of sorted permissions (value = permission id) * @return mixed true or Ajax error */ public function changeorder() { $this->checkAjaxToken(); $this->throwForbiddenUnless(SecurityUtil::checkPermission('Permissions::', '::', ACCESS_ADMIN)); $permorder = $this->request->getPost()->get('permorder'); $dbtable = DBUtil::getTables(); $permcolumn = $dbtable['group_perms_column']; for ($cnt = 0; $cnt < count($permorder); $cnt++) { $where = "WHERE {$permcolumn['pid']} = '" . (int) DataUtil::formatForStore($permorder[$cnt]) . "'"; $obj = array('sequence' => $cnt); DBUtil::updateObject($obj, 'group_perms', $where, 'pid'); } return new Zikula_Response_Ajax(array('result' => true)); }
/** * process user input and form a WHERE clause * @return string SQL where clause */ private function _process_args(&$args) { // optional arguments. if (!isset($args['startnum']) || !is_numeric($args['startnum'])) { $args['startnum'] = -1; } if (!isset($args['numitems']) || !is_numeric($args['numitems'])) { $args['numitems'] = -1; } if (!isset($args['author'])) { $args['author'] = null; } if (!isset($args['keyword'])) { $args['keyword'] = null; } if (!isset($args['category'])) { $args['category'] = null; } if (!isset($args['catFilter']) || !is_numeric($args['catFilter'])) { $args['catFilter'] = array(); } if (!isset($args['rootCat'])) { $args['rootCat'] = 0; } // build the where clause $wheres = array(); if (isset($args['qid'])) { $wheres[] = "qid = " . DataUtil::formatForStore($args['qid']); } if ($args['author']) { $wheres[] = "author = '" . DataUtil::formatForStore($args['author']) . "'"; } if (isset($args['status'])) { $wheres[] = "status = '" . DataUtil::formatForStore($args['status']) . "'"; } if ($args['category']) { if (is_array($args['category'])) { $args['catFilter'] = $args['category']; } else { $args['catFilter'][] = $args['category']; } $args['catFilter']['__META__'] = array('module' => 'Quotes'); } if ($args['keyword']) { $wheres[] = "quote LIKE '%" . DataUtil::formatForStore($args['keyword']) . "%'"; } $args['where'] = implode(' AND ', $wheres); return $args['where']; }
function mediashare_sourcesapi_getSources($args) { $dom = ZLanguage::getModuleDomain('mediashare'); $pntable = pnDBGetTables(); $sourcesTable = $pntable['mediashare_sources']; $sourcesColumn = $pntable['mediashare_sources_column']; $where = ""; if ($args['active']) { $where = "WHERE {$sourcesColumn['active']} = '" . DataUtil::formatForStore($args['active']) . "'"; } $result = DBUtil::selectObjectArray('mediashare_sources', $where); if ($result === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('sourcesapi.getSources', 'Could not retrieve the sources.'), $dom)); } return $result; }
function updateFile($orgFileReference, $newFilename) { $dom = ZLanguage::getModuleDomain('mediashare'); $pntable = pnDBGetTables(); $mediadbTable = $pntable['mediashare_mediadb']; $mediadbColumn = $pntable['mediashare_mediadb_column']; $data = file_get_contents($newFilename); $bytes = count($data); $orgFileReference = DataUtil::formatForStore($orgFileReference); $sql = "UPDATE {$mediadbTable}\n SET {$mediadbColumn['data']} = '" . DataUtil::formatForStore($data) . "',\n {$mediadbColumn['bytes']} = '{$bytes}'\n WHERE {$mediadbColumn['fileref']} = '{$orgFileReference}'"; $result = DBUtil::executeSQL($sql); if ($result === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('vfsHandlerDB.updateFile', 'Could not update the file information.'), $dom)); } return true; }
public function getYoutubeVideos($channelId = '', $collectionId = 0) { $dom = ZLanguage::getModuleDomain($this->name); $youtubeApi = ModUtil::getVar($this->name, 'youtubeApi'); $collectionRepository = MUVideo_Util_Model::getCollectionRepository(); $collectionObject = $collectionRepository->selectById($collectionId); $api = self::getData("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" . $channelId . "&key=" . $youtubeApi); // https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCJC8ynLpY_q89tmNhqIf1Sg&key={YOUR_API_KEY} //$api = self::getData("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={DEINE_PLAYLIST_ID}&maxResults=10&fields=items%2Fsnippet&key=" . $youtubeApi); $videos = json_decode($api, true); $movieRepository = MUVideo_Util_Model::getMovieRepository(); $where = 'tbl.urlOfYoutube != \'' . DataUtil::formatForStore('') . '\''; // we look for movies with a youtube url entered $existingYoutubeVideos = $movieRepository->selectWhere($where); if ($existingYoutubeVideos && count($existingYoutubeVideos > 0)) { foreach ($existingYoutubeVideos as $existingYoutubeVideo) { $youtubeId = str_replace('https://www.youtube.com/watch?v=', '', $existingYoutubeVideo['urlOfYoutube']); $videoIds[] = $youtubeId; } } if (is_array($videos['items'])) { foreach ($videos['items'] as $videoData) { if (isset($videoData['id']['videoId'])) { if (isset($videoIds) && is_array($videoIds)) { if (in_array($videoData['id']['videoId'], $videoIds)) { continue; } } $serviceManager = ServiceUtil::getManager(); $entityManager = $serviceManager->getService('doctrine.entitymanager'); $newYoutubeVideo = new MUVideo_Entity_Movie(); $newYoutubeVideo->setTitle($videoData['snippet']['title']); $newYoutubeVideo->setDescription($videoData['snippet']['description']); $newYoutubeVideo->setUrlOfYoutube('https://www.youtube.com/watch?v=' . $videoData['id']['videoId']); $newYoutubeVideo->setWidthOfMovie('400'); $newYoutubeVideo->setHeightOfMovie('300'); $newYoutubeVideo->setWorkflowState('approved'); $newYoutubeVideo->setCollection($collectionObject); $entityManager->persist($newYoutubeVideo); $entityManager->flush(); LogUtil::registerStatus(__('The movie', $dom) . ' ' . $videoData['snippet']['title'] . ' ' . __('was created and put into the collection', $dom) . ' ' . $collectionObject['title']); } } } $redirectUrl = ModUtil::url($this->name, 'user', 'display', array('ot' => 'collection', 'id' => $collectionId)); return System::redirect($redirectUrl); }
/** * This method get the abos of the relevant forum and return the mailadresses * @param int $forumid id of relevant forum if available * @param int $userId userid of the user created the posting */ protected static function getForumAbos($forumid, $userId) { // we get a repository for abos $repository = MUBoard_Util_Model::getAboRepository(); $where = 'tbl.forumid = \'' . DataUtil::formatForStore($forumid) . '\''; $where .= ' AND '; $where .= 'tbl.createdUserId != \'' . DataUtil::formatForStore($userId) . '\''; $forumabos = $repository->selectWhere($where); foreach ($forumabos as $forumabo) { //if ($forumabo['createdUserId'] != $userid) { $userids[] = $forumabo['createdUserId']; //} } foreach ($userids as $userid) { $mailadresses[] = UserUtil::getVar('email', $userid); } return $mailadresses; }
/** * Change the status of a block. * * Invert the status of a given block id (collapsed/uncollapsed). * * @return void */ public function changestatus() { $bid = FormUtil::getPassedValue('bid'); $uid = UserUtil::getVar('uid'); $dbtable = DBUtil::getTables(); $column = $dbtable['userblocks_column']; $where = "WHERE {$column['bid']}='" . DataUtil::formatForStore($bid) . "' AND {$column['uid']}='" . DataUtil::formatForStore($uid) . "'"; $active = DBUtil::selectField('userblocks', 'active', $where); $obj = array(); $obj['active'] = $active ? 0 : 1; $where = "WHERE {$column['uid']}='" . DataUtil::formatForStore($uid) . "' AND {$column['bid']}='" . DataUtil::formatForStore($bid) . "'"; $res = DBUtil::updateObject($obj, 'userblocks', $where); if (!$res) { return LogUtil::registerError($this->__('Error! An SQL error occurred.')); } // now lets get back to where we came from $this->redirect(System::serverGetVar('HTTP_REFERER')); }
/** * Get all admin messages items that match the criteria * * @author Mark West, Jorn Wildt * @param bool args['activeonly'] only show active items * @return bool true/false on success/failure */ function Admin_Messages_searchapi_search($args) { $dom = ZLanguage::getModuleDomain('Admin_Messages'); // Security check if (!SecurityUtil::checkPermission('Admin_Messages::', '::', ACCESS_READ)) { return true; } // get the db and table info ModUtil::dbInfoLoad('Search'); $pntable = DBUtil::getTables(); $messagestable = $pntable['message']; $messagescolumn = $pntable['message_column']; $searchTable =& $pntable['search_result']; $searchColumn =& $pntable['search_result_column']; // form the where clause $where = ''; if (!ModUtil::getVar('Admin_Messages', 'allowsearchinactive') || isset($args['activeonly']) && (bool) $args['activeonly']) { $where .= " {$messagescolumn['active']} = 1 AND "; } $where .= " ({$messagescolumn['date']}+{$messagescolumn['expire']} > '" . time() . "' OR {$messagescolumn['expire']} = 0) AND"; $where .= search_construct_where($args, array($messagescolumn['title'], $messagescolumn['content']), $messagescolumn['language']); $sessionId = session_id(); $sql = "\nSELECT\n {$messagescolumn['mid']} as mid,\n {$messagescolumn['title']} as title,\n {$messagescolumn['content']} as text,\n {$messagescolumn['date']} as date\nFROM {$messagestable}\nWHERE {$where}"; $result = DBUtil::executeSQL($sql); if (!$result) { return LogUtil::registerError(__('Error! Could not load data.')); } $insertSql = "INSERT INTO {$searchTable}\n ({$searchColumn['title']},\n {$searchColumn['text']},\n {$searchColumn['module']},\n {$searchColumn['created']},\n {$searchColumn['session']})\nVALUES "; // Process the result set and insert into search result table for (; !$result->EOF; $result->MoveNext()) { $message = $result->GetRowAssoc(2); if (SecurityUtil::checkPermission('Admin_Messages::', "{$message['title']}::{$message['mid']}", ACCESS_READ)) { $sql = $insertSql . '(' . '\'' . DataUtil::formatForStore($message['title']) . '\', ' . '\'' . DataUtil::formatForStore($message['text']) . '\', ' . '\'' . 'Admin_Messages' . '\', ' . '\'' . DataUtil::formatForStore(DateUtil::getDatetime($message['date'])) . '\', ' . '\'' . DataUtil::formatForStore($sessionId) . '\')'; $insertResult = DBUtil::executeSQL($sql); if (!$insertResult) { return LogUtil::registerError(__('Error! Could not load data.', $dom)); } } } return true; }
/** * delete a admin category * @param int $args['cid'] ID of the category * @return bool true on success, false on failure */ public function delete($args) { if (!isset($args['cid']) || !is_numeric($args['cid'])) { return LogUtil::registerArgsError(); } $category = ModUtil::apiFunc('Admin', 'admin', 'get', array('cid' => $args['cid'])); if ($category == false) { return LogUtil::registerError($this->__('Sorry! No such item found.')); } if (!SecurityUtil::checkPermission('Admin::Category', "{$category['catname']}::{$category['cid']}", ACCESS_DELETE)) { return LogUtil::registerPermissionError(); } // Avoid deletion of the default category $defaultcategory = $this->getVar('defaultcategory'); if ($category['cid'] == $defaultcategory) { return LogUtil::registerError($this->__('Error! You cannot delete the default module category used in the administration panel.')); } // Avoid deletion of the start category $startcategory = $this->getVar('startcategory'); if ($category['cid'] == $startcategory) { return LogUtil::registerError($this->__('Error! This module category is currently set as the category that is initially displayed when you visit the administration panel. You must first select a different category for initial display. Afterwards, you will be able to delete the category you have just attempted to remove.')); } // move all modules from the category to be deleted into the // default category. We can't do this via a simple DBUtil call // because it's a non-object based mass update of the key field. $dbtable = DBUtil::getTables(); $column = $dbtable['admin_module_column']; $where = "WHERE {$column['cid']} = '" . (int) DataUtil::formatForStore($category['cid']) . "'"; $obj = array(); $obj['cid'] = $defaultcategory; $res = DBUtil::updateObject($obj, 'admin_module', $where); if (!$res) { return LogUtil::registerError($this->__('Error! Could not perform the deletion.')); } // Now actually delete the category if (!DBUtil::deleteObjectByID('admin_category', $category['cid'], 'cid')) { return LogUtil::registerError($this->__('Error! Could not perform the deletion.')); } // Let the calling process know that we have finished successfully return true; }
/** * Do the migration * * With this function, the actual migration is done. * * @return boolean true on sucessful migration, false else * @since 0.6 */ function EZComments_migrateapi_reviews() { // Security check if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) { return LogUtil::registerError('Reviews migration: Not Admin'); } // Get datbase setup ModUtil::dbInfoLoad('Reviews', 'EZComments/migrateapi/Reviews', true); $tables = DBUtil::getTables(); $Commentstable = $tables['reviews_comments']; $Commentscolumn = $tables['reviews_comments_column']; if (version_compare(PN_VERSION_NUM, '1', '>=')) { EZComments_get76xcolumns_reviews($Commentstable, $Commentscolumn); } if (is_null($Commentstable) || is_null($Commentscolumn)) { return LogUtil::registerError('Reviews migration: Comments tables not found'); } $Usertable = $tables['users']; $Usercolumn = $tables['users_column']; // note: there's nothing we can do with the score...... $sql = "SELECT {$Commentscolumn['cid']},\n {$Commentscolumn['rid']},\n {$Commentscolumn['date']}, \n {$Usercolumn['uid']}, \n {$Commentscolumn['comments']},\n {$Commentscolumn['score']}\n FROM {$Commentstable}\n LEFT JOIN {$Usertable}\n ON {$Commentscolumn['userid']} = {$Usercolumn['uname']}"; $result = DBUtil::executeSQL($sql); if ($result == false) { return LogUtil::registerError('Reviews migration: DB Error'); } // loop through the old comments and insert them one by one into the DB $items = DBUtil::marshalObjects($result, array('cid', 'rid', 'date', 'uid', 'comment', 'score')); foreach ($items as $item) { // set the correct user id for anonymous users if (empty($item['uid'])) { $item['uid'] = 1; } $id = ModUtil::apiFunc('EZComments', 'user', 'create', array('mod' => 'Reviews', 'objectid' => DataUtil::formatForStore($item['rid']), 'url' => ModUtil::url('Reviews', 'user', 'display', array('id' => $item['rid'])), 'comment' => $item['comment'], 'subject' => '', 'uid' => $item['uid'], 'date' => $item['date'])); if (!$id) { return LogUtil::registerError('Reviews migration: Error creating comment'); } } // activate the ezcomments hook for the Reviews module ModUtil::apiFunc('Modules', 'admin', 'enablehooks', array('callermodname' => 'Reviews', 'hookmodname' => 'EZComments')); return LogUtil::registerStatus('Reviews migration successful'); }
/** * Zikula_View modifier to create a link to a users profile * * Example * * Simple version, shows $username * {$username|userprofilelink} * Simple version, shows $username, using class="classname" * {$username|userprofilelink:classname} * Using profile.gif instead of username, no class * {$username|userprofilelink:'':'images/profile.gif'} * * Using language depending image from pnimg. Note that we pass * the pnimg result array to the modifier as-is * { pnimg src='profile.gif' assign=profile} * {$username|userprofilelink:'classname':$profile} * * @param string $string The users name. * @param string $class The class name for the link (optional). * @param mixed $image The image to show instead of the username (optional). * May be an array as created by pnimg. * @param integer $maxLength If set then user names are truncated to x chars. * * @return string The output. */ function smarty_modifier_userprofilelink($string, $class = '', $image = '', $maxLength = 0) { LogUtil::log(__f('Warning! Template modifier {$var|%1$s} is deprecated, please use {$var|%2$s} instead.', array('userprofilelink', 'profilelinkbyuname} {$var|profilelinkbyuid')), E_USER_DEPRECATED); // TODO - This does not handle cases where the uname is made up entirely of digits (e.g. $uname == "123456"). It will interpret it // as a uid. A new modifier is needed that acts on uids and only uids, and this modifier should act on unames and only unames. if (is_numeric($string)) { $uid = DataUtil::formatForStore($string); $uname = UserUtil::getVar('uname', $uid); } else { $uname = DataUtil::formatForStore($string); $uid = UserUtil::getIdFromName($uname); } $showUname = DataUtil::formatForDisplay($uname); $profileModule = System::getVar('profilemodule', ''); if (isset($uid) && $uid && isset($uname) && $uname && $uid > 1 && !empty($profileModule) && ModUtil::available($profileModule) && strtolower($uname) != strtolower(ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_ANONYMOUS_DISPLAY_NAME))) { if (!empty($class)) { $class = ' class="' . DataUtil::formatForDisplay($class) . '"'; } if (!empty($image)) { if (is_array($image)) { // if it is an array we assume that it is an pnimg array $show = '<img src="' . DataUtil::formatForDisplay($image['src']) . '" alt="' . DataUtil::formatForDisplay($image['alt']) . '" width="' . DataUtil::formatForDisplay($image['width']) . '" height="' . DataUtil::formatForDisplay($image['height']) . '" />'; } else { $show = '<img src="' . DataUtil::formatForDisplay($image) . '" alt="' . $showUname . '" />'; } } elseif ($maxLength > 0) { // truncate the user name to $maxLength chars $showLength = strlen($showUname); $truncEnd = $maxLength > $showLength ? $showLength : $maxLength; $showUname = substr($string, 0, $truncEnd); } $profileLink = '<a' . $class . ' title="' . DataUtil::formatForDisplay(__('Personal information')) . ': ' . $showUname . '" href="' . DataUtil::formatForDisplay(ModUtil::url($profileModule, 'user', 'view', array('uid' => $uid), null, null, true)) . '">' . $showUname . '</a>'; } elseif (!empty($image)) { $profileLink = ''; //image for anonymous user should be "empty" } else { $profileLink = DataUtil::formatForDisplay($string); } return $profileLink; }
/** * get all users that use the given avatar * *@params $args['avatar'] string the avatar name */ public function getusersbyavatar($args) { if (!SecurityUtil::checkPermission('Avatar::', '::', ACCESS_READ)) { return LogUtil::registerPermissionError(); } $users = array(); if (!isset($args['avatar']) || empty($args['avatar'])) { return $users; } $ztables = DBUtil::getTables(); $userdatacolumn = $ztables['objectdata_attributes_column']; if ($args['avatar'] == 'blank.gif') { $where = $userdatacolumn['attribute_name'] . '="avatar" AND (' . $userdatacolumn['value'] . '="' . DataUtil::formatForStore($args['avatar']) . '" OR ' . $userdatacolumn['value'] . '="")'; } else { $where = $userdatacolumn['attribute_name'] . '="avatar" AND ' . $userdatacolumn['value'] . '="' . DataUtil::formatForStore($args['avatar']) . '"'; } $avatarusers = DBUtil::selectObjectArray('objectdata_attributes', $where); foreach ($avatarusers as $avataruser) { $users[$avataruser['id']] = UserUtil::getVar('uname', $avataruser['object_id']); } return $users; }
/** * Performs a user search based on the user name fragment entered so far. * * Parameters passed via POST: * --------------------------- * string fragment A partial user name entered by the user. * * @return string Zikula_Response_Ajax_Plain with list of users matching the criteria. */ public function getUsers() { $this->checkAjaxToken(); $view = Zikula_View::getInstance($this->name); if (SecurityUtil::checkPermission('Users::', '::', ACCESS_MODERATE)) { $fragment = $this->request->query->get('fragment', $this->request->request->get('fragment')); ModUtil::dbInfoLoad($this->name); $tables = DBUtil::getTables(); $usersColumn = $tables['users_column']; $where = 'WHERE ' . $usersColumn['uname'] . ' REGEXP \'(' . DataUtil::formatForStore($fragment) . ')\''; $results = DBUtil::selectObjectArray('users', $where); $view->assign('results', $results); } $output = $view->fetch('users_ajax_getusers.tpl'); return new Zikula_Response_Ajax_Plain($output); }
/** * update the used disk for the user * @author: Albert Pérez Monfort * @return: True if success and false otherwise */ public function updateUsedSpace() { // security check if (!SecurityUtil::checkPermission('Files::', '::', ACCESS_ADD)) { return LogUtil::registerPermissionError(); } // get user used space $usedSpace = ModUtil::apiFunc('Files', 'user', 'get'); if (!$usedSpace) { // user row doesn't exists and it is created ModUtil::apiFunc('Files', 'user', 'createUserFilesInfo'); } $initFolderPath = ModUtil::func('Files', 'user', 'getInitFolderPath'); $spaceUsed = ModUtil::apiFunc('Files', 'user', 'calcUsedSpace', array('folderToCalc' => $initFolderPath)); $item = array('diskUse' => DataUtil::formatForStore($spaceUsed)); $pntable =& DBUtil::getTables(); $c = $pntable['Files_column']; $where = "{$c['userId']}=" . UserUtil::getVar('uid'); if (!DBUtil::updateObject($item, 'Files', $where, 'fileId')) { return LogUtil::registerError($this->__('Error! Could not update the used disk.')); } // Let the calling process know that we have finished successfully return true; }
/** * get all pages * * @param array $args Arguments array. * * @return mixed array of items, or false on failure */ public function getall($args) { // Optional arguments. if (!isset($args['startnum']) || empty($args['startnum'])) { $args['startnum'] = 0; } if (!isset($args['numitems']) || empty($args['numitems'])) { $args['numitems'] = -1; } if (!isset($args['ignoreml']) || !is_bool($args['ignoreml'])) { $args['ignoreml'] = false; } if (!isset($args['language'])) { $args['language'] = null; } if (!isset($args['category'])) { $args['category'] = null; } if (!is_numeric($args['startnum']) || !is_numeric($args['numitems'])) { return LogUtil::registerArgsError(); } // Security check if (!SecurityUtil::checkPermission('Pages::', '::', ACCESS_READ)) { return array(); } $catFilter = array(); if (isset($args['category']) && !empty($args['category'])) { if (is_array($args['category'])) { $catFilter = $args['category']; } elseif (isset($args['property'])) { $property = $args['property']; $catFilter[$property] = $args['category']; } $catFilter['__META__'] = array('module' => 'Pages'); } elseif (isset($args['catfilter'])) { $catFilter = $args['catfilter']; } // populate an array with each part of the where clause and then implode the array if there is a need. // credit to Jorg Napp for this technique - markwest $table = DBUtil::getTables(); $pagescolumn = $table['pages_column']; $queryargs = array(); if (System::getVar('multilingual') == 1 && !$args['ignoreml'] && $args['language']) { $queryargs[] = '(' . $pagescolumn['language'] . ' = "' . DataUtil::formatForStore($args['language']) . '"' .' OR ' . $pagescolumn['language'] . ' = "")'; } $where = null; if (count($queryargs) > 0) { $where = ' WHERE ' . implode(' AND ', $queryargs); } // define the permission filter to apply $permFilter = array(); $permFilter[] = array('component_left' => 'Pages', 'instance_left' => 'title', 'instance_right' => 'pageid', 'level' => ACCESS_READ); $orderby = $pagescolumn['pageid']; if (isset($args['order']) && !empty($args['order'])) { $orderby = $pagescolumn[strtolower($args['order'])]; } $orderdir = 'DESC'; if (isset($args['orderdir']) && !empty($args['orderdir'])) { $orderdir = $args['orderdir']; } $orderby = $orderby . ' ' . $orderdir; // get the objects from the db $objArray = DBUtil::selectObjectArray( 'pages', $where, $orderby, $args['startnum']-1, $args['numitems'], '', $permFilter, $catFilter ); // check for an error with the database code, and if so set an appropriate // error message and return if ($objArray === false) { return LogUtil::registerError($this->__('Error! Could not load any page.')); } // need to do this here as the category expansion code can't know the // root category which we need to build the relative path component if ($objArray && isset($args['catregistry']) && $args['catregistry']) { ObjectUtil::postProcessExpandedObjectArrayCategories($objArray, $args['catregistry']); } // return the items return $objArray; }
/** * delete module */ public function uninstall() { DBUtil::dropTable('categories_category'); DBUtil::dropTable('categories_mapobj'); DBUtil::dropTable('categories_mapmeta'); DBUtil::dropTable('categories_registry'); $this->delVars(); // delete other modules use of categories flag $dbtable = DBUtil::getTables(); $cols = $dbtable['module_vars_column']; $name = DataUtil::formatForStore('enablecategorization'); $where = "{$cols['name']}='{$name}'"; $res = (bool) DBUtil::deleteWhere('module_vars', $where); // Deletion successful return true; }
function getajaxcompanies() { $fragment = FormUtil::getPassedValue('fragment'); // Get DB $dbconn = Doctrine_Manager::getInstance()->getCurrentConnection(); $ztable = DBUtil::getTables(); // define tables and columns $userstable =& $ztable['addressbook_address']; $userscolumn =& $ztable['addressbook_address_column']; $sql = "SELECT DISTINCT {$userscolumn['company']},\n {$userscolumn['address1']},\n {$userscolumn['address2']},\n {$userscolumn['zip']},\n {$userscolumn['city']},\n {$userscolumn['state']},\n {$userscolumn['country']}\n FROM {$userstable}\n WHERE {$userscolumn['company']} REGEXP '" . DataUtil::formatForStore($fragment) . "' ORDER BY {$userscolumn['company']}"; $results = $dbconn->Execute($sql); // get the companies $out = '<ul>'; while (list($company, $address1, $address2, $zip, $city, $state, $country) = $results->fields) { $results->MoveNext(); $out .= '<li><a href="#">' . DataUtil::formatForDisplay($company) . '<span style="display:none">#</span>,' . DataUtil::formatForDisplay($address1) . '<span style="display:none">#' . DataUtil::formatForDisplay($address1) . '#' . DataUtil::formatForDisplay($address2) . '#' . DataUtil::formatForDisplay($zip) . '#' . DataUtil::formatForDisplay($city) . '#' . DataUtil::formatForDisplay($state) . '#' . DataUtil::formatForDisplay($country) . '</span></a></li>'; } $out .= '</ul>'; echo $out; return true; }
/** * Contruct part of a where clause out of the supplied search parameters */ public static function construct_where($args, $fields, $mlfield = null) { $where = ''; if (!isset($args) || empty($args) || !isset($fields) || empty($fields)) { return $where; } if (!empty($args['q'])) { $q = DataUtil::formatForStore($args['q']); $q = str_replace('%', '\\%', $q); // Don't allow user input % as wildcard $where .= ' ('; if ($args['searchtype'] !== 'EXACT') { $searchwords = self::split_query($q); $connector = $args['searchtype'] == 'AND' ? ' AND ' : ' OR '; } else { $searchwords = array("%{$q}%"); } $start = true; foreach ($searchwords as $word) { $where .= ( !$start ? $connector : '') . ' ('; // I'm not sure if "LIKE" is the best solution in terms of DB portability (PC) foreach ($fields as $field) { $where .= "{$field} LIKE '$word' OR "; } $where = substr($where, 0, -4); $where .= ')'; $start = false; } $where .= ') '; } // Check if we're in a multilingual setup if (isset($mlfield) && System::getVar('multilingual') == 1) { $currentlang = ZLanguage::getLanguageCode(); $where .= "AND ({$mlfield} = '$currentlang' OR {$mlfield} = '')"; } return $where; }