diff --git "a/000000.jsonl" "b/000000.jsonl" --- "a/000000.jsonl" +++ "b/000000.jsonl" @@ -1,13 +1,3 @@ -{"repo": "dokufreaks/plugin-discussion", "pr_number": 348, "filename": "helper.php", "file_before": "\n */\n\n/**\n * Class helper_plugin_discussion\n */\nclass helper_plugin_discussion extends DokuWiki_Plugin\n{\n\n /**\n * @return array\n */\n public function getMethods()\n {\n $result = [];\n $result[] = [\n 'name' => 'th',\n 'desc' => 'returns the header of the comments column for pagelist',\n 'return' => ['header' => 'string'],\n ];\n $result[] = [\n 'name' => 'td',\n 'desc' => 'returns the link to the discussion section with number of comments',\n 'params' => [\n 'id' => 'string',\n 'number of comments (optional)' => 'integer'],\n 'return' => ['link' => 'string'],\n ];\n $result[] = [\n 'name' => 'getThreads',\n 'desc' => 'returns pages with discussion sections, sorted by recent comments',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'getComments',\n 'desc' => 'returns recently added or edited comments individually',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'isDiscussionModerator',\n 'desc' => 'check if current user is member of moderator groups',\n 'params' => [],\n 'return' => ['isModerator' => 'boolean']\n ];\n return $result;\n }\n\n /**\n * Returns the column header for the Pagelist Plugin\n *\n * @return string\n */\n public function th()\n {\n return $this->getLang('discussion');\n }\n\n /**\n * Returns the link to the discussion section of a page\n *\n * @param string $id page id\n * @param string $col column name, used if more columns needed per plugin\n * @param string $class class name per cell set by reference\n * @param null|int $num number of visible comments -- internally used, not by pagelist plugin\n * @return string\n */\n public function td($id, $col = null, &$class = null, $num = null)\n {\n $section = '#discussion__section';\n\n if (!isset($num)) {\n $cfile = metaFN($id, '.comments');\n $comments = unserialize(io_readFile($cfile, false));\n\n $num = $comments['number'];\n if (!$comments['status'] || ($comments['status'] == 2 && !$num)) {\n return '';\n }\n }\n\n if ($num == 0) {\n $comment = '0 ' . $this->getLang('nocomments');\n } elseif ($num == 1) {\n $comment = '1 ' . $this->getLang('comment');\n } else {\n $comment = $num . ' ' . $this->getLang('comments');\n }\n\n return ''\n . $comment\n . '';\n }\n\n /**\n * Returns an array of pages with discussion sections, sorted by recent comments\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param null|int $num\n * @param string|bool $skipEmpty\n * @return array\n */\n public function getThreads($ns, $num = null, $skipEmpty = false)\n {\n global $conf;\n\n // returns the list of pages in the given namespace and it's subspaces\n $dir = utf8_encodeFN(str_replace(':', '/', $ns));\n $opts = [\n 'depth' => 0, // 0=all\n 'skipacl' => true // is checked later\n ];\n $items = [];\n search($items, $conf['datadir'], 'search_allpages', $opts, $dir);\n\n // add pages with comments to result\n $result = [];\n foreach ($items as $item) {\n $id = $item['id'];\n\n // some checks\n $perm = auth_quickaclcheck($id);\n if ($perm < AUTH_READ) continue; // skip if no permission\n $file = metaFN($id, '.comments');\n if (!@file_exists($file)) continue; // skip if no comments file\n $data = unserialize(io_readFile($file, false));\n $status = $data['status'];\n $number = $data['number'];\n\n if (!$status || ($status == 2 && !$number)) continue; // skip if comments are off or closed without comments\n if ($skipEmpty && $number == 0) continue; // skip if discussion is empty and flag is set\n\n //new comments are added to the end of array\n $date = false;\n if(isset($data['comments'])) {\n $latestcomment = end($data['comments']);\n $date = $latestcomment['date']['created'] ?? false;\n }\n //e.g. if no comments\n if(!$date) {\n $date = filemtime($file);\n }\n\n $meta = p_get_metadata($id);\n $result[$date . '_' . $id] = [\n 'id' => $id,\n 'file' => $file,\n 'title' => $meta['title'] ?? '',\n 'date' => $date,\n 'user' => $meta['creator'],\n 'desc' => $meta['description']['abstract'],\n 'num' => $number,\n 'comments' => $this->td($id, null, $class, $number),\n 'status' => $status,\n 'perm' => $perm,\n 'exists' => true,\n 'anchor' => 'discussion__section',\n ];\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n if (is_numeric($num)) {\n $result = array_slice($result, 0, $num);\n }\n\n return $result;\n }\n\n /**\n * Returns an array of recently added comments to a given page or namespace\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param int|null $num number of comment per page\n * @return array\n */\n public function getComments($ns, $num = null)\n {\n global $conf, $INPUT;\n\n $first = $INPUT->int('first');\n\n if (!$num || !is_numeric($num)) {\n $num = $conf['recent'];\n }\n\n $result = [];\n $count = 0;\n\n if (!@file_exists($conf['metadir'] . '/_comments.changes')) {\n return $result;\n }\n\n // read all recent changes. (kept short)\n $lines = file($conf['metadir'] . '/_comments.changes');\n\n $seen = []; //caches seen pages in order to skip them\n // handle lines\n $line_num = count($lines);\n for ($i = ($line_num - 1); $i >= 0; $i--) {\n $rec = $this->handleRecentComment($lines[$i], $ns, $seen);\n if ($rec !== false) {\n if (--$first >= 0) continue; // skip first entries\n\n $result[$rec['date']] = $rec;\n $count++;\n // break when we have enough entries\n if ($count >= $num) break;\n }\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n return $result;\n }\n\n /* ---------- Changelog function adapted for the Discussion Plugin ---------- */\n\n /**\n * Internal function used by $this->getComments()\n *\n * don't call directly\n *\n * @param string $line comment changelog line\n * @param string $ns namespace (or id) to filter\n * @param array $seen array to cache seen pages\n * @return array|false with\n * 'type' => string,\n * 'extra' => string comment id,\n * 'id' => string page id,\n * 'perm' => int ACL permission\n * 'file' => string file path of wiki page\n * 'exists' => bool wiki page exists\n * 'name' => string name of user\n * 'desc' => string text of comment\n * 'anchor' => string\n *\n * @see getRecentComments()\n * @author Andreas Gohr \n * @author Ben Coburn \n * @author Esther Brunner \n *\n */\n protected function handleRecentComment($line, $ns, &$seen)\n {\n if (empty($line)) return false; //skip empty lines\n\n // split the line into parts\n $recent = parseChangelogLine($line);\n if ($recent === false) return false;\n\n $cid = $recent['extra'];\n $fullcid = $recent['id'] . '#' . $recent['extra'];\n\n // skip seen ones\n if (isset($seen[$fullcid])) return false;\n\n // skip 'show comment' log entries\n if ($recent['type'] === 'sc') return false;\n\n // remember in seen to skip additional sights\n $seen[$fullcid] = 1;\n\n // check if it's a hidden page or comment\n if (isHiddenPage($recent['id'])) return false;\n if ($recent['type'] === 'hc') return false;\n\n // filter namespace or id\n if ($ns && strpos($recent['id'] . ':', $ns . ':') !== 0) return false;\n\n // check ACL\n $recent['perm'] = auth_quickaclcheck($recent['id']);\n if ($recent['perm'] < AUTH_READ) return false;\n\n // check existance\n $recent['file'] = wikiFN($recent['id']);\n $recent['exists'] = @file_exists($recent['file']);\n if (!$recent['exists']) return false;\n if ($recent['type'] === 'dc') return false;\n\n // get discussion meta file name\n $data = unserialize(io_readFile(metaFN($recent['id'], '.comments'), false));\n\n // check if discussion is turned off\n if ($data['status'] === 0) return false;\n\n $parent_id = $cid;\n // Check for the comment and all parents if they exist and are visible.\n do {\n $tcid = $parent_id;\n\n // check if the comment still exists\n if (!isset($data['comments'][$tcid])) return false;\n // check if the comment is visible\n if ($data['comments'][$tcid]['show'] != 1) return false;\n\n $parent_id = $data['comments'][$tcid]['parent'];\n } while ($parent_id && $parent_id != $tcid);\n\n // okay, then add some additional info\n if (is_array($data['comments'][$cid]['user'])) {\n $recent['name'] = $data['comments'][$cid]['user']['name'];\n } else {\n $recent['name'] = $data['comments'][$cid]['name'];\n }\n $recent['desc'] = strip_tags($data['comments'][$cid]['xhtml']);\n $recent['anchor'] = 'comment_' . $cid;\n\n return $recent;\n }\n\n /**\n * Check if current user is member of the moderator groups\n *\n * @return bool is moderator?\n */\n public function isDiscussionModerator()\n {\n global $USERINFO, $INPUT;\n $groups = trim($this->getConf('moderatorgroups'));\n\n if (auth_ismanager()) {\n return true;\n }\n // Check if user is member of the moderator groups\n if (!empty($groups) && auth_isMember($groups, $INPUT->server->str('REMOTE_USER'), (array)$USERINFO['grps'])) {\n return true;\n }\n\n return false;\n }\n}\n", "file_after": "\n */\n\n/**\n * Class helper_plugin_discussion\n */\nclass helper_plugin_discussion extends DokuWiki_Plugin\n{\n\n /**\n * @return array\n */\n public function getMethods()\n {\n $result = [];\n $result[] = [\n 'name' => 'th',\n 'desc' => 'returns the header of the comments column for pagelist',\n 'return' => ['header' => 'string'],\n ];\n $result[] = [\n 'name' => 'td',\n 'desc' => 'returns the link to the discussion section with number of comments',\n 'params' => [\n 'id' => 'string',\n 'number of comments (optional)' => 'integer'],\n 'return' => ['link' => 'string'],\n ];\n $result[] = [\n 'name' => 'getThreads',\n 'desc' => 'returns pages with discussion sections, sorted by recent comments',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'getComments',\n 'desc' => 'returns recently added or edited comments individually',\n 'params' => [\n 'namespace' => 'string',\n 'number (optional)' => 'integer'],\n 'return' => ['pages' => 'array'],\n ];\n $result[] = [\n 'name' => 'isDiscussionModerator',\n 'desc' => 'check if current user is member of moderator groups',\n 'params' => [],\n 'return' => ['isModerator' => 'boolean']\n ];\n return $result;\n }\n\n /**\n * Returns the column header for the Pagelist Plugin\n *\n * @return string\n */\n public function th()\n {\n return $this->getLang('discussion');\n }\n\n /**\n * Returns the link to the discussion section of a page\n *\n * @param string $id page id\n * @param string $col column name, used if more columns needed per plugin\n * @param string $class class name per cell set by reference\n * @param null|int $num number of visible comments -- internally used, not by pagelist plugin\n * @return string\n */\n public function td($id, $col = null, &$class = null, $num = null)\n {\n $section = '#discussion__section';\n\n if (!isset($num)) {\n $cfile = metaFN($id, '.comments');\n $comments = unserialize(io_readFile($cfile, false));\n\n if ($comments) {\n $num = $comments['number'];\n if (!$comments['status'] || ($comments['status'] == 2 && !$num)) {\n return '';\n }\n } else {\n $num = 0;\n }\n }\n\n if ($num == 0) {\n $comment = '0 ' . $this->getLang('nocomments');\n } elseif ($num == 1) {\n $comment = '1 ' . $this->getLang('comment');\n } else {\n $comment = $num . ' ' . $this->getLang('comments');\n }\n\n return ''\n . $comment\n . '';\n }\n\n /**\n * Returns an array of pages with discussion sections, sorted by recent comments\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param null|int $num\n * @param string|bool $skipEmpty\n * @return array\n */\n public function getThreads($ns, $num = null, $skipEmpty = false)\n {\n global $conf;\n\n // returns the list of pages in the given namespace and it's subspaces\n $dir = utf8_encodeFN(str_replace(':', '/', $ns));\n $opts = [\n 'depth' => 0, // 0=all\n 'skipacl' => true // is checked later\n ];\n $items = [];\n search($items, $conf['datadir'], 'search_allpages', $opts, $dir);\n\n // add pages with comments to result\n $result = [];\n foreach ($items as $item) {\n $id = $item['id'];\n\n // some checks\n $perm = auth_quickaclcheck($id);\n if ($perm < AUTH_READ) continue; // skip if no permission\n $file = metaFN($id, '.comments');\n if (!@file_exists($file)) continue; // skip if no comments file\n $data = unserialize(io_readFile($file, false));\n $status = $data['status'];\n $number = $data['number'];\n\n if (!$status || ($status == 2 && !$number)) continue; // skip if comments are off or closed without comments\n if ($skipEmpty && $number == 0) continue; // skip if discussion is empty and flag is set\n\n //new comments are added to the end of array\n $date = false;\n if(isset($data['comments'])) {\n $latestcomment = end($data['comments']);\n $date = $latestcomment['date']['created'] ?? false;\n }\n //e.g. if no comments\n if(!$date) {\n $date = filemtime($file);\n }\n\n $meta = p_get_metadata($id);\n $result[$date . '_' . $id] = [\n 'id' => $id,\n 'file' => $file,\n 'title' => $meta['title'] ?? '',\n 'date' => $date,\n 'user' => $meta['creator'],\n 'desc' => $meta['description']['abstract'],\n 'num' => $number,\n 'comments' => $this->td($id, null, $class, $number),\n 'status' => $status,\n 'perm' => $perm,\n 'exists' => true,\n 'anchor' => 'discussion__section',\n ];\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n if (is_numeric($num)) {\n $result = array_slice($result, 0, $num);\n }\n\n return $result;\n }\n\n /**\n * Returns an array of recently added comments to a given page or namespace\n * Note: also used for content by Feed Plugin\n *\n * @param string $ns\n * @param int|null $num number of comment per page\n * @return array\n */\n public function getComments($ns, $num = null)\n {\n global $conf, $INPUT;\n\n $first = $INPUT->int('first');\n\n if (!$num || !is_numeric($num)) {\n $num = $conf['recent'];\n }\n\n $result = [];\n $count = 0;\n\n if (!@file_exists($conf['metadir'] . '/_comments.changes')) {\n return $result;\n }\n\n // read all recent changes. (kept short)\n $lines = file($conf['metadir'] . '/_comments.changes');\n\n $seen = []; //caches seen pages in order to skip them\n // handle lines\n $line_num = count($lines);\n for ($i = ($line_num - 1); $i >= 0; $i--) {\n $rec = $this->handleRecentComment($lines[$i], $ns, $seen);\n if ($rec !== false) {\n if (--$first >= 0) continue; // skip first entries\n\n $result[$rec['date']] = $rec;\n $count++;\n // break when we have enough entries\n if ($count >= $num) break;\n }\n }\n\n // finally sort by time of last comment\n krsort($result);\n\n return $result;\n }\n\n /* ---------- Changelog function adapted for the Discussion Plugin ---------- */\n\n /**\n * Internal function used by $this->getComments()\n *\n * don't call directly\n *\n * @param string $line comment changelog line\n * @param string $ns namespace (or id) to filter\n * @param array $seen array to cache seen pages\n * @return array|false with\n * 'type' => string,\n * 'extra' => string comment id,\n * 'id' => string page id,\n * 'perm' => int ACL permission\n * 'file' => string file path of wiki page\n * 'exists' => bool wiki page exists\n * 'name' => string name of user\n * 'desc' => string text of comment\n * 'anchor' => string\n *\n * @see getRecentComments()\n * @author Andreas Gohr \n * @author Ben Coburn \n * @author Esther Brunner \n *\n */\n protected function handleRecentComment($line, $ns, &$seen)\n {\n if (empty($line)) return false; //skip empty lines\n\n // split the line into parts\n $recent = parseChangelogLine($line);\n if ($recent === false) return false;\n\n $cid = $recent['extra'];\n $fullcid = $recent['id'] . '#' . $recent['extra'];\n\n // skip seen ones\n if (isset($seen[$fullcid])) return false;\n\n // skip 'show comment' log entries\n if ($recent['type'] === 'sc') return false;\n\n // remember in seen to skip additional sights\n $seen[$fullcid] = 1;\n\n // check if it's a hidden page or comment\n if (isHiddenPage($recent['id'])) return false;\n if ($recent['type'] === 'hc') return false;\n\n // filter namespace or id\n if ($ns && strpos($recent['id'] . ':', $ns . ':') !== 0) return false;\n\n // check ACL\n $recent['perm'] = auth_quickaclcheck($recent['id']);\n if ($recent['perm'] < AUTH_READ) return false;\n\n // check existance\n $recent['file'] = wikiFN($recent['id']);\n $recent['exists'] = @file_exists($recent['file']);\n if (!$recent['exists']) return false;\n if ($recent['type'] === 'dc') return false;\n\n // get discussion meta file name\n $data = unserialize(io_readFile(metaFN($recent['id'], '.comments'), false));\n\n // check if discussion is turned off\n if ($data['status'] === 0) return false;\n\n $parent_id = $cid;\n // Check for the comment and all parents if they exist and are visible.\n do {\n $tcid = $parent_id;\n\n // check if the comment still exists\n if (!isset($data['comments'][$tcid])) return false;\n // check if the comment is visible\n if ($data['comments'][$tcid]['show'] != 1) return false;\n\n $parent_id = $data['comments'][$tcid]['parent'];\n } while ($parent_id && $parent_id != $tcid);\n\n // okay, then add some additional info\n if (is_array($data['comments'][$cid]['user'])) {\n $recent['name'] = $data['comments'][$cid]['user']['name'];\n } else {\n $recent['name'] = $data['comments'][$cid]['name'];\n }\n $recent['desc'] = strip_tags($data['comments'][$cid]['xhtml']);\n $recent['anchor'] = 'comment_' . $cid;\n\n return $recent;\n }\n\n /**\n * Check if current user is member of the moderator groups\n *\n * @return bool is moderator?\n */\n public function isDiscussionModerator()\n {\n global $USERINFO, $INPUT;\n $groups = trim($this->getConf('moderatorgroups'));\n\n if (auth_ismanager()) {\n return true;\n }\n // Check if user is member of the moderator groups\n if (!empty($groups) && auth_isMember($groups, $INPUT->server->str('REMOTE_USER'), (array)$USERINFO['grps'])) {\n return true;\n }\n\n return false;\n }\n}\n"} -{"repo": "dokufreaks/plugin-discussion", "pr_number": 348, "filename": "action.php", "file_before": "\n */\n\nuse dokuwiki\\Extension\\Event;\nuse dokuwiki\\Subscriptions\\SubscriberManager;\nuse dokuwiki\\Utf8\\PhpString;\n\n/**\n * Class action_plugin_discussion\n *\n * Data format of file metadir/.comments:\n * array = [\n * 'status' => int whether comments are 0=disabled/1=open/2=closed,\n * 'number' => int number of visible comments,\n * 'title' => string|null alternative title for discussion section\n * 'comments' => [\n * ''=> [\n * 'cid' => string comment id - long random string\n * 'raw' => string comment text,\n * 'xhtml' => string rendered html,\n * 'parent' => null|string null or empty string at highest level, otherwise comment id of parent\n * 'replies' => string[] array with comment ids\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string,\n * 'address' => string,\n * 'url' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp,\n * 'modified' => int (not defined if not modified)\n * ],\n * 'show' => bool, whether shown (still be moderated, or hidden by moderator or user self)\n * ],\n * ...\n * ]\n * 'subscribers' => [\n * '' => [\n * 'hash' => string unique token,\n * 'active' => bool, true if confirmed\n * 'confirmsent' => bool, true if confirmation mail is sent\n * ],\n * ...\n * ]\n */\nclass action_plugin_discussion extends DokuWiki_Action_Plugin\n{\n\n /** @var helper_plugin_avatar */\n protected $avatar = null;\n /** @var null|string */\n protected $style = null;\n /** @var null|bool */\n protected $useAvatar = null;\n /** @var helper_plugin_discussion */\n protected $helper = null;\n\n /**\n * load helper\n */\n public function __construct()\n {\n $this->helper = plugin_load('helper', 'discussion');\n }\n\n /**\n * Register the handlers\n *\n * @param Doku_Event_Handler $controller DokuWiki's event controller object.\n */\n public function register(Doku_Event_Handler $controller)\n {\n $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions');\n $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection');\n $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']);\n $controller->register_hook('FULLTEXT_SNIPPET_CREATE', 'BEFORE', $this, 'addCommentsToIndex', ['id' => 'id', 'text' => 'text']);\n $controller->register_hook('INDEXER_VERSION_GET', 'BEFORE', $this, 'addIndexVersion', []);\n $controller->register_hook('FULLTEXT_PHRASE_MATCH', 'AFTER', $this, 'fulltextPhraseMatchInComments', []);\n $controller->register_hook('PARSER_METADATA_RENDER', 'AFTER', $this, 'updateCommentStatusFromMetadata', []);\n $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addToolbarToCommentfield', []);\n $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'modifyToolbar', []);\n $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajaxPreviewComments', []);\n $controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'addDiscussionToTOC', []);\n }\n\n /**\n * Preview Comments\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function ajaxPreviewComments(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'discussion_preview') return;\n\n $event->preventDefault();\n $event->stopPropagation();\n print p_locale_xhtml('preview');\n print '
';\n if (!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) {\n print p_locale_xhtml('denied');\n } else {\n print $this->renderComment($INPUT->post->str('comment'));\n }\n print '
';\n }\n\n /**\n * Adds a TOC item if a discussion exists\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addDiscussionToTOC(Doku_Event $event)\n {\n global $ACT;\n if ($this->hasDiscussion($title) && $event->data && $ACT != 'admin') {\n $tocitem = [\n 'hid' => 'discussion__section',\n 'title' => $title ?: $this->getLang('discussion'),\n 'type' => 'ul',\n 'level' => 1\n ];\n\n $event->data[] = $tocitem;\n }\n }\n\n /**\n * Modify Toolbar for use with discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function modifyToolbar(Doku_Event $event)\n {\n global $ACT;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n $toolbar = [];\n foreach ($event->data as $btn) {\n if ($btn['type'] == 'mediapopup') continue;\n if ($btn['type'] == 'signature') continue;\n if ($btn['type'] == 'linkwiz') continue;\n if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin\n //FIXME does nothing. Checks for '=' on toplevel, but today it are special buttons and a picker with subarray\n if (isset($btn['open']) && preg_match(\"/=+?/\", $btn['open'])) continue;\n\n $toolbar[] = $btn;\n }\n $event->data = $toolbar;\n }\n }\n\n /**\n * Dirty workaround to add a toolbar to the discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addToolbarToCommentfield(Doku_Event $event)\n {\n global $ACT;\n global $ID;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n // FIXME ugly workaround, replace this once DW the toolbar code is more flexible\n @require_once(DOKU_INC . 'inc/toolbar.php');\n ob_start();\n print 'NS = \"' . getNS($ID) . '\";'; // we have to define NS, otherwise we get get JS errors\n toolbar_JSdefines('toolbar');\n $script = ob_get_clean();\n $event->data['script'][] = ['type' => 'text/javascript', 'charset' => \"utf-8\", '_data' => $script];\n }\n }\n\n /**\n * Handles comment actions, dispatches data processing routines\n *\n * @param Doku_Event $event\n */\n public function handleCommentActions(Doku_Event $event)\n {\n global $ID, $INFO, $lang, $INPUT;\n\n // handle newthread ACTs\n if ($event->data == 'newthread') {\n // we can handle it -> prevent others\n $event->data = $this->newThread();\n }\n\n // enable captchas\n if (in_array($INPUT->str('comment'), ['add', 'save'])) {\n $this->captchaCheck();\n $this->recaptchaCheck();\n }\n\n // if we are not in show mode or someone wants to unsubscribe, that was all for now\n if ($event->data != 'show'\n && $event->data != 'discussion_unsubscribe'\n && $event->data != 'discussion_confirmsubscribe') {\n return;\n }\n\n if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') {\n if ($INPUT->has('hash')) {\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file));\n $matchedMail = '';\n foreach ($data['subscribers'] as $mail => $info) {\n // convert old style subscribers just in case\n if (!is_array($info)) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n\n if ($data['subscribers'][$mail]['hash'] == $INPUT->str('hash')) {\n $matchedMail = $mail;\n }\n }\n\n if ($matchedMail != '') {\n if ($event->data == 'discussion_unsubscribe') {\n unset($data['subscribers'][$matchedMail]);\n msg(sprintf($lang['subscr_unsubscribe_success'], $matchedMail, $ID), 1);\n } else { //$event->data == 'discussion_confirmsubscribe'\n $data['subscribers'][$matchedMail]['active'] = true;\n msg(sprintf($lang['subscr_subscribe_success'], $matchedMail, $ID), 1);\n }\n io_saveFile($file, serialize($data));\n $event->data = 'show';\n }\n\n }\n return;\n }\n\n // do the data processing for comments\n $cid = $INPUT->str('cid');\n switch ($INPUT->str('comment')) {\n case 'add':\n if (empty($INPUT->str('text'))) return; // don't add empty comments\n\n if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) {\n $comment['user']['id'] = $INPUT->server->str('REMOTE_USER');\n $comment['user']['name'] = $INFO['userinfo']['name'];\n $comment['user']['mail'] = $INFO['userinfo']['mail'];\n } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionModerator())\n || !$INPUT->server->has('REMOTE_USER')) {\n // don't add anonymous comments\n if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) {\n return;\n }\n\n if (!mail_isvalid($INPUT->str('mail'))) {\n msg($lang['regbadmail'], -1);\n return;\n } else {\n $comment['user']['id'] = ''; //prevent overlap with loggedin users, before: 'test'\n $comment['user']['name'] = hsc($INPUT->str('name'));\n $comment['user']['mail'] = hsc($INPUT->str('mail'));\n }\n }\n $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : '';\n $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : '';\n $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : '';\n $comment['date'] = ['created' => $INPUT->str('date')];\n $comment['raw'] = cleanText($INPUT->str('text'));\n $reply = $INPUT->str('reply');\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n $comment['show'] = false;\n } else {\n $comment['show'] = true;\n }\n $this->add($comment, $reply);\n break;\n\n case 'save':\n $raw = cleanText($INPUT->str('text'));\n $this->save([$cid], $raw);\n break;\n\n case 'delete':\n $this->save([$cid], '');\n break;\n\n case 'toogle':\n $this->save([$cid], '', 'toogle');\n break;\n }\n }\n\n /**\n * Main function; dispatches the visual comment actions\n *\n * @param Doku_Event $event\n */\n public function renderCommentsSection(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'show') return; // nothing to do for us\n\n $cid = $INPUT->str('cid');\n\n if (!$cid) {\n $cid = $INPUT->str('reply');\n }\n\n switch ($INPUT->str('comment')) {\n case 'edit':\n $this->showDiscussionSection(null, $cid);\n break;\n default: //'reply' or no action specified\n $this->showDiscussionSection($cid);\n break;\n }\n }\n\n /**\n * Redirects browser to given comment anchor\n *\n * @param string $cid comment id\n */\n protected function redirect($cid)\n {\n global $ID;\n global $ACT;\n\n if ($ACT !== 'show') return;\n\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n msg($this->getLang('moderation'), 1);\n @session_start();\n global $MSG;\n $_SESSION[DOKU_COOKIE]['msg'] = $MSG;\n session_write_close();\n $url = wl($ID);\n } else {\n $url = wl($ID) . '#comment_' . $cid;\n }\n\n if (function_exists('send_redirect')) {\n send_redirect($url);\n } else {\n header('Location: ' . $url);\n }\n exit();\n }\n\n /**\n * Checks config settings to enable/disable discussions\n *\n * @return bool true if enabled\n */\n public function isDiscussionEnabled()\n {\n global $ID;\n\n if ($this->getConf('excluded_ns') == '') {\n $isNamespaceExcluded = false;\n } else {\n $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status()\n $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $ns);\n }\n\n if ($this->getConf('automatic')) {\n if ($isNamespaceExcluded) {\n return false;\n } else {\n return true;\n }\n } else {\n if ($isNamespaceExcluded) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Shows all comments of the current page, if no reply or edit requested, then comment form is shown on the end\n *\n * @param null|string $reply comment id on which the user requested a reply\n * @param null|string $edit comment id which the user requested for editing\n */\n protected function showDiscussionSection($reply = null, $edit = null)\n {\n global $ID, $INFO, $INPUT;\n\n // get .comments meta file name\n $file = metaFN($ID, '.comments');\n\n if (!$INFO['exists']) return;\n if (!@file_exists($file) && !$this->isDiscussionEnabled()) return;\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('showguests')) return;\n\n // load data\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n // comments are turned off\n if (!$data['status']) {\n return;\n }\n } elseif (!@file_exists($file) && $this->isDiscussionEnabled()) {\n // set status to show the comment form\n $data['status'] = 1;\n $data['number'] = 0;\n $data['title'] = null;\n }\n\n // show discussion wrapper only on certain circumstances\n if (empty($data['comments']) || !is_array($data['comments'])) {\n $cnt = 0;\n $cids = [];\n } else {\n $cnt = count($data['comments']);\n $cids = array_keys($data['comments']);\n }\n\n $show = false;\n if ($cnt > 1 || ($cnt == 1 && $data['comments'][$cids[0]]['show'] == 1)\n || $this->getConf('allowguests')\n || $INPUT->server->has('REMOTE_USER')) {\n $show = true;\n // section title\n $title = (!empty($data['title']) ? hsc($data['title']) : $this->getLang('discussion'));\n ptln('
'); // the id value is used for visibility toggling the section\n ptln('

', 2);\n ptln($title, 4);\n ptln('

', 2);\n ptln('
', 2);\n }\n\n // now display the comments\n if (isset($data['comments'])) {\n if (!$this->getConf('usethreading')) {\n $data['comments'] = $this->flattenThreads($data['comments']);\n uasort($data['comments'], [$this, 'sortThreadsOnCreation']);\n }\n if ($this->getConf('newestfirst')) {\n $data['comments'] = array_reverse($data['comments']);\n }\n foreach ($data['comments'] as $cid => $value) {\n if ($cid == $edit) { // edit form\n $this->showCommentForm($value['raw'], 'save', $edit);\n } else {\n $this->showCommentWithReplies($cid, $data, '', $reply);\n }\n }\n }\n\n // comment form shown on the end, if no comment form of $reply or $edit is requested before\n if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) {\n $this->showCommentForm('', 'add');\n }\n\n if ($show) {\n ptln('
', 2); // level2 hfeed\n ptln('
'); // comment_wrapper\n }\n\n // check for toggle print configuration\n if ($this->getConf('visibilityButton')) {\n // print the hide/show discussion section button\n $this->showDiscussionToggleButton();\n }\n }\n\n /**\n * Remove the parent-child relation, such that the comment structure becomes flat\n *\n * @param array $comments array with all comments\n * @param null|array $cids comment ids of replies, which should be flatten\n * @return array returned array with flattened comment structure\n */\n protected function flattenThreads($comments, $cids = null)\n {\n if (is_null($cids)) {\n $cids = array_keys($comments);\n }\n\n foreach ($cids as $cid) {\n if (!empty($comments[$cid]['replies'])) {\n $rids = $comments[$cid]['replies'];\n $comments = $this->flattenThreads($comments, $rids);\n $comments[$cid]['replies'] = [];\n }\n $comments[$cid]['parent'] = '';\n }\n return $comments;\n }\n\n /**\n * Adds a new comment and then displays all comments\n *\n * @param array $comment with\n * 'raw' => string comment text,\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp\n * ]\n * 'show' => bool\n * 'subscribe' => bool\n * @param string $parent comment id of parent\n * @return bool\n */\n protected function add($comment, $parent)\n {\n global $ID, $TEXT, $INPUT;\n\n $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $comment['raw'];\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n if (!$this->getConf('allowguests')\n && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER')\n ) {\n return false; // guest comments not allowed\n }\n\n $TEXT = $originalTxt; // restore global $TEXT\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n\n // create comments file if it doesn't exist yet\n if (!@file_exists($file)) {\n $data = [\n 'status' => 1,\n 'number' => 0,\n 'title' => null\n ];\n io_saveFile($file, serialize($data));\n } else {\n $data = unserialize(io_readFile($file, false));\n // comments off or closed\n if ($data['status'] != 1) {\n return false;\n }\n }\n\n if ($comment['date']['created']) {\n $date = strtotime($comment['date']['created']);\n } else {\n $date = time();\n }\n\n if ($date == -1) {\n $date = time();\n }\n\n $cid = md5($comment['user']['id'] . $date); // create a unique id\n\n if (!isset($data['comments'][$parent]) || !is_array($data['comments'][$parent])) {\n $parent = null; // invalid parent comment\n }\n\n // render the comment\n $xhtml = $this->renderComment($comment['raw']);\n\n // fill in the new comment\n $data['comments'][$cid] = [\n 'user' => $comment['user'],\n 'date' => ['created' => $date],\n 'raw' => $comment['raw'],\n 'xhtml' => $xhtml,\n 'parent' => $parent,\n 'replies' => [],\n 'show' => $comment['show']\n ];\n\n if ($comment['subscribe']) {\n $mail = $comment['user']['mail'];\n if (isset($data['subscribers'])) {\n if (!$data['subscribers'][$mail]) {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n } else {\n // convert old style subscribers and set them active\n if (!is_array($data['subscribers'][$mail])) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n }\n } else {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n }\n }\n\n // update parent comment\n if ($parent) {\n $data['comments'][$parent]['replies'][] = $cid;\n }\n\n // update the number of comments\n $data['number']++;\n\n // notify subscribers of the page\n $data['comments'][$cid]['cid'] = $cid;\n $this->notify($data['comments'][$cid], $data['subscribers']);\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, 'cc', '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Saves the comment with the given ID and then displays all comments\n *\n * @param array|string $cids array with comment ids to save, or a single string comment id\n * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!)\n * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw\n * @return bool succeed?\n */\n public function save($cids, $raw, $act = null)\n {\n global $ID, $INPUT;\n\n if (empty($cids)) return false; // do nothing if we get no comment id\n\n if ($raw) {\n global $TEXT;\n\n $otxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $raw;\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n $TEXT = $otxt; // restore global $TEXT\n }\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file, false));\n\n if (!is_array($cids)) {\n $cids = [$cids];\n }\n foreach ($cids as $cid) {\n\n if (is_array($data['comments'][$cid]['user'])) {\n $user = $data['comments'][$cid]['user']['id'];\n $convert = false;\n } else {\n $user = $data['comments'][$cid]['user'];\n $convert = true;\n }\n\n // someone else was trying to edit our comment -> abort\n if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) {\n return false;\n }\n\n $date = time();\n\n // need to convert to new format?\n if ($convert) {\n $data['comments'][$cid]['user'] = [\n 'id' => $user,\n 'name' => $data['comments'][$cid]['name'],\n 'mail' => $data['comments'][$cid]['mail'],\n 'url' => $data['comments'][$cid]['url'],\n 'address' => $data['comments'][$cid]['address'],\n ];\n $data['comments'][$cid]['date'] = [\n 'created' => $data['comments'][$cid]['date']\n ];\n }\n\n if ($act == 'toogle') { // toogle visibility\n $now = $data['comments'][$cid]['show'];\n $data['comments'][$cid]['show'] = !$now;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');\n\n } elseif ($act == 'show') { // show comment\n $data['comments'][$cid]['show'] = true;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'sc'; // show comment\n\n } elseif ($act == 'hide') { // hide comment\n $data['comments'][$cid]['show'] = false;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'hc'; // hide comment\n\n } elseif (!$raw) { // remove the comment\n $data['comments'] = $this->removeComment($cid, $data['comments']);\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'dc'; // delete comment\n\n } else { // save changed comment\n $xhtml = $this->renderComment($raw);\n\n // now change the comment's content\n $data['comments'][$cid]['date']['modified'] = $date;\n $data['comments'][$cid]['raw'] = $raw;\n $data['comments'][$cid]['xhtml'] = $xhtml;\n\n $type = 'ec'; // edit comment\n }\n }\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, $type, '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Recursive function to remove a comment from the data array\n *\n * @param string $cid comment id to be removed\n * @param array $comments array with all comments\n * @return array returns modified array with all remaining comments\n */\n protected function removeComment($cid, $comments)\n {\n if (is_array($comments[$cid]['replies'])) {\n foreach ($comments[$cid]['replies'] as $rid) {\n $comments = $this->removeComment($rid, $comments);\n }\n }\n unset($comments[$cid]);\n return $comments;\n }\n\n /**\n * Prints an individual comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent comment id of parent\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible\n */\n protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true)\n {\n // comment was removed\n if (!isset($data['comments'][$cid])) {\n return;\n }\n $comment = $data['comments'][$cid];\n\n // corrupt datatype\n if (!is_array($comment)) {\n return;\n }\n\n // handle only replies to given parent comment\n if ($comment['parent'] != $parent) {\n return;\n }\n\n // comment hidden, only shown for moderators\n if (!$comment['show'] && !$this->helper->isDiscussionModerator()) {\n return;\n }\n\n // print the actual comment\n $this->showComment($cid, $data, $reply, $isVisible);\n // replies to this comment entry?\n $this->showReplies($cid, $data, $reply, $isVisible);\n // reply form\n $this->showReplyForm($cid, $reply);\n }\n\n /**\n * Print the comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible (grand)parent is marked as visible\n */\n protected function showComment($cid, $data, $reply, $isVisible)\n {\n global $conf, $lang, $HIGH, $INPUT;\n $comment = $data['comments'][$cid];\n\n //only moderators can arrive here if hidden\n $class = '';\n if (!$comment['show'] || !$isVisible) {\n $class = ' comment_hidden';\n }\n if($cid === $reply) {\n $class .= ' reply';\n }\n // comment head with date and user data\n ptln('
', 4);\n ptln('
', 6);\n ptln('', 8);\n $head = '';\n\n // prepare variables\n if (is_array($comment['user'])) { // new format\n $user = $comment['user']['id'];\n $name = $comment['user']['name'];\n $mail = $comment['user']['mail'];\n $url = $comment['user']['url'];\n $address = $comment['user']['address'];\n } else { // old format\n $user = $comment['user'];\n $name = $comment['name'];\n $mail = $comment['mail'];\n $url = $comment['url'];\n $address = $comment['address'];\n }\n if (is_array($comment['date'])) { // new format\n $created = $comment['date']['created'];\n $modified = $comment['date']['modified'] ?? null;\n } else { // old format\n $created = $comment['date'];\n $modified = $comment['edited'];\n }\n\n // show username or real name?\n if (!$this->getConf('userealname') && $user) {\n //not logged-in users have currently username set to '', but before 'test'\n if(substr($user, 0,4) === 'test'\n && (strpos($user, ':', 4) !== false || strpos($user, '.', 4) !== false)) {\n $showname = $name;\n } else {\n $showname = $user;\n }\n } else {\n $showname = $name;\n }\n\n // show avatar image?\n if ($this->useAvatar()) {\n $user_data['name'] = $name;\n $user_data['user'] = $user;\n $user_data['mail'] = $mail;\n $align = $lang['direction'] === 'ltr' ? 'left' : 'right';\n $avatar = $this->avatar->getXHTML($user_data, $name, $align);\n if ($avatar) {\n $head .= $avatar;\n }\n }\n\n if ($this->getConf('linkemail') && $mail) {\n $head .= $this->email($mail, $showname, 'email fn');\n } elseif ($url) {\n $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn');\n } else {\n $head .= '' . $showname . '';\n }\n\n if ($address) {\n $head .= ', ' . $address . '';\n }\n $head .= ', ' .\n '' .\n dformat($created, $conf['dformat']) . '';\n if ($modified) {\n $head .= ', ' . dformat($modified, $conf['dformat']) .\n '';\n }\n ptln($head, 8);\n ptln('
', 6); // class=\"comment_head\"\n\n // main comment content\n ptln('
useAvatar() ? $this->getWidthStyle() : '') . '>', 6);\n echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF;\n ptln('
', 6); // class=\"comment_body\"\n\n if ($isVisible) {\n ptln('
', 6);\n\n // show reply button?\n if ($data['status'] == 1 && !$reply && $comment['show']\n && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER'))\n && $this->getConf('usethreading')\n ) {\n $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true);\n }\n\n // show edit, show/hide and delete button?\n if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) {\n $this->showButton($cid, $lang['btn_secedit'], 'edit', true);\n $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));\n $this->showButton($cid, $label, 'toogle');\n $this->showButton($cid, $lang['btn_delete'], 'delete');\n }\n ptln('
', 6); // class=\"comment_buttons\"\n }\n ptln('
', 4); // class=\"hentry\"\n }\n\n /**\n * If requested by user, show comment form to write a reply\n *\n * @param string $cid current comment id\n * @param string $reply comment id on which the user requested a reply\n */\n protected function showReplyForm($cid, $reply)\n {\n if ($this->getConf('usethreading') && $reply == $cid) {\n ptln('
', 4);\n $this->showCommentForm('', 'add', $cid);\n ptln('
', 4); // class=\"comment_replies\"\n }\n }\n\n /**\n * Show the replies to the given comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible by reference\n */\n protected function showReplies($cid, &$data, $reply, &$isVisible)\n {\n $comment = $data['comments'][$cid];\n if (!count($comment['replies'])) {\n return;\n }\n ptln('
getWidthStyle() . '>', 4);\n $isVisible = ($comment['show'] && $isVisible);\n foreach ($comment['replies'] as $rid) {\n $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible);\n }\n ptln('
', 4);\n }\n\n /**\n * Is an avatar displayed?\n *\n * @return bool\n */\n protected function useAvatar()\n {\n if (is_null($this->useAvatar)) {\n $this->useAvatar = $this->getConf('useavatar')\n && ($this->avatar = $this->loadHelper('avatar', false));\n }\n return $this->useAvatar;\n }\n\n /**\n * Calculate width of indent\n *\n * @return string\n */\n protected function getWidthStyle()\n {\n global $lang;\n\n if (is_null($this->style)) {\n $side = $lang['direction'] === 'ltr' ? 'left' : 'right';\n\n if ($this->useAvatar()) {\n $this->style = ' style=\"margin-' . $side . ': ' . ($this->avatar->getConf('size') + 14) . 'px;\"';\n } else {\n $this->style = ' style=\"margin-' . $side . ': 20px;\"';\n }\n }\n return $this->style;\n }\n\n /**\n * Show the button which toggles between show/hide of the entire discussion section\n */\n protected function showDiscussionToggleButton()\n {\n ptln('
');\n ptln('getLang('toggle_display') . '\">');\n ptln('
');\n }\n\n /**\n * Outputs the comment form\n *\n * @param string $raw the existing comment text in case of edit\n * @param string $act action 'add' or 'save'\n * @param string|null $cid comment id to be responded to or null\n */\n protected function showCommentForm($raw, $act, $cid = null)\n {\n global $lang, $conf, $ID, $INPUT;\n\n // not for unregistered users when guest comments aren't allowed\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) {\n ?>\n
\n getLang('noguests'); ?>\n
\n str('text') if it's empty (for failed CAPTCHA check)\n if (!$raw && $INPUT->str('comment') == 'show') {\n $raw = $INPUT->str('text');\n }\n ?>\n\n
\n
\"\n accept-charset=\"\">\n
\n \"/>\n \n \"/>\n \n \"/>\n server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) {\n ?>\n \n
\n \n
\n
\n \n
\n getConf('urlfield')) {\n ?>\n
\n \n
\n getConf('addressfield')) {\n ?>\n
\n \n
\n getConf('adminimport') && ($this->helper->isDiscussionModerator())) {\n ?>\n
\n \n
\n \n \"/>\n \n
\n getLang('entercomment');\n echo($this->getConf('wikisyntaxok') ? \"\" : \":\");\n if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>\n\n \n getConf('wikisyntaxok')) { ?>\n
\n \n
\n \n
\n str('comment') == 'add' && empty($INPUT->str('text'))) echo ' error' ?>\"\n name=\"text\" cols=\"80\" rows=\"10\" id=\"discussion__comment_text\" tabindex=\"5\">str('text'));\n }\n ?>\n
\n\n loadHelper('captcha', false);\n if ($captcha && $captcha->isEnabled()) {\n echo $captcha->getHTML();\n }\n\n /** @var helper_plugin_recaptcha $recaptcha */\n $recaptcha = $this->loadHelper('recaptcha', false);\n if ($recaptcha && $recaptcha->isEnabled()) {\n echo $recaptcha->getHTML();\n }\n ?>\n\n \"\n title=\" [S]\" tabindex=\"7\"/>\n server->has('REMOTE_USER')\n || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers'])\n && $this->getConf('subscribe')) { ?>\n \n \n \"\n title=\" [P]\"/>\n \n \" >\n \n\n
\n
 
\n
\n \n
\n \n
\" method=\"get\" action=\"\">\n
\n \"/>\n \n \"/>\n \"/>\n \" class=\"button\" title=\"\"/>\n
\n
\n \n *\n * @author Esther Brunner \n */\n protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '')\n {\n global $conf, $INPUT;\n\n $changelog = $conf['metadir'] . '/_comments.changes';\n\n //use current time if none supplied\n if (!$date) {\n $date = time();\n }\n $remote = $INPUT->server->str('REMOTE_ADDR');\n $user = $INPUT->server->str('REMOTE_USER');\n\n $strip = [\"\\t\", \"\\n\"];\n $logline = [\n 'date' => $date,\n 'ip' => $remote,\n 'type' => str_replace($strip, '', $type),\n 'id' => $id,\n 'user' => $user,\n 'sum' => str_replace($strip, '', $summary),\n 'extra' => str_replace($strip, '', $extra)\n ];\n\n // add changelog line\n $logline = implode(\"\\t\", $logline) . \"\\n\";\n io_saveFile($changelog, $logline, true); //global changelog cache\n $this->trimRecentCommentsLog($changelog);\n\n // tell the indexer to re-index the page\n @unlink(metaFN($id, '.indexed'));\n }\n\n /**\n * Trims the recent comments cache to the last $conf['changes_days'] recent\n * changes or $conf['recent'] items, which ever is larger.\n * The trimming is only done once a day.\n *\n * @param string $changelog file path\n * @return bool\n * @author Ben Coburn \n *\n */\n protected function trimRecentCommentsLog($changelog)\n {\n global $conf;\n\n if (@file_exists($changelog)\n && (filectime($changelog) + 86400) < time()\n && !@file_exists($changelog . '_tmp')\n ) {\n\n io_lock($changelog);\n $lines = file($changelog);\n if (count($lines) < $conf['recent']) {\n // nothing to trim\n io_unlock($changelog);\n return true;\n }\n\n // presave tmp as 2nd lock\n io_saveFile($changelog . '_tmp', '');\n $trim_time = time() - $conf['recent_days'] * 86400;\n $out_lines = [];\n\n $num = count($lines);\n for ($i = 0; $i < $num; $i++) {\n $log = parseChangelogLine($lines[$i]);\n if ($log === false) continue; // discard junk\n if ($log['date'] < $trim_time) {\n $old_lines[$log['date'] . \".$i\"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions)\n } else {\n $out_lines[$log['date'] . \".$i\"] = $lines[$i]; // definitely keep these lines\n }\n }\n\n // sort the final result, it shouldn't be necessary,\n // however the extra robustness in making the changelog cache self-correcting is worth it\n ksort($out_lines);\n $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum\n if ($extra > 0) {\n ksort($old_lines);\n $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);\n }\n\n // save trimmed changelog\n io_saveFile($changelog . '_tmp', implode('', $out_lines));\n @unlink($changelog);\n if (!rename($changelog . '_tmp', $changelog)) {\n // rename failed so try another way...\n io_unlock($changelog);\n io_saveFile($changelog, implode('', $out_lines));\n @unlink($changelog . '_tmp');\n } else {\n io_unlock($changelog);\n }\n return true;\n }\n return true;\n }\n\n /**\n * Sends a notify mail on new comment\n *\n * @param array $comment data array of the new comment\n * @param array $subscribers data of the subscribers by reference\n *\n * @author Andreas Gohr \n * @author Esther Brunner \n */\n protected function notify($comment, &$subscribers)\n {\n global $conf, $ID, $INPUT, $auth;\n\n $notify_text = io_readfile($this->localfn('subscribermail'));\n $confirm_text = io_readfile($this->localfn('confirmsubscribe'));\n $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment');\n $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe');\n\n $mailer = new Mailer();\n if (!$INPUT->server->has('REMOTE_USER')) {\n $mailer->from($conf['mailfromnobody']);\n }\n\n $replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DATE' => dformat($comment['date']['created'], $conf['dformat']),\n 'NAME' => $comment['user']['name'],\n 'TEXT' => $comment['raw'],\n 'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],\n 'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n $confirm_replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n\n // send mail to notify address\n if ($conf['notify']) {\n $mailer->bcc($conf['notify']);\n $mailer->send();\n }\n\n // send email to moderators\n if ($this->getConf('moderatorsnotify')) {\n $moderatorgrpsString = trim($this->getConf('moderatorgroups'));\n if (!empty($moderatorgrpsString)) {\n // create a clean mods list\n $moderatorgroups = explode(',', $moderatorgrpsString);\n $moderatorgroups = array_map('trim', $moderatorgroups);\n $moderatorgroups = array_unique($moderatorgroups);\n $moderatorgroups = array_filter($moderatorgroups);\n // search for moderators users\n foreach ($moderatorgroups as $moderatorgroup) {\n if (!$auth->isCaseSensitive()) {\n $moderatorgroup = PhpString::strtolower($moderatorgroup);\n }\n // create a clean mailing list\n $bccs = [];\n if ($moderatorgroup[0] == '@') {\n foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) {\n if (!empty($user['mail'])) {\n $bccs[] = $user['mail'];\n }\n }\n } else {\n //it is an user\n $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup));\n if (!empty($userdata['mail'])) {\n $bccs[] = $userdata['mail'];\n }\n }\n $bccs = array_unique($bccs);\n // notify the users\n $mailer->bcc(implode(',', $bccs));\n $mailer->send();\n }\n }\n }\n\n // notify page subscribers\n if (actionOK('subscribe')) {\n $data = ['id' => $ID, 'addresslist' => '', 'self' => false];\n //FIXME default callback, needed to mentioned it again?\n Event::createAndTrigger(\n 'COMMON_NOTIFY_ADDRESSLIST', $data,\n [new SubscriberManager(), 'notifyAddresses']\n );\n\n $to = $data['addresslist'];\n if (!empty($to)) {\n $mailer->bcc($to);\n $mailer->send();\n }\n }\n\n // notify comment subscribers\n if (!empty($subscribers)) {\n\n foreach ($subscribers as $mail => $data) {\n $mailer->bcc($mail);\n if ($data['active']) {\n $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n $mailer->send();\n } elseif (!$data['confirmsent']) {\n $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_subscribe);\n $mailer->setBody($confirm_text, $confirm_replace);\n $mailer->send();\n $subscribers[$mail]['confirmsent'] = true;\n }\n }\n }\n }\n\n /**\n * Counts the number of visible comments\n *\n * @param array $data array with all comments\n * @return int\n */\n protected function countVisibleComments($data)\n {\n $number = 0;\n foreach ($data['comments'] as $comment) {\n if ($comment['parent']) continue;\n if (!$comment['show']) continue;\n\n $number++;\n $rids = $comment['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Count visible replies on the comments\n *\n * @param array $data\n * @param array $rids\n * @return int counted replies\n */\n protected function countVisibleReplies(&$data, $rids)\n {\n $number = 0;\n foreach ($rids as $rid) {\n if (!isset($data['comments'][$rid])) continue; // reply was removed\n if (!$data['comments'][$rid]['show']) continue;\n\n $number++;\n $rids = $data['comments'][$rid]['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Renders the raw comment (wiki)text to html\n *\n * @param string $raw comment text\n * @return null|string\n */\n protected function renderComment($raw)\n {\n if ($this->getConf('wikisyntaxok')) {\n // Note the warning for render_text:\n // \"very ineffecient for small pieces of data - try not to use\"\n // in dokuwiki/inc/plugin.php\n $xhtml = $this->render_text($raw);\n } else { // wiki syntax not allowed -> just encode special chars\n $xhtml = hsc(trim($raw));\n $xhtml = str_replace(\"\\n\", '
', $xhtml);\n }\n return $xhtml;\n }\n\n /**\n * Finds out whether there is a discussion section for the current page\n *\n * @param string $title set to title from metadata or empty string\n * @return bool discussion section is shown?\n */\n protected function hasDiscussion(&$title)\n {\n global $ID;\n\n $file = metaFN($ID, '.comments');\n\n if (!@file_exists($file)) {\n if ($this->isDiscussionEnabled()) {\n return true;\n } else {\n return false;\n }\n }\n\n $data = unserialize(io_readFile($file, false));\n\n $title = $data['title'] ?? '';\n\n $num = $data['number'] ?? 0;\n if (!$data['status'] || ($data['status'] == 2 && $num == 0)) {\n //disabled, or closed and no comments\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Creates a new thread page\n *\n * @return string\n */\n protected function newThread()\n {\n global $ID, $INFO, $INPUT;\n\n $ns = cleanID($INPUT->str('ns'));\n $title = str_replace(':', '', $INPUT->str('title'));\n $back = $ID;\n $ID = ($ns ? $ns . ':' : '') . cleanID($title);\n $INFO = pageinfo();\n\n // check if we are allowed to create this file\n if ($INFO['perm'] >= AUTH_CREATE) {\n\n //check if locked by anyone - if not lock for my self\n if ($INFO['locked']) {\n return 'locked';\n } else {\n lock($ID);\n }\n\n // prepare the new thread file with default stuff\n if (!@file_exists($INFO['filepath'])) {\n global $TEXT;\n\n $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title);\n if (!$TEXT) {\n $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back];\n $TEXT = $this->pageTemplate($data);\n }\n return 'preview';\n } else {\n return 'edit';\n }\n } else {\n return 'show';\n }\n }\n\n /**\n * Adapted version of pageTemplate() function\n *\n * @param array $data\n * @return string\n */\n protected function pageTemplate($data)\n {\n global $conf, $INFO, $INPUT;\n\n $id = $data['id'];\n $user = $INPUT->server->str('REMOTE_USER');\n $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt');\n\n // standard replacements\n $replace = [\n '@NS@' => $data['ns'],\n '@PAGE@' => strtr(noNS($id), '_', ' '),\n '@USER@' => $user,\n '@NAME@' => $INFO['userinfo']['name'],\n '@MAIL@' => $INFO['userinfo']['mail'],\n '@DATE@' => dformat(time(), $conf['dformat']),\n ];\n\n // additional replacements\n $replace['@BACK@'] = $data['back'];\n $replace['@TITLE@'] = $data['title'];\n\n // avatar if useavatar and avatar plugin available\n if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) {\n $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} ';\n } else {\n $replace['@AVATAR@'] = '';\n }\n\n // tag if tag plugin is available\n if (!plugin_isdisabled('tag')) {\n $replace['@TAG@'] = \"\\n\\n{{tag>}}\";\n } else {\n $replace['@TAG@'] = '';\n }\n\n // perform the replacements in tpl\n return str_replace(array_keys($replace), array_values($replace), $tpl);\n }\n\n /**\n * Checks if the CAPTCHA string submitted is valid, modifies action if needed\n */\n protected function captchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_captcha $captcha */\n if (!$captcha = $this->loadHelper('captcha', false)) {\n // CAPTCHA is disabled or not available\n return;\n }\n\n if ($captcha->isEnabled() && !$captcha->check()) {\n if ($INPUT->str('comment') == 'save') {\n $INPUT->set('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->set('comment', 'show');\n }\n }\n }\n\n /**\n * checks if the submitted reCAPTCHA string is valid, modifies action if needed\n *\n * @author Adrian Schlegel \n */\n protected function recaptchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_recaptcha $recaptcha */\n if (!$recaptcha = plugin_load('helper', 'recaptcha'))\n return; // reCAPTCHA is disabled or not available\n\n // do nothing if logged in user and no reCAPTCHA required\n if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return;\n\n $response = $recaptcha->check();\n if (!$response->is_valid) {\n msg($recaptcha->getLang('testfailed'), -1);\n if ($INPUT->str('comment') == 'save') {\n $INPUT->str('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->str('comment', 'show');\n }\n }\n }\n\n /**\n * Add discussion plugin version to the indexer version\n * This means that all pages will be indexed again in order to add the comments\n * to the index whenever there has been a change that concerns the index content.\n *\n * @param Doku_Event $event\n */\n public function addIndexVersion(Doku_Event $event)\n {\n $event->data['discussion'] = '0.1';\n }\n\n /**\n * Adds the comments to the index\n *\n * @param Doku_Event $event\n * @param array $param with\n * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event\n * 'text' => string 'body'/'text'\n */\n public function addCommentsToIndex(Doku_Event $event, $param)\n {\n // get .comments meta file name\n $file = metaFN($event->data[$param['id']], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to index\n if (!$data['status'] || $data['number'] == 0) return;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $key => $value) {\n $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data);\n }\n }\n }\n\n /**\n * Checks if the phrase occurs in the comments and return event result true if matching\n *\n * @param Doku_Event $event\n */\n public function fulltextPhraseMatchInComments(Doku_Event $event)\n {\n if ($event->result === true) return;\n\n // get .comments meta file name\n $file = metaFN($event->data['id'], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to match\n if (!$data['status'] || $data['number'] == 0) return;\n\n $matched = false;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $cid => $value) {\n $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data);\n if ($matched) break;\n }\n }\n\n if ($matched) {\n $event->result = true;\n }\n }\n\n /**\n * Match the phrase in the comment and its replies\n *\n * @param string $phrase phrase to search\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return bool if match true, otherwise false\n */\n protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '')\n {\n if (!isset($data['comments'][$cid])) return false; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return false; // corrupt datatype\n if ($comment['parent'] != $parent) return false; // reply to an other comment\n if (!$comment['show']) return false; // hidden comment\n\n $text = PhpString::strtolower($comment['raw']);\n if (strpos($text, $phrase) !== false) {\n return true;\n }\n\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Saves the current comment status and title from metadata into the .comments file\n *\n * @param Doku_Event $event\n */\n public function updateCommentStatusFromMetadata(Doku_Event $event)\n {\n global $ID;\n\n $meta = $event->data['current'];\n\n $file = metaFN($ID, '.comments');\n $configurationStatus = ($this->isDiscussionEnabled() ? 1 : 0); // 0=off, 1=enabled\n $title = null;\n if (isset($meta['plugin_discussion'])) {\n $status = (int) $meta['plugin_discussion']['status']; // 0=off, 1=enabled or 2=closed\n $title = $meta['plugin_discussion']['title'];\n\n // do we have metadata that differs from general config?\n $saveNeededFromMetadata = $configurationStatus !== $status || ($status > 0 && $title);\n } else {\n $status = $configurationStatus;\n $saveNeededFromMetadata = false;\n }\n\n // if .comment file exists always update it with latest status\n if ($saveNeededFromMetadata || file_exists($file)) {\n\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n }\n\n if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {\n //title can be only set from metadata\n $data['title'] = $title;\n $data['status'] = $status;\n if (!isset($data['number'])) {\n $data['number'] = 0;\n }\n io_saveFile($file, serialize($data));\n }\n }\n }\n\n /**\n * Return words of a given comment and its replies, suitable to be added to the index\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return string\n */\n protected function addCommentWords($cid, &$data, $parent = '')\n {\n\n if (!isset($data['comments'][$cid])) return ''; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return ''; // corrupt datatype\n if ($comment['parent'] != $parent) return ''; // reply to an other comment\n if (!$comment['show']) return ''; // hidden comment\n\n $text = $comment['raw']; // we only add the raw comment text\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n $text .= $this->addCommentWords($rid, $data, $cid);\n }\n }\n return ' ' . $text;\n }\n\n /**\n * Only allow http(s) URLs and append http:// to URLs if needed\n *\n * @param string $url\n * @return string\n */\n protected function checkURL($url)\n {\n if (preg_match(\"#^http://|^https://#\", $url)) {\n return hsc($url);\n } elseif (substr($url, 0, 4) == 'www.') {\n return hsc('https://' . $url);\n } else {\n return '';\n }\n }\n\n /**\n * Sort threads\n *\n * @param array $a array with comment properties\n * @param array $b array with comment properties\n * @return int\n */\n function sortThreadsOnCreation($a, $b)\n {\n if (is_array($a['date'])) {\n // new format\n $createdA = $a['date']['created'];\n } else {\n // old format\n $createdA = $a['date'];\n }\n\n if (is_array($b['date'])) {\n // new format\n $createdB = $b['date']['created'];\n } else {\n // old format\n $createdB = $b['date'];\n }\n\n if ($createdA == $createdB) {\n return 0;\n } else {\n return ($createdA < $createdB) ? -1 : 1;\n }\n }\n\n}\n\n\n", "file_after": "\n */\n\nuse dokuwiki\\Extension\\Event;\nuse dokuwiki\\Subscriptions\\SubscriberManager;\nuse dokuwiki\\Utf8\\PhpString;\n\n/**\n * Class action_plugin_discussion\n *\n * Data format of file metadir/.comments:\n * array = [\n * 'status' => int whether comments are 0=disabled/1=open/2=closed,\n * 'number' => int number of visible comments,\n * 'title' => string|null alternative title for discussion section\n * 'comments' => [\n * ''=> [\n * 'cid' => string comment id - long random string\n * 'raw' => string comment text,\n * 'xhtml' => string rendered html,\n * 'parent' => null|string null or empty string at highest level, otherwise comment id of parent\n * 'replies' => string[] array with comment ids\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string,\n * 'address' => string,\n * 'url' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp,\n * 'modified' => int (not defined if not modified)\n * ],\n * 'show' => bool, whether shown (still be moderated, or hidden by moderator or user self)\n * ],\n * ...\n * ]\n * 'subscribers' => [\n * '' => [\n * 'hash' => string unique token,\n * 'active' => bool, true if confirmed\n * 'confirmsent' => bool, true if confirmation mail is sent\n * ],\n * ...\n * ]\n */\nclass action_plugin_discussion extends DokuWiki_Action_Plugin\n{\n\n /** @var helper_plugin_avatar */\n protected $avatar = null;\n /** @var null|string */\n protected $style = null;\n /** @var null|bool */\n protected $useAvatar = null;\n /** @var helper_plugin_discussion */\n protected $helper = null;\n\n /**\n * load helper\n */\n public function __construct()\n {\n $this->helper = plugin_load('helper', 'discussion');\n }\n\n /**\n * Register the handlers\n *\n * @param Doku_Event_Handler $controller DokuWiki's event controller object.\n */\n public function register(Doku_Event_Handler $controller)\n {\n $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions');\n $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection');\n $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']);\n $controller->register_hook('FULLTEXT_SNIPPET_CREATE', 'BEFORE', $this, 'addCommentsToIndex', ['id' => 'id', 'text' => 'text']);\n $controller->register_hook('INDEXER_VERSION_GET', 'BEFORE', $this, 'addIndexVersion', []);\n $controller->register_hook('FULLTEXT_PHRASE_MATCH', 'AFTER', $this, 'fulltextPhraseMatchInComments', []);\n $controller->register_hook('PARSER_METADATA_RENDER', 'AFTER', $this, 'updateCommentStatusFromMetadata', []);\n $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addToolbarToCommentfield', []);\n $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'modifyToolbar', []);\n $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajaxPreviewComments', []);\n $controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'addDiscussionToTOC', []);\n }\n\n /**\n * Preview Comments\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function ajaxPreviewComments(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'discussion_preview') return;\n\n $event->preventDefault();\n $event->stopPropagation();\n print p_locale_xhtml('preview');\n print '
';\n if (!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) {\n print p_locale_xhtml('denied');\n } else {\n print $this->renderComment($INPUT->post->str('comment'));\n }\n print '
';\n }\n\n /**\n * Adds a TOC item if a discussion exists\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addDiscussionToTOC(Doku_Event $event)\n {\n global $ACT;\n if ($this->hasDiscussion($title) && $event->data && $ACT != 'admin') {\n $tocitem = [\n 'hid' => 'discussion__section',\n 'title' => $title ?: $this->getLang('discussion'),\n 'type' => 'ul',\n 'level' => 1\n ];\n\n $event->data[] = $tocitem;\n }\n }\n\n /**\n * Modify Toolbar for use with discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function modifyToolbar(Doku_Event $event)\n {\n global $ACT;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n $toolbar = [];\n foreach ($event->data as $btn) {\n if ($btn['type'] == 'mediapopup') continue;\n if ($btn['type'] == 'signature') continue;\n if ($btn['type'] == 'linkwiz') continue;\n if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin\n //FIXME does nothing. Checks for '=' on toplevel, but today it are special buttons and a picker with subarray\n if (isset($btn['open']) && preg_match(\"/=+?/\", $btn['open'])) continue;\n\n $toolbar[] = $btn;\n }\n $event->data = $toolbar;\n }\n }\n\n /**\n * Dirty workaround to add a toolbar to the discussion plugin\n *\n * @param Doku_Event $event\n * @author Michael Klier \n */\n public function addToolbarToCommentfield(Doku_Event $event)\n {\n global $ACT;\n global $ID;\n if ($ACT != 'show') return;\n\n if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) {\n // FIXME ugly workaround, replace this once DW the toolbar code is more flexible\n @require_once(DOKU_INC . 'inc/toolbar.php');\n ob_start();\n print 'NS = \"' . getNS($ID) . '\";'; // we have to define NS, otherwise we get get JS errors\n toolbar_JSdefines('toolbar');\n $script = ob_get_clean();\n $event->data['script'][] = ['type' => 'text/javascript', 'charset' => \"utf-8\", '_data' => $script];\n }\n }\n\n /**\n * Handles comment actions, dispatches data processing routines\n *\n * @param Doku_Event $event\n */\n public function handleCommentActions(Doku_Event $event)\n {\n global $ID, $INFO, $lang, $INPUT;\n\n // handle newthread ACTs\n if ($event->data == 'newthread') {\n // we can handle it -> prevent others\n $event->data = $this->newThread();\n }\n\n // enable captchas\n if (in_array($INPUT->str('comment'), ['add', 'save'])) {\n $this->captchaCheck();\n $this->recaptchaCheck();\n }\n\n // if we are not in show mode or someone wants to unsubscribe, that was all for now\n if ($event->data != 'show'\n && $event->data != 'discussion_unsubscribe'\n && $event->data != 'discussion_confirmsubscribe') {\n return;\n }\n\n if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') {\n if ($INPUT->has('hash')) {\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file));\n $matchedMail = '';\n foreach ($data['subscribers'] as $mail => $info) {\n // convert old style subscribers just in case\n if (!is_array($info)) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n\n if ($data['subscribers'][$mail]['hash'] == $INPUT->str('hash')) {\n $matchedMail = $mail;\n }\n }\n\n if ($matchedMail != '') {\n if ($event->data == 'discussion_unsubscribe') {\n unset($data['subscribers'][$matchedMail]);\n msg(sprintf($lang['subscr_unsubscribe_success'], $matchedMail, $ID), 1);\n } else { //$event->data == 'discussion_confirmsubscribe'\n $data['subscribers'][$matchedMail]['active'] = true;\n msg(sprintf($lang['subscr_subscribe_success'], $matchedMail, $ID), 1);\n }\n io_saveFile($file, serialize($data));\n $event->data = 'show';\n }\n\n }\n return;\n }\n\n // do the data processing for comments\n $cid = $INPUT->str('cid');\n switch ($INPUT->str('comment')) {\n case 'add':\n if (empty($INPUT->str('text'))) return; // don't add empty comments\n\n if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) {\n $comment['user']['id'] = $INPUT->server->str('REMOTE_USER');\n $comment['user']['name'] = $INFO['userinfo']['name'];\n $comment['user']['mail'] = $INFO['userinfo']['mail'];\n } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionModerator())\n || !$INPUT->server->has('REMOTE_USER')) {\n // don't add anonymous comments\n if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) {\n return;\n }\n\n if (!mail_isvalid($INPUT->str('mail'))) {\n msg($lang['regbadmail'], -1);\n return;\n } else {\n $comment['user']['id'] = ''; //prevent overlap with loggedin users, before: 'test'\n $comment['user']['name'] = hsc($INPUT->str('name'));\n $comment['user']['mail'] = hsc($INPUT->str('mail'));\n }\n }\n $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : '';\n $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : '';\n $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : '';\n $comment['date'] = ['created' => $INPUT->str('date')];\n $comment['raw'] = cleanText($INPUT->str('text'));\n $reply = $INPUT->str('reply');\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n $comment['show'] = false;\n } else {\n $comment['show'] = true;\n }\n $this->add($comment, $reply);\n break;\n\n case 'save':\n $raw = cleanText($INPUT->str('text'));\n $this->save([$cid], $raw);\n break;\n\n case 'delete':\n $this->save([$cid], '');\n break;\n\n case 'toogle':\n $this->save([$cid], '', 'toogle');\n break;\n }\n }\n\n /**\n * Main function; dispatches the visual comment actions\n *\n * @param Doku_Event $event\n */\n public function renderCommentsSection(Doku_Event $event)\n {\n global $INPUT;\n if ($event->data != 'show') return; // nothing to do for us\n\n $cid = $INPUT->str('cid');\n\n if (!$cid) {\n $cid = $INPUT->str('reply');\n }\n\n switch ($INPUT->str('comment')) {\n case 'edit':\n $this->showDiscussionSection(null, $cid);\n break;\n default: //'reply' or no action specified\n $this->showDiscussionSection($cid);\n break;\n }\n }\n\n /**\n * Redirects browser to given comment anchor\n *\n * @param string $cid comment id\n */\n protected function redirect($cid)\n {\n global $ID;\n global $ACT;\n\n if ($ACT !== 'show') return;\n\n if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) {\n msg($this->getLang('moderation'), 1);\n @session_start();\n global $MSG;\n $_SESSION[DOKU_COOKIE]['msg'] = $MSG;\n session_write_close();\n $url = wl($ID);\n } else {\n $url = wl($ID) . '#comment_' . $cid;\n }\n\n if (function_exists('send_redirect')) {\n send_redirect($url);\n } else {\n header('Location: ' . $url);\n }\n exit();\n }\n\n /**\n * Checks config settings to enable/disable discussions\n *\n * @return bool true if enabled\n */\n public function isDiscussionEnabled()\n {\n global $ID;\n\n if ($this->getConf('excluded_ns') == '') {\n $isNamespaceExcluded = false;\n } else {\n $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status()\n $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $ns);\n }\n\n if ($this->getConf('automatic')) {\n if ($isNamespaceExcluded) {\n return false;\n } else {\n return true;\n }\n } else {\n if ($isNamespaceExcluded) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n /**\n * Shows all comments of the current page, if no reply or edit requested, then comment form is shown on the end\n *\n * @param null|string $reply comment id on which the user requested a reply\n * @param null|string $edit comment id which the user requested for editing\n */\n protected function showDiscussionSection($reply = null, $edit = null)\n {\n global $ID, $INFO, $INPUT;\n\n // get .comments meta file name\n $file = metaFN($ID, '.comments');\n\n if (!$INFO['exists']) return;\n if (!@file_exists($file) && !$this->isDiscussionEnabled()) return;\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('showguests')) return;\n\n // load data\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n // comments are turned off\n if (!$data['status']) {\n return;\n }\n } elseif (!@file_exists($file) && $this->isDiscussionEnabled()) {\n // set status to show the comment form\n $data['status'] = 1;\n $data['number'] = 0;\n $data['title'] = null;\n }\n\n // show discussion wrapper only on certain circumstances\n if (empty($data['comments']) || !is_array($data['comments'])) {\n $cnt = 0;\n $cids = [];\n } else {\n $cnt = count($data['comments']);\n $cids = array_keys($data['comments']);\n }\n\n $show = false;\n if ($cnt > 1 || ($cnt == 1 && $data['comments'][$cids[0]]['show'] == 1)\n || $this->getConf('allowguests')\n || $INPUT->server->has('REMOTE_USER')) {\n $show = true;\n // section title\n $title = (!empty($data['title']) ? hsc($data['title']) : $this->getLang('discussion'));\n ptln('
'); // the id value is used for visibility toggling the section\n ptln('

', 2);\n ptln($title, 4);\n ptln('

', 2);\n ptln('
', 2);\n }\n\n // now display the comments\n if (isset($data['comments'])) {\n if (!$this->getConf('usethreading')) {\n $data['comments'] = $this->flattenThreads($data['comments']);\n uasort($data['comments'], [$this, 'sortThreadsOnCreation']);\n }\n if ($this->getConf('newestfirst')) {\n $data['comments'] = array_reverse($data['comments']);\n }\n foreach ($data['comments'] as $cid => $value) {\n if ($cid == $edit) { // edit form\n $this->showCommentForm($value['raw'], 'save', $edit);\n } else {\n $this->showCommentWithReplies($cid, $data, '', $reply);\n }\n }\n }\n\n // comment form shown on the end, if no comment form of $reply or $edit is requested before\n if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) {\n $this->showCommentForm('', 'add');\n }\n\n if ($show) {\n ptln('
', 2); // level2 hfeed\n ptln('
'); // comment_wrapper\n }\n\n // check for toggle print configuration\n if ($this->getConf('visibilityButton')) {\n // print the hide/show discussion section button\n $this->showDiscussionToggleButton();\n }\n }\n\n /**\n * Remove the parent-child relation, such that the comment structure becomes flat\n *\n * @param array $comments array with all comments\n * @param null|array $cids comment ids of replies, which should be flatten\n * @return array returned array with flattened comment structure\n */\n protected function flattenThreads($comments, $cids = null)\n {\n if (is_null($cids)) {\n $cids = array_keys($comments);\n }\n\n foreach ($cids as $cid) {\n if (!empty($comments[$cid]['replies'])) {\n $rids = $comments[$cid]['replies'];\n $comments = $this->flattenThreads($comments, $rids);\n $comments[$cid]['replies'] = [];\n }\n $comments[$cid]['parent'] = '';\n }\n return $comments;\n }\n\n /**\n * Adds a new comment and then displays all comments\n *\n * @param array $comment with\n * 'raw' => string comment text,\n * 'user' => [\n * 'id' => string,\n * 'name' => string,\n * 'mail' => string\n * ],\n * 'date' => [\n * 'created' => int timestamp\n * ]\n * 'show' => bool\n * 'subscribe' => bool\n * @param string $parent comment id of parent\n * @return bool\n */\n protected function add($comment, $parent)\n {\n global $ID, $TEXT, $INPUT;\n\n $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $comment['raw'];\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n if (!$this->getConf('allowguests')\n && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER')\n ) {\n return false; // guest comments not allowed\n }\n\n $TEXT = $originalTxt; // restore global $TEXT\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n\n // create comments file if it doesn't exist yet\n if (!@file_exists($file)) {\n $data = [\n 'status' => 1,\n 'number' => 0,\n 'title' => null\n ];\n io_saveFile($file, serialize($data));\n } else {\n $data = unserialize(io_readFile($file, false));\n // comments off or closed\n if ($data['status'] != 1) {\n return false;\n }\n }\n\n if ($comment['date']['created']) {\n $date = strtotime($comment['date']['created']);\n } else {\n $date = time();\n }\n\n if ($date == -1) {\n $date = time();\n }\n\n $cid = md5($comment['user']['id'] . $date); // create a unique id\n\n if (!isset($data['comments'][$parent]) || !is_array($data['comments'][$parent])) {\n $parent = null; // invalid parent comment\n }\n\n // render the comment\n $xhtml = $this->renderComment($comment['raw']);\n\n // fill in the new comment\n $data['comments'][$cid] = [\n 'user' => $comment['user'],\n 'date' => ['created' => $date],\n 'raw' => $comment['raw'],\n 'xhtml' => $xhtml,\n 'parent' => $parent,\n 'replies' => [],\n 'show' => $comment['show']\n ];\n\n if ($comment['subscribe']) {\n $mail = $comment['user']['mail'];\n if (isset($data['subscribers'])) {\n if (!$data['subscribers'][$mail]) {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n } else {\n // convert old style subscribers and set them active\n if (!is_array($data['subscribers'][$mail])) {\n $hash = $data['subscribers'][$mail];\n $data['subscribers'][$mail]['hash'] = $hash;\n $data['subscribers'][$mail]['active'] = true;\n $data['subscribers'][$mail]['confirmsent'] = true;\n }\n }\n } else {\n $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());\n $data['subscribers'][$mail]['active'] = false;\n $data['subscribers'][$mail]['confirmsent'] = false;\n }\n }\n\n // update parent comment\n if ($parent) {\n $data['comments'][$parent]['replies'][] = $cid;\n }\n\n // update the number of comments\n $data['number']++;\n\n // notify subscribers of the page\n $data['comments'][$cid]['cid'] = $cid;\n $this->notify($data['comments'][$cid], $data['subscribers']);\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, 'cc', '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Saves the comment with the given ID and then displays all comments\n *\n * @param array|string $cids array with comment ids to save, or a single string comment id\n * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!)\n * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw\n * @return bool succeed?\n */\n public function save($cids, $raw, $act = null)\n {\n global $ID, $INPUT;\n\n if (empty($cids)) return false; // do nothing if we get no comment id\n\n if ($raw) {\n global $TEXT;\n\n $otxt = $TEXT; // set $TEXT to comment text for wordblock check\n $TEXT = $raw;\n\n // spamcheck against the DokuWiki blacklist\n if (checkwordblock()) {\n msg($this->getLang('wordblock'), -1);\n return false;\n }\n\n $TEXT = $otxt; // restore global $TEXT\n }\n\n // get discussion meta file name\n $file = metaFN($ID, '.comments');\n $data = unserialize(io_readFile($file, false));\n\n if (!is_array($cids)) {\n $cids = [$cids];\n }\n foreach ($cids as $cid) {\n\n if (is_array($data['comments'][$cid]['user'])) {\n $user = $data['comments'][$cid]['user']['id'];\n $convert = false;\n } else {\n $user = $data['comments'][$cid]['user'];\n $convert = true;\n }\n\n // someone else was trying to edit our comment -> abort\n if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) {\n return false;\n }\n\n $date = time();\n\n // need to convert to new format?\n if ($convert) {\n $data['comments'][$cid]['user'] = [\n 'id' => $user,\n 'name' => $data['comments'][$cid]['name'],\n 'mail' => $data['comments'][$cid]['mail'],\n 'url' => $data['comments'][$cid]['url'],\n 'address' => $data['comments'][$cid]['address'],\n ];\n $data['comments'][$cid]['date'] = [\n 'created' => $data['comments'][$cid]['date']\n ];\n }\n\n if ($act == 'toogle') { // toogle visibility\n $now = $data['comments'][$cid]['show'];\n $data['comments'][$cid]['show'] = !$now;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');\n\n } elseif ($act == 'show') { // show comment\n $data['comments'][$cid]['show'] = true;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'sc'; // show comment\n\n } elseif ($act == 'hide') { // hide comment\n $data['comments'][$cid]['show'] = false;\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'hc'; // hide comment\n\n } elseif (!$raw) { // remove the comment\n $data['comments'] = $this->removeComment($cid, $data['comments']);\n $data['number'] = $this->countVisibleComments($data);\n\n $type = 'dc'; // delete comment\n\n } else { // save changed comment\n $xhtml = $this->renderComment($raw);\n\n // now change the comment's content\n $data['comments'][$cid]['date']['modified'] = $date;\n $data['comments'][$cid]['raw'] = $raw;\n $data['comments'][$cid]['xhtml'] = $xhtml;\n\n $type = 'ec'; // edit comment\n }\n }\n\n // save the comment metadata file\n io_saveFile($file, serialize($data));\n $this->addLogEntry($date, $ID, $type, '', $cid);\n\n $this->redirect($cid);\n return true;\n }\n\n /**\n * Recursive function to remove a comment from the data array\n *\n * @param string $cid comment id to be removed\n * @param array $comments array with all comments\n * @return array returns modified array with all remaining comments\n */\n protected function removeComment($cid, $comments)\n {\n if (is_array($comments[$cid]['replies'])) {\n foreach ($comments[$cid]['replies'] as $rid) {\n $comments = $this->removeComment($rid, $comments);\n }\n }\n unset($comments[$cid]);\n return $comments;\n }\n\n /**\n * Prints an individual comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent comment id of parent\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible\n */\n protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true)\n {\n // comment was removed\n if (!isset($data['comments'][$cid])) {\n return;\n }\n $comment = $data['comments'][$cid];\n\n // corrupt datatype\n if (!is_array($comment)) {\n return;\n }\n\n // handle only replies to given parent comment\n if ($comment['parent'] != $parent) {\n return;\n }\n\n // comment hidden, only shown for moderators\n if (!$comment['show'] && !$this->helper->isDiscussionModerator()) {\n return;\n }\n\n // print the actual comment\n $this->showComment($cid, $data, $reply, $isVisible);\n // replies to this comment entry?\n $this->showReplies($cid, $data, $reply, $isVisible);\n // reply form\n $this->showReplyForm($cid, $reply);\n }\n\n /**\n * Print the comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible (grand)parent is marked as visible\n */\n protected function showComment($cid, $data, $reply, $isVisible)\n {\n global $conf, $lang, $HIGH, $INPUT;\n $comment = $data['comments'][$cid];\n\n //only moderators can arrive here if hidden\n $class = '';\n if (!$comment['show'] || !$isVisible) {\n $class = ' comment_hidden';\n }\n if($cid === $reply) {\n $class .= ' reply';\n }\n // comment head with date and user data\n ptln('
', 4);\n ptln('
', 6);\n ptln('', 8);\n $head = '';\n\n // prepare variables\n if (is_array($comment['user'])) { // new format\n $user = $comment['user']['id'];\n $name = $comment['user']['name'];\n $mail = $comment['user']['mail'];\n $url = $comment['user']['url'];\n $address = $comment['user']['address'];\n } else { // old format\n $user = $comment['user'];\n $name = $comment['name'];\n $mail = $comment['mail'];\n $url = $comment['url'];\n $address = $comment['address'];\n }\n if (is_array($comment['date'])) { // new format\n $created = $comment['date']['created'];\n $modified = $comment['date']['modified'] ?? null;\n } else { // old format\n $created = $comment['date'];\n $modified = $comment['edited'];\n }\n\n // show username or real name?\n if (!$this->getConf('userealname') && $user) {\n //not logged-in users have currently username set to '', but before 'test'\n if(substr($user, 0,4) === 'test'\n && (strpos($user, ':', 4) !== false || strpos($user, '.', 4) !== false)) {\n $showname = $name;\n } else {\n $showname = $user;\n }\n } else {\n $showname = $name;\n }\n\n // show avatar image?\n if ($this->useAvatar()) {\n $user_data['name'] = $name;\n $user_data['user'] = $user;\n $user_data['mail'] = $mail;\n $align = $lang['direction'] === 'ltr' ? 'left' : 'right';\n $avatar = $this->avatar->getXHTML($user_data, $name, $align);\n if ($avatar) {\n $head .= $avatar;\n }\n }\n\n if ($this->getConf('linkemail') && $mail) {\n $head .= $this->email($mail, $showname, 'email fn');\n } elseif ($url) {\n $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn');\n } else {\n $head .= '' . $showname . '';\n }\n\n if ($address) {\n $head .= ', ' . $address . '';\n }\n $head .= ', ' .\n '' .\n dformat($created, $conf['dformat']) . '';\n if ($modified) {\n $head .= ', ' . dformat($modified, $conf['dformat']) .\n '';\n }\n ptln($head, 8);\n ptln('
', 6); // class=\"comment_head\"\n\n // main comment content\n ptln('
useAvatar() ? $this->getWidthStyle() : '') . '>', 6);\n echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF;\n ptln('
', 6); // class=\"comment_body\"\n\n if ($isVisible) {\n ptln('
', 6);\n\n // show reply button?\n if ($data['status'] == 1 && !$reply && $comment['show']\n && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER'))\n && $this->getConf('usethreading')\n ) {\n $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true);\n }\n\n // show edit, show/hide and delete button?\n if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) {\n $this->showButton($cid, $lang['btn_secedit'], 'edit', true);\n $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));\n $this->showButton($cid, $label, 'toogle');\n $this->showButton($cid, $lang['btn_delete'], 'delete');\n }\n ptln('
', 6); // class=\"comment_buttons\"\n }\n ptln('
', 4); // class=\"hentry\"\n }\n\n /**\n * If requested by user, show comment form to write a reply\n *\n * @param string $cid current comment id\n * @param string $reply comment id on which the user requested a reply\n */\n protected function showReplyForm($cid, $reply)\n {\n if ($this->getConf('usethreading') && $reply == $cid) {\n ptln('
', 4);\n $this->showCommentForm('', 'add', $cid);\n ptln('
', 4); // class=\"comment_replies\"\n }\n }\n\n /**\n * Show the replies to the given comment\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $reply comment id on which the user requested a reply\n * @param bool $isVisible is marked as visible by reference\n */\n protected function showReplies($cid, &$data, $reply, &$isVisible)\n {\n $comment = $data['comments'][$cid];\n if (!empty($comment['replies'])) {\n return;\n }\n ptln('
getWidthStyle() . '>', 4);\n $isVisible = ($comment['show'] && $isVisible);\n foreach ($comment['replies'] as $rid) {\n $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible);\n }\n ptln('
', 4);\n }\n\n /**\n * Is an avatar displayed?\n *\n * @return bool\n */\n protected function useAvatar()\n {\n if (is_null($this->useAvatar)) {\n $this->useAvatar = $this->getConf('useavatar')\n && ($this->avatar = $this->loadHelper('avatar', false));\n }\n return $this->useAvatar;\n }\n\n /**\n * Calculate width of indent\n *\n * @return string\n */\n protected function getWidthStyle()\n {\n global $lang;\n\n if (is_null($this->style)) {\n $side = $lang['direction'] === 'ltr' ? 'left' : 'right';\n\n if ($this->useAvatar()) {\n $this->style = ' style=\"margin-' . $side . ': ' . ($this->avatar->getConf('size') + 14) . 'px;\"';\n } else {\n $this->style = ' style=\"margin-' . $side . ': 20px;\"';\n }\n }\n return $this->style;\n }\n\n /**\n * Show the button which toggles between show/hide of the entire discussion section\n */\n protected function showDiscussionToggleButton()\n {\n ptln('
');\n ptln('getLang('toggle_display') . '\">');\n ptln('
');\n }\n\n /**\n * Outputs the comment form\n *\n * @param string $raw the existing comment text in case of edit\n * @param string $act action 'add' or 'save'\n * @param string|null $cid comment id to be responded to or null\n */\n protected function showCommentForm($raw, $act, $cid = null)\n {\n global $lang, $conf, $ID, $INPUT;\n\n // not for unregistered users when guest comments aren't allowed\n if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) {\n ?>\n
\n getLang('noguests'); ?>\n
\n str('text') if it's empty (for failed CAPTCHA check)\n if (!$raw && $INPUT->str('comment') == 'show') {\n $raw = $INPUT->str('text');\n }\n ?>\n\n
\n
\"\n accept-charset=\"\">\n
\n \"/>\n \n \"/>\n \n \"/>\n server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) {\n ?>\n \n
\n \n
\n
\n \n
\n getConf('urlfield')) {\n ?>\n
\n \n
\n getConf('addressfield')) {\n ?>\n
\n \n
\n getConf('adminimport') && ($this->helper->isDiscussionModerator())) {\n ?>\n
\n \n
\n \n \"/>\n \n
\n getLang('entercomment');\n echo($this->getConf('wikisyntaxok') ? \"\" : \":\");\n if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>\n\n \n getConf('wikisyntaxok')) { ?>\n
\n \n
\n \n
\n str('comment') == 'add' && empty($INPUT->str('text'))) echo ' error' ?>\"\n name=\"text\" cols=\"80\" rows=\"10\" id=\"discussion__comment_text\" tabindex=\"5\">str('text'));\n }\n ?>\n
\n\n loadHelper('captcha', false);\n if ($captcha && $captcha->isEnabled()) {\n echo $captcha->getHTML();\n }\n\n /** @var helper_plugin_recaptcha $recaptcha */\n $recaptcha = $this->loadHelper('recaptcha', false);\n if ($recaptcha && $recaptcha->isEnabled()) {\n echo $recaptcha->getHTML();\n }\n ?>\n\n \"\n title=\" [S]\" tabindex=\"7\"/>\n server->has('REMOTE_USER')\n || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers'])\n && $this->getConf('subscribe')) { ?>\n \n \n \"\n title=\" [P]\"/>\n \n \" >\n \n\n
\n
 
\n
\n \n
\n \n
\" method=\"get\" action=\"\">\n
\n \"/>\n \n \"/>\n \"/>\n \" class=\"button\" title=\"\"/>\n
\n
\n \n *\n * @author Esther Brunner \n */\n protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '')\n {\n global $conf, $INPUT;\n\n $changelog = $conf['metadir'] . '/_comments.changes';\n\n //use current time if none supplied\n if (!$date) {\n $date = time();\n }\n $remote = $INPUT->server->str('REMOTE_ADDR');\n $user = $INPUT->server->str('REMOTE_USER');\n\n $strip = [\"\\t\", \"\\n\"];\n $logline = [\n 'date' => $date,\n 'ip' => $remote,\n 'type' => str_replace($strip, '', $type),\n 'id' => $id,\n 'user' => $user,\n 'sum' => str_replace($strip, '', $summary),\n 'extra' => str_replace($strip, '', $extra)\n ];\n\n // add changelog line\n $logline = implode(\"\\t\", $logline) . \"\\n\";\n io_saveFile($changelog, $logline, true); //global changelog cache\n $this->trimRecentCommentsLog($changelog);\n\n // tell the indexer to re-index the page\n @unlink(metaFN($id, '.indexed'));\n }\n\n /**\n * Trims the recent comments cache to the last $conf['changes_days'] recent\n * changes or $conf['recent'] items, which ever is larger.\n * The trimming is only done once a day.\n *\n * @param string $changelog file path\n * @return bool\n * @author Ben Coburn \n *\n */\n protected function trimRecentCommentsLog($changelog)\n {\n global $conf;\n\n if (@file_exists($changelog)\n && (filectime($changelog) + 86400) < time()\n && !@file_exists($changelog . '_tmp')\n ) {\n\n io_lock($changelog);\n $lines = file($changelog);\n if (count($lines) < $conf['recent']) {\n // nothing to trim\n io_unlock($changelog);\n return true;\n }\n\n // presave tmp as 2nd lock\n io_saveFile($changelog . '_tmp', '');\n $trim_time = time() - $conf['recent_days'] * 86400;\n $out_lines = [];\n\n $num = count($lines);\n for ($i = 0; $i < $num; $i++) {\n $log = parseChangelogLine($lines[$i]);\n if ($log === false) continue; // discard junk\n if ($log['date'] < $trim_time) {\n $old_lines[$log['date'] . \".$i\"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions)\n } else {\n $out_lines[$log['date'] . \".$i\"] = $lines[$i]; // definitely keep these lines\n }\n }\n\n // sort the final result, it shouldn't be necessary,\n // however the extra robustness in making the changelog cache self-correcting is worth it\n ksort($out_lines);\n $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum\n if ($extra > 0) {\n ksort($old_lines);\n $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);\n }\n\n // save trimmed changelog\n io_saveFile($changelog . '_tmp', implode('', $out_lines));\n @unlink($changelog);\n if (!rename($changelog . '_tmp', $changelog)) {\n // rename failed so try another way...\n io_unlock($changelog);\n io_saveFile($changelog, implode('', $out_lines));\n @unlink($changelog . '_tmp');\n } else {\n io_unlock($changelog);\n }\n return true;\n }\n return true;\n }\n\n /**\n * Sends a notify mail on new comment\n *\n * @param array $comment data array of the new comment\n * @param array $subscribers data of the subscribers by reference\n *\n * @author Andreas Gohr \n * @author Esther Brunner \n */\n protected function notify($comment, &$subscribers)\n {\n global $conf, $ID, $INPUT, $auth;\n\n $notify_text = io_readfile($this->localfn('subscribermail'));\n $confirm_text = io_readfile($this->localfn('confirmsubscribe'));\n $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment');\n $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe');\n\n $mailer = new Mailer();\n if (!$INPUT->server->has('REMOTE_USER')) {\n $mailer->from($conf['mailfromnobody']);\n }\n\n $replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DATE' => dformat($comment['date']['created'], $conf['dformat']),\n 'NAME' => $comment['user']['name'],\n 'TEXT' => $comment['raw'],\n 'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],\n 'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n $confirm_replace = [\n 'PAGE' => $ID,\n 'TITLE' => $conf['title'],\n 'DOKUWIKIURL' => DOKU_URL\n ];\n\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n\n // send mail to notify address\n if ($conf['notify']) {\n $mailer->bcc($conf['notify']);\n $mailer->send();\n }\n\n // send email to moderators\n if ($this->getConf('moderatorsnotify')) {\n $moderatorgrpsString = trim($this->getConf('moderatorgroups'));\n if (!empty($moderatorgrpsString)) {\n // create a clean mods list\n $moderatorgroups = explode(',', $moderatorgrpsString);\n $moderatorgroups = array_map('trim', $moderatorgroups);\n $moderatorgroups = array_unique($moderatorgroups);\n $moderatorgroups = array_filter($moderatorgroups);\n // search for moderators users\n foreach ($moderatorgroups as $moderatorgroup) {\n if (!$auth->isCaseSensitive()) {\n $moderatorgroup = PhpString::strtolower($moderatorgroup);\n }\n // create a clean mailing list\n $bccs = [];\n if ($moderatorgroup[0] == '@') {\n foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) {\n if (!empty($user['mail'])) {\n $bccs[] = $user['mail'];\n }\n }\n } else {\n //it is an user\n $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup));\n if (!empty($userdata['mail'])) {\n $bccs[] = $userdata['mail'];\n }\n }\n $bccs = array_unique($bccs);\n // notify the users\n $mailer->bcc(implode(',', $bccs));\n $mailer->send();\n }\n }\n }\n\n // notify page subscribers\n if (actionOK('subscribe')) {\n $data = ['id' => $ID, 'addresslist' => '', 'self' => false];\n //FIXME default callback, needed to mentioned it again?\n Event::createAndTrigger(\n 'COMMON_NOTIFY_ADDRESSLIST', $data,\n [new SubscriberManager(), 'notifyAddresses']\n );\n\n $to = $data['addresslist'];\n if (!empty($to)) {\n $mailer->bcc($to);\n $mailer->send();\n }\n }\n\n // notify comment subscribers\n if (!empty($subscribers)) {\n\n foreach ($subscribers as $mail => $data) {\n $mailer->bcc($mail);\n if ($data['active']) {\n $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_notify);\n $mailer->setBody($notify_text, $replace);\n $mailer->send();\n } elseif (!$data['confirmsent']) {\n $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');\n\n $mailer->subject($subject_subscribe);\n $mailer->setBody($confirm_text, $confirm_replace);\n $mailer->send();\n $subscribers[$mail]['confirmsent'] = true;\n }\n }\n }\n }\n\n /**\n * Counts the number of visible comments\n *\n * @param array $data array with all comments\n * @return int\n */\n protected function countVisibleComments($data)\n {\n $number = 0;\n foreach ($data['comments'] as $comment) {\n if ($comment['parent']) continue;\n if (!$comment['show']) continue;\n\n $number++;\n $rids = $comment['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Count visible replies on the comments\n *\n * @param array $data\n * @param array $rids\n * @return int counted replies\n */\n protected function countVisibleReplies(&$data, $rids)\n {\n $number = 0;\n foreach ($rids as $rid) {\n if (!isset($data['comments'][$rid])) continue; // reply was removed\n if (!$data['comments'][$rid]['show']) continue;\n\n $number++;\n $rids = $data['comments'][$rid]['replies'];\n if (count($rids)) {\n $number = $number + $this->countVisibleReplies($data, $rids);\n }\n }\n return $number;\n }\n\n /**\n * Renders the raw comment (wiki)text to html\n *\n * @param string $raw comment text\n * @return null|string\n */\n protected function renderComment($raw)\n {\n if ($this->getConf('wikisyntaxok')) {\n // Note the warning for render_text:\n // \"very ineffecient for small pieces of data - try not to use\"\n // in dokuwiki/inc/plugin.php\n $xhtml = $this->render_text($raw);\n } else { // wiki syntax not allowed -> just encode special chars\n $xhtml = hsc(trim($raw));\n $xhtml = str_replace(\"\\n\", '
', $xhtml);\n }\n return $xhtml;\n }\n\n /**\n * Finds out whether there is a discussion section for the current page\n *\n * @param string $title set to title from metadata or empty string\n * @return bool discussion section is shown?\n */\n protected function hasDiscussion(&$title)\n {\n global $ID;\n\n $file = metaFN($ID, '.comments');\n\n if (!@file_exists($file)) {\n if ($this->isDiscussionEnabled()) {\n return true;\n } else {\n return false;\n }\n }\n\n $data = unserialize(io_readFile($file, false));\n\n $title = $data['title'] ?? '';\n\n $num = $data['number'] ?? 0;\n if (!$data['status'] || ($data['status'] == 2 && $num == 0)) {\n //disabled, or closed and no comments\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Creates a new thread page\n *\n * @return string\n */\n protected function newThread()\n {\n global $ID, $INFO, $INPUT;\n\n $ns = cleanID($INPUT->str('ns'));\n $title = str_replace(':', '', $INPUT->str('title'));\n $back = $ID;\n $ID = ($ns ? $ns . ':' : '') . cleanID($title);\n $INFO = pageinfo();\n\n // check if we are allowed to create this file\n if ($INFO['perm'] >= AUTH_CREATE) {\n\n //check if locked by anyone - if not lock for my self\n if ($INFO['locked']) {\n return 'locked';\n } else {\n lock($ID);\n }\n\n // prepare the new thread file with default stuff\n if (!@file_exists($INFO['filepath'])) {\n global $TEXT;\n\n $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title);\n if (!$TEXT) {\n $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back];\n $TEXT = $this->pageTemplate($data);\n }\n return 'preview';\n } else {\n return 'edit';\n }\n } else {\n return 'show';\n }\n }\n\n /**\n * Adapted version of pageTemplate() function\n *\n * @param array $data\n * @return string\n */\n protected function pageTemplate($data)\n {\n global $conf, $INFO, $INPUT;\n\n $id = $data['id'];\n $user = $INPUT->server->str('REMOTE_USER');\n $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt');\n\n // standard replacements\n $replace = [\n '@NS@' => $data['ns'],\n '@PAGE@' => strtr(noNS($id), '_', ' '),\n '@USER@' => $user,\n '@NAME@' => $INFO['userinfo']['name'],\n '@MAIL@' => $INFO['userinfo']['mail'],\n '@DATE@' => dformat(time(), $conf['dformat']),\n ];\n\n // additional replacements\n $replace['@BACK@'] = $data['back'];\n $replace['@TITLE@'] = $data['title'];\n\n // avatar if useavatar and avatar plugin available\n if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) {\n $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} ';\n } else {\n $replace['@AVATAR@'] = '';\n }\n\n // tag if tag plugin is available\n if (!plugin_isdisabled('tag')) {\n $replace['@TAG@'] = \"\\n\\n{{tag>}}\";\n } else {\n $replace['@TAG@'] = '';\n }\n\n // perform the replacements in tpl\n return str_replace(array_keys($replace), array_values($replace), $tpl);\n }\n\n /**\n * Checks if the CAPTCHA string submitted is valid, modifies action if needed\n */\n protected function captchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_captcha $captcha */\n if (!$captcha = $this->loadHelper('captcha', false)) {\n // CAPTCHA is disabled or not available\n return;\n }\n\n if ($captcha->isEnabled() && !$captcha->check()) {\n if ($INPUT->str('comment') == 'save') {\n $INPUT->set('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->set('comment', 'show');\n }\n }\n }\n\n /**\n * checks if the submitted reCAPTCHA string is valid, modifies action if needed\n *\n * @author Adrian Schlegel \n */\n protected function recaptchaCheck()\n {\n global $INPUT;\n /** @var helper_plugin_recaptcha $recaptcha */\n if (!$recaptcha = plugin_load('helper', 'recaptcha'))\n return; // reCAPTCHA is disabled or not available\n\n // do nothing if logged in user and no reCAPTCHA required\n if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return;\n\n $response = $recaptcha->check();\n if (!$response->is_valid) {\n msg($recaptcha->getLang('testfailed'), -1);\n if ($INPUT->str('comment') == 'save') {\n $INPUT->str('comment', 'edit');\n } elseif ($INPUT->str('comment') == 'add') {\n $INPUT->str('comment', 'show');\n }\n }\n }\n\n /**\n * Add discussion plugin version to the indexer version\n * This means that all pages will be indexed again in order to add the comments\n * to the index whenever there has been a change that concerns the index content.\n *\n * @param Doku_Event $event\n */\n public function addIndexVersion(Doku_Event $event)\n {\n $event->data['discussion'] = '0.1';\n }\n\n /**\n * Adds the comments to the index\n *\n * @param Doku_Event $event\n * @param array $param with\n * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event\n * 'text' => string 'body'/'text'\n */\n public function addCommentsToIndex(Doku_Event $event, $param)\n {\n // get .comments meta file name\n $file = metaFN($event->data[$param['id']], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to index\n if (!$data['status'] || $data['number'] == 0) return;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $key => $value) {\n $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data);\n }\n }\n }\n\n /**\n * Checks if the phrase occurs in the comments and return event result true if matching\n *\n * @param Doku_Event $event\n */\n public function fulltextPhraseMatchInComments(Doku_Event $event)\n {\n if ($event->result === true) return;\n\n // get .comments meta file name\n $file = metaFN($event->data['id'], '.comments');\n\n if (!@file_exists($file)) return;\n $data = unserialize(io_readFile($file, false));\n\n // comments are turned off or no comments available to match\n if (!$data['status'] || $data['number'] == 0) return;\n\n $matched = false;\n\n // now add the comments\n if (isset($data['comments'])) {\n foreach ($data['comments'] as $cid => $value) {\n $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data);\n if ($matched) break;\n }\n }\n\n if ($matched) {\n $event->result = true;\n }\n }\n\n /**\n * Match the phrase in the comment and its replies\n *\n * @param string $phrase phrase to search\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return bool if match true, otherwise false\n */\n protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '')\n {\n if (!isset($data['comments'][$cid])) return false; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return false; // corrupt datatype\n if ($comment['parent'] != $parent) return false; // reply to an other comment\n if (!$comment['show']) return false; // hidden comment\n\n $text = PhpString::strtolower($comment['raw']);\n if (strpos($text, $phrase) !== false) {\n return true;\n }\n\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Saves the current comment status and title from metadata into the .comments file\n *\n * @param Doku_Event $event\n */\n public function updateCommentStatusFromMetadata(Doku_Event $event)\n {\n global $ID;\n\n $meta = $event->data['current'];\n\n $file = metaFN($ID, '.comments');\n $configurationStatus = ($this->isDiscussionEnabled() ? 1 : 0); // 0=off, 1=enabled\n $title = null;\n if (isset($meta['plugin_discussion'])) {\n $status = (int) $meta['plugin_discussion']['status']; // 0=off, 1=enabled or 2=closed\n $title = $meta['plugin_discussion']['title'];\n\n // do we have metadata that differs from general config?\n $saveNeededFromMetadata = $configurationStatus !== $status || ($status > 0 && $title);\n } else {\n $status = $configurationStatus;\n $saveNeededFromMetadata = false;\n }\n\n // if .comment file exists always update it with latest status\n if ($saveNeededFromMetadata || file_exists($file)) {\n\n $data = [];\n if (@file_exists($file)) {\n $data = unserialize(io_readFile($file, false));\n }\n\n if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {\n //title can be only set from metadata\n $data['title'] = $title;\n $data['status'] = $status;\n if (!isset($data['number'])) {\n $data['number'] = 0;\n }\n io_saveFile($file, serialize($data));\n }\n }\n }\n\n /**\n * Return words of a given comment and its replies, suitable to be added to the index\n *\n * @param string $cid comment id\n * @param array $data array with all comments by reference\n * @param string $parent cid of parent\n * @return string\n */\n protected function addCommentWords($cid, &$data, $parent = '')\n {\n\n if (!isset($data['comments'][$cid])) return ''; // comment was removed\n\n $comment = $data['comments'][$cid];\n\n if (!is_array($comment)) return ''; // corrupt datatype\n if ($comment['parent'] != $parent) return ''; // reply to an other comment\n if (!$comment['show']) return ''; // hidden comment\n\n $text = $comment['raw']; // we only add the raw comment text\n if (is_array($comment['replies'])) { // and the replies\n foreach ($comment['replies'] as $rid) {\n $text .= $this->addCommentWords($rid, $data, $cid);\n }\n }\n return ' ' . $text;\n }\n\n /**\n * Only allow http(s) URLs and append http:// to URLs if needed\n *\n * @param string $url\n * @return string\n */\n protected function checkURL($url)\n {\n if (preg_match(\"#^http://|^https://#\", $url)) {\n return hsc($url);\n } elseif (substr($url, 0, 4) == 'www.') {\n return hsc('https://' . $url);\n } else {\n return '';\n }\n }\n\n /**\n * Sort threads\n *\n * @param array $a array with comment properties\n * @param array $b array with comment properties\n * @return int\n */\n function sortThreadsOnCreation($a, $b)\n {\n if (is_array($a['date'])) {\n // new format\n $createdA = $a['date']['created'];\n } else {\n // old format\n $createdA = $a['date'];\n }\n\n if (is_array($b['date'])) {\n // new format\n $createdB = $b['date']['created'];\n } else {\n // old format\n $createdB = $b['date'];\n }\n\n if ($createdA == $createdB) {\n return 0;\n } else {\n return ($createdA < $createdB) ? -1 : 1;\n }\n }\n\n}\n\n\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/autoload.rb", "file_before": "require \"#{Rails.root}/config/initializers/inflections\"\n\nmodule HasManyPolymorphs\n\n=begin rdoc \nSearches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes. \n\nNote that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an after_initialize block in config/environment.rb that appends to the 'requirements' key:\n Rails::Initializer.run do |config| \n # your other configuration here\n \n config.after_initialize do\n config.has_many_polymorphs.options['requirements'] << 'lib/my_extension'\n end \n end\n \n=end\n \n MODELS_ROOT = Rails.root.join('app', 'models')\n \n DEFAULT_OPTIONS = {\n :file_pattern => \"#{MODELS_ROOT}/**/*.rb\",\n :file_exclusions => ['svn', 'CVS', 'bzr'],\n :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],\n :requirements => []}\n \n mattr_accessor :options\n @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS) \n\n # Dispatcher callback to load polymorphic relationships from the top down.\n def self.setup\n\n _logger_debug \"autoload hook invoked\"\n \n options[:requirements].each do |requirement|\n _logger_warn \"forcing requirement load of #{requirement}\"\n require requirement\n end\n \n Dir.glob(options[:file_pattern]).each do |filename|\n next if filename =~ /#{options[:file_exclusions].join(\"|\")}/\n open(filename) do |file|\n if file.grep(/#{options[:methods].join(\"|\")}/).any?\n begin\n # determines the modelname by the directory - this allows the autoload of namespaced models\n modelname = filename[0..-4].gsub(\"#{MODELS_ROOT.to_s}/\", \"\")\n model = modelname.camelize\n _logger_warn \"preloading parent model #{model}\"\n model.constantize\n rescue Object => e\n _logger_warn \"#{model} could not be preloaded: #{e.inspect} #{e.backtrace}\"\n end\n end\n end\n end\n end \n \nend\n", "file_after": "require \"#{Rails.root}/config/initializers/inflections\"\n\nmodule HasManyPolymorphs\n\n=begin rdoc\nSearches for models that use has_many_polymorphs or acts_as_double_polymorphic_join and makes sure that they get loaded during app initialization. This ensures that helper methods are injected into the target classes.\n\nNote that you can override DEFAULT_OPTIONS via Rails::Configuration#has_many_polymorphs_options. For example, if you need an application extension to be required before has_many_polymorphs loads your models, add an after_initialize block in config/environment.rb that appends to the 'requirements' key:\n Rails::Initializer.run do |config|\n # your other configuration here\n\n config.after_initialize do\n config.has_many_polymorphs.options['requirements'] << 'lib/my_extension'\n end\n end\n\n=end\n\n MODELS_ROOT = Rails.root.join('app', 'models')\n\n DEFAULT_OPTIONS = {\n :file_pattern => \"#{MODELS_ROOT}/**/*.rb\",\n :file_exclusions => ['svn', 'CVS', 'bzr'],\n :methods => ['has_many_polymorphs', 'acts_as_double_polymorphic_join'],\n :requirements => []}\n\n mattr_accessor :options\n @@options = HashWithIndifferentAccess.new(DEFAULT_OPTIONS)\n\n # Dispatcher callback to load polymorphic relationships from the top down.\n def self.setup\n\n _logger_debug \"autoload hook invoked\"\n\n options[:requirements].each do |requirement|\n _logger_warn \"forcing requirement load of #{requirement}\"\n require requirement\n end\n\n Dir.glob(options[:file_pattern]).each do |filename|\n next if filename =~ /#{options[:file_exclusions].join(\"|\")}/\n open(filename) do |file|\n if file.grep(/#{options[:methods].join(\"|\")}/).any?\n begin\n # determines the modelname by the directory - this allows the autoload of namespaced models\n modelname = filename[0..-4].gsub(\"#{MODELS_ROOT.to_s}/\", \"\")\n model = modelname.camelize\n _logger_warn \"preloading parent model #{model}\"\n model.constantize\n rescue Object => e\n _logger_warn \"#{model} could not be preloaded: #{e.inspect} #{e.backtrace}\"\n end\n end\n end\n end\n end\n\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/debugging_tools.rb", "file_before": "\n=begin rdoc\n\nDebugging tools for Has_many_polymorphs. \n\nEnable the different tools by setting the environment variable HMP_DEBUG. Settings with special meaning are \"ruby-debug\", \"trace\", and \"dependencies\".\n\n== Code generation\n\nEnabled by default when HMP_DEBUG is set.\n\nOuputs a folder generated_models/ in RAILS_ROOT containing valid Ruby files explaining all the ActiveRecord relationships set up by the plugin, as well as listing the line in the plugin that called each particular association method.\n\n== Ruby-debug\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nStarts ruby-debug for the life of the process.\n\n== Trace\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nOutputs an indented trace of relevant method calls as they occur.\n\n== Dependencies\n\nEnable by setting HMP_DEBUG to \"dependencies\".\n\nTurns on Rails' default dependency logging.\n\n=end\n\n_logger_warn \"debug mode enabled\"\n\nclass << ActiveRecord::Base\n COLLECTION_METHODS = [:belongs_to, :has_many, :has_and_belongs_to_many, :has_one, \n :has_many_polymorphs, :acts_as_double_polymorphic_join].each do |method_name|\n alias_method \"original_#{method_name}\".to_sym, method_name\n undef_method method_name\n end \n\n unless defined? GENERATED_CODE_DIR\n GENERATED_CODE_DIR = \"#{RAILS_ROOT}/generated_models\"\n \n begin\n system \"rm -rf #{GENERATED_CODE_DIR}\" \n Dir.mkdir GENERATED_CODE_DIR\n rescue Errno::EACCES\n _logger_warn \"no permissions for generated code dir: #{GENERATED_CODE_DIR}\"\n end\n\n if File.exist? GENERATED_CODE_DIR\n alias :original_method_missing :method_missing\n def method_missing(method_name, *args, &block)\n if COLLECTION_METHODS.include? method_name.to_sym\n Dir.chdir GENERATED_CODE_DIR do\n filename = \"#{demodulate(self.name.underscore)}.rb\"\n contents = File.open(filename).read rescue \"\\nclass #{self.name}\\n\\nend\\n\"\n line = caller[1][/\\:(\\d+)\\:/, 1]\n contents[-5..-5] = \"\\n #{method_name} #{args[0..-2].inspect[1..-2]},\\n #{args[-1].inspect[1..-2].gsub(\" :\", \"\\n :\").gsub(\"=>\", \" => \")}\\n#{ block ? \" #{block.inspect.sub(/\\@.*\\//, '@')}\\n\" : \"\"} # called from line #{line}\\n\\n\"\n File.open(filename, \"w\") do |file| \n file.puts contents \n end\n end\n # doesn't actually display block contents\n self.send(\"original_#{method_name}\", *args, &block)\n else\n self.send(:original_method_missing, method_name, *args, &block)\n end\n end\n end \n \n end\nend\n\ncase ENV['HMP_DEBUG']\n\n when \"ruby-debug\"\n require 'rubygems'\n require 'ruby-debug'\n Debugger.start\n _logger_warn \"ruby-debug enabled.\"\n\n when \"trace\"\n _logger_warn \"method tracing enabled\" \n $debug_trace_indent = 0\n set_trace_func (proc do |event, file, line, id, binding, classname|\n if id.to_s =~ /instantiate/ #/IRB|Wirble|RubyLex|RubyToken|Logger|ConnectionAdapters|SQLite3|MonitorMixin|Benchmark|Inflector|Inflections/ \n if event == 'call'\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id} from #{file.split('/').last}::#{line}\"\n $debug_trace_indent += 1\n elsif event == 'return'\n $debug_trace_indent -= 1 unless $debug_trace_indent == 0\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id}\"\n end\n end\n end)\n \n when \"dependencies\"\n _logger_warn \"dependency activity being logged\"\n (::Dependencies.log_activity = true) rescue nil\nend\n", "file_after": "\n=begin rdoc\n\nDebugging tools for Has_many_polymorphs.\n\nEnable the different tools by setting the environment variable HMP_DEBUG. Settings with special meaning are \"ruby-debug\", \"trace\", and \"dependencies\".\n\n== Code generation\n\nEnabled by default when HMP_DEBUG is set.\n\nOuputs a folder generated_models/ in Rails.root containing valid Ruby files explaining all the ActiveRecord relationships set up by the plugin, as well as listing the line in the plugin that called each particular association method.\n\n== Ruby-debug\n\nEnable by setting HMP_DEBUG to \"ruby-debug\".\n\nStarts ruby-debug for the life of the process.\n\n== Trace\n\nEnable by setting HMP_DEBUG to \"trace\".\n\nOutputs an indented trace of relevant method calls as they occur.\n\n== Dependencies\n\nEnable by setting HMP_DEBUG to \"dependencies\".\n\nTurns on Rails' default dependency logging.\n\n=end\n\n_logger_warn \"debug mode enabled\"\n\nclass << ActiveRecord::Base\n COLLECTION_METHODS = [:belongs_to, :has_many, :has_and_belongs_to_many, :has_one,\n :has_many_polymorphs, :acts_as_double_polymorphic_join].each do |method_name|\n alias_method \"original_#{method_name}\".to_sym, method_name\n undef_method method_name\n end\n\n unless defined? GENERATED_CODE_DIR\n base_dir = defined?(Rails) ? Rails.root.expand_path : '/tmp'\n GENERATED_CODE_DIR = \"#{base_dir}/generated_models\"\n\n begin\n system \"rm -rf #{GENERATED_CODE_DIR}\"\n Dir.mkdir GENERATED_CODE_DIR\n rescue Errno::EACCES\n _logger_warn \"no permissions for generated code dir: #{GENERATED_CODE_DIR}\"\n end\n\n if File.exist? GENERATED_CODE_DIR\n alias :original_method_missing :method_missing\n def method_missing(method_name, *args, &block)\n if COLLECTION_METHODS.include? method_name.to_sym\n Dir.chdir GENERATED_CODE_DIR do\n filename = \"#{demodulate(self.name.underscore)}.rb\"\n contents = File.open(filename).read rescue \"\\nclass #{self.name}\\n\\nend\\n\"\n callfile, callline = caller[2][%r!/.*/(.*?:\\d+)!, 1].split(':')\n contents[-5..-5] = \"\\n #{method_name} #{args[0..-2].inspect[1..-2]},\\n #{args[-1].inspect[1..-2].gsub(\" :\", \"\\n :\").gsub(\"=>\", \" => \")}\\n#{ block ? \" #{block.inspect.sub(/\\@.*\\//, '@')}\\n\" : \"\"} # called from #{callfile}, line #{callline}\\n\\n\"\n File.open(filename, \"w\") do |file|\n file.puts contents\n end\n end\n # doesn't actually display block contents\n self.send(\"original_#{method_name}\", *args, &block)\n else\n self.send(:original_method_missing, method_name, *args, &block)\n end\n end\n end\n\n end\nend\n\ncase ENV['HMP_DEBUG']\n\n when \"ruby-debug\"\n require 'rubygems'\n require 'ruby-debug'\n Debugger.start\n _logger_warn \"ruby-debug enabled.\"\n\n when \"trace\"\n _logger_warn \"method tracing enabled\"\n $debug_trace_indent = 0\n set_trace_func (proc do |event, file, line, id, binding, classname|\n if id.to_s =~ /instantiate/ #/IRB|Wirble|RubyLex|RubyToken|Logger|ConnectionAdapters|SQLite3|MonitorMixin|Benchmark|Inflector|Inflections/\n if event == 'call'\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id} from #{file.split('/').last}::#{line}\"\n $debug_trace_indent += 1\n elsif event == 'return'\n $debug_trace_indent -= 1 unless $debug_trace_indent == 0\n puts (\" \" * $debug_trace_indent) + \"#{event}ed #{classname}\\##{id}\"\n end\n end\n end)\n\n when \"dependencies\"\n _logger_warn \"dependency activity being logged\"\n (::Dependencies.log_activity = true) rescue nil\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/base.rb", "file_before": "\nmodule ActiveRecord\n class Base\n \n class << self\n \n # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks.\n def instantiate_with_polymorphic_checks(record)\n if record['polymorphic_parent_class']\n reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym)\n# _logger_debug \"Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})\"\n\n # rewrite the record with the right column names\n table_aliases = reflection.options[:table_aliases].dup\n record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten] \n \n # find the real child class\n klass = record[\"#{self.table_name}.#{reflection.options[:polymorphic_type_key]}\"].constantize\n if sti_klass = record[\"#{klass.table_name}.#{klass.inheritance_column}\"]\n klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models\n end\n \n # check that the join actually joined to something\n unless (child_id = record[\"#{self.table_name}.#{reflection.options[:polymorphic_key]}\"]) == record[\"#{klass.table_name}.#{klass.primary_key}\"]\n raise ActiveRecord::Associations::PolymorphicError, \n \"Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}\" \n end\n \n # eject the join keys\n # XXX not very readable\n record = Hash[*record._select do |column, value| \n column[/^#{klass.table_name}/]\n end.map do |column, value|\n [column[/\\.(.*)/, 1], value]\n end.flatten]\n \n # allocate and assign values\n returning(klass.allocate) do |obj|\n obj.instance_variable_set(\"@attributes\", record)\n obj.instance_variable_set(\"@attributes_cache\", Hash.new)\n \n if obj.respond_to_without_attributes?(:after_find)\n obj.send(:callback, :after_find)\n end\n \n if obj.respond_to_without_attributes?(:after_initialize)\n obj.send(:callback, :after_initialize)\n end\n \n end\n else \n instantiate_without_polymorphic_checks(record)\n end\n end\n \n alias_method_chain :instantiate, :polymorphic_checks \n end\n \n end\nend\n", "file_after": "\nmodule ActiveRecord\n class Base\n\n class << self\n\n # Interprets a polymorphic row from a unified SELECT, returning the appropriate ActiveRecord instance. Overrides ActiveRecord::Base.instantiate_without_callbacks.\n def instantiate_with_polymorphic_checks(record)\n if record['polymorphic_parent_class']\n reflection = record['polymorphic_parent_class'].constantize.reflect_on_association(record['polymorphic_association_id'].to_sym)\n# _logger_debug \"Instantiating a polymorphic row for #{record['polymorphic_parent_class']}.reflect_on_association(:#{record['polymorphic_association_id']})\"\n\n # rewrite the record with the right column names\n table_aliases = reflection.options[:table_aliases].dup\n record = Hash[*table_aliases.keys.map {|key| [key, record[table_aliases[key]]] }.flatten]\n\n # find the real child class\n klass = record[\"#{self.table_name}.#{reflection.options[:polymorphic_type_key]}\"].constantize\n if sti_klass = record[\"#{klass.table_name}.#{klass.inheritance_column}\"]\n klass = klass.class_eval do compute_type(sti_klass) end # in case of namespaced STI models\n\n # copy the data over to the right structure\n klass.columns.map(&:name).each do |col|\n record[\"#{klass.table_name}.#{col}\"] = record[\"#{klass.base_class.table_name}.#{col}\"]\n end\n end\n\n # check that the join actually joined to something\n unless (child_id = record[\"#{self.table_name}.#{reflection.options[:polymorphic_key]}\"]) == record[\"#{klass.table_name}.#{klass.primary_key}\"]\n raise ActiveRecord::Associations::PolymorphicError,\n \"Referential integrity violation; child <#{klass.name}:#{child_id}> was not found for #{reflection.name.inspect}\"\n end\n\n # eject the join keys\n # XXX not very readable\n record = Hash[*record._select do |column, value|\n column[/^#{klass.table_name}/]\n end.map do |column, value|\n [column[/\\.(.*)/, 1], value]\n end.flatten]\n\n # allocate and assign values\n klass.allocate.tap do |obj|\n obj.instance_variable_set(\"@attributes\", record)\n obj.instance_variable_set(\"@attributes_cache\", Hash.new)\n\n if obj.respond_to_without_attributes?(:after_find)\n obj.send(:callback, :after_find)\n end\n\n if obj.respond_to_without_attributes?(:after_initialize)\n obj.send(:callback, :after_initialize)\n end\n\n end\n else\n instantiate_without_polymorphic_checks(record)\n end\n end\n\n alias_method_chain :instantiate, :polymorphic_checks\n end\n\n end\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/class_methods.rb", "file_before": "\nmodule ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n=begin rdoc\n\nClass methods added to ActiveRecord::Base for setting up polymorphic associations.\n\n== Notes\n \nSTI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say [:dogs, :cats], and not [:animals].\n\nNamespaced models follow the Rails underscore convention. ZooAnimal::Lion becomes :'zoo_animal/lion'.\n\nYou do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required. \n\nThere is a tentative report that you can make the parent model be its own join model, but this is untested.\n\n=end\n\n module PolymorphicClassMethods\n \n RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates, \n :join_extend, :dependent, :rename_individual_collections,\n :namespace] #:nodoc:\n \n=begin rdoc\n\nThis method creates a doubled-sided polymorphic relationship. It must be called on the join model:\n\n class Devouring < ActiveRecord::Base\n belongs_to :eater, :polymorphic => true\n belongs_to :eaten, :polymorphic => true\n \n acts_as_double_polymorphic_join(\n :eaters => [:dogs, :cats], \n :eatens => [:cats, :birds]\n ) \n end\n\nThe method works by defining one or more special has_many_polymorphs association on every model in the target lists, depending on which side of the association it is on. Double self-references will work.\n\nThe two association names and their value arrays are the only required parameters.\n\n== Available options\n\nThese options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, :eaters_extend.\n\n:dependent:: Accepts :destroy, :nullify, or :delete_all. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"\\_of_#{association_name}\".\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:conditions:: An array or string of conditions for the SQL WHERE clause. \n:order:: A string for the SQL ORDER BY clause.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n\n=end\n\n def acts_as_double_polymorphic_join options={}, &extension \n \n collections, options = extract_double_collections(options)\n \n # handle the block\n options[:extend] = (if options[:extend]\n Array(options[:extend]) + [extension]\n else \n extension\n end) if extension \n \n collection_option_keys = make_general_option_keys_specific!(options, collections)\n \n join_name = self.name.tableize.to_sym\n collections.each do |association_id, children|\n parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array\n \n begin\n parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name\n rescue NoMethodError\n raise PolymorphicError, \"Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}.\" unless parent_foreign_key\n end\n\n parents = collections[parent_hash_key]\n conflicts = (children & parents) # set intersection \n parents.each do |plural_parent_name| \n \n parent_class = plural_parent_name._as_class\n singular_reverse_association_id = parent_hash_key._singularize \n \n internal_options = {\n :is_double => true,\n :from => children, \n :as => singular_reverse_association_id,\n :through => join_name.to_sym, \n :foreign_key => parent_foreign_key, \n :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'),\n :singular_reverse_association_id => singular_reverse_association_id,\n :conflicts => conflicts\n }\n \n general_options = Hash[*options._select do |key, value|\n collection_option_keys[association_id].include? key and !value.nil?\n end.map do |key, value|\n [key.to_s[association_id.to_s.length+1..-1].to_sym, value]\n end._flatten_once] # rename side-specific options to general names\n \n general_options.each do |key, value|\n # avoid clobbering keys that appear in both option sets\n if internal_options[key]\n general_options[key] = Array(value) + Array(internal_options[key])\n end\n end\n\n parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options))\n \n if conflicts.include? plural_parent_name \n # unify the alternate sides of the conflicting children\n (conflicts).each do |method_name|\n unless parent_class.instance_methods.include?(method_name)\n parent_class.send(:define_method, method_name) do\n (self.send(\"#{singular_reverse_association_id}_#{method_name}\") + \n self.send(\"#{association_id._singularize}_#{method_name}\")).freeze\n end\n end \n end \n \n # unify the join model... join model is always renamed for doubles, unlike child associations\n unless parent_class.instance_methods.include?(join_name)\n parent_class.send(:define_method, join_name) do\n (self.send(\"#{join_name}_as_#{singular_reverse_association_id}\") + \n self.send(\"#{join_name}_as_#{association_id._singularize}\")).freeze\n end \n end \n else\n unless parent_class.instance_methods.include?(join_name)\n # ensure there are no forward slashes in the aliased join_name_method (occurs when namespaces are used)\n join_name_method = join_name.to_s.gsub('/', '_').to_sym\n parent_class.send(:alias_method, join_name_method, \"#{join_name_method}_as_#{singular_reverse_association_id}\")\n end\n end \n \n end\n end\n end\n \n private\n \n def extract_double_collections(options)\n collections = options._select do |key, value| \n value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/\n end\n \n raise PolymorphicError, \"Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore.\" unless collections.size == 2\n \n options = options._select do |key, value| \n !collections[key]\n end\n \n [collections, options]\n end\n \n def make_general_option_keys_specific!(options, collections)\n collection_option_keys = Hash[*collections.keys.map do |key|\n [key, RESERVED_DOUBLES_KEYS.map{|option| \"#{key}_#{option}\".to_sym}] \n end._flatten_once] \n \n collections.keys.each do |collection| \n options.each do |key, value|\n next if collection_option_keys.values.flatten.include? key\n # shift the general options to the individual sides\n collection_key = \"#{collection}_#{key}\".to_sym\n collection_value = options[collection_key]\n case key\n when :conditions\n collection_value, value = sanitize_sql(collection_value), sanitize_sql(value)\n options[collection_key] = (collection_value ? \"(#{collection_value}) AND (#{value})\" : value)\n when :order\n options[collection_key] = (collection_value ? \"#{collection_value}, #{value}\" : value)\n when :extend, :join_extend\n options[collection_key] = Array(collection_value) + Array(value)\n else\n options[collection_key] ||= value\n end \n end\n end\n \n collection_option_keys\n end\n \n \n \n public\n\n=begin rdoc\n\nThis method createds a single-sided polymorphic relationship. \n\n class Petfood < ActiveRecord::Base\n has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds]\n end\n\nThe only required parameter, aside from the association name, is :from. \n\nThe method generates a number of associations aside from the polymorphic one. In this example Petfood also gets dogs, cats, and birds, and Dog, Cat, and Bird get petfoods. (The reverse association to the parents is always plural.)\n\n== Available options\n\n:from:: An array of symbols representing the target models. Required.\n:as:: A symbol for the parent's interface in the join--what the parent 'acts as'.\n:through:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized).\n:dependent:: Accepts :destroy, :nullify, :delete_all. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"_of_#{association_name}\". For example, zoos becomes zoos_of_animals. This is to help avoid method name collisions in crowded classes.\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:parent_extend:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.\n:conditions:: An array or string of conditions for the SQL WHERE clause. \n:parent_conditions:: An array or string of conditions which are applied to the target models' association to the parents.\n:order:: A string for the SQL ORDER BY clause.\n:parent_order:: A string for the SQL ORDER BY which is applied to the target models' association to the parents.\n:group:: An array or string of conditions for the SQL GROUP BY clause. Affects the polymorphic and individual associations.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n:uniq:: If true, the records returned are passed through a pure-Ruby uniq before they are returned. Rarely needed.\n:foreign_key:: The column name for the parent's id in the join. \n:foreign_type_key:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use acts_as_double_polymorphic_join() instead.\n:polymorphic_key:: The column name for the child's id in the join.\n:polymorphic_type_key:: The column name for the child's class name in the join.\n\nIf you pass a block, it gets converted to a Proc and added to :extend. \n\n== On condition nullification\n\nWhen you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's :conditions, :order, and :group options get changed to NULL. For example, if you set :conditions => \"dogs.name != 'Spot'\", when you request .cats, the conditions string is changed to NULL != 'Spot'. \n\nBe aware, however, that NULL != 'Spot' returns false due to SQL's 3-value logic. Instead, you need to use the :conditions string \"dogs.name IS NULL OR dogs.name != 'Spot'\" to get the behavior you probably expect for negative matches.\n\n=end\n\n def has_many_polymorphs (association_id, options = {}, &extension)\n _logger_debug \"associating #{self}.#{association_id}\"\n reflection = create_has_many_polymorphs_reflection(association_id, options, &extension)\n # puts \"Created reflection #{reflection.inspect}\"\n # configure_dependency_for_has_many(reflection)\n collection_reader_method(reflection, PolymorphicAssociation)\n end\n \n # Composed method that assigns option defaults, builds the reflection object, and sets up all the related associations on the parent, join, and targets.\n def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc:\n options.assert_valid_keys(\n :from,\n :as,\n :through,\n :foreign_key,\n :foreign_type_key,\n :polymorphic_key, # same as :association_foreign_key\n :polymorphic_type_key,\n :dependent, # default :destroy, only affects the join table\n :skip_duplicates, # default true, only affects the polymorphic collection\n :ignore_duplicates, # deprecated\n :is_double,\n :rename_individual_collections,\n :reverse_association_id, # not used\n :singular_reverse_association_id,\n :conflicts,\n :extend,\n :join_class_name,\n :join_extend,\n :parent_extend,\n :table_aliases,\n :select, # applies to the polymorphic relationship\n :conditions, # applies to the polymorphic relationship, the children, and the join\n # :include,\n :parent_conditions,\n :parent_order,\n :order, # applies to the polymorphic relationship, the children, and the join\n :group, # only applies to the polymorphic relationship and the children\n :limit, # only applies to the polymorphic relationship and the children\n :offset, # only applies to the polymorphic relationship\n :parent_order,\n :parent_group,\n :parent_limit,\n :parent_offset,\n # :source,\n :namespace,\n :uniq, # XXX untested, only applies to the polymorphic relationship\n # :finder_sql,\n # :counter_sql,\n # :before_add,\n # :after_add,\n # :before_remove,\n # :after_remove\n :dummy)\n \n # validate against the most frequent configuration mistakes\n verify_pluralization_of(association_id) \n raise PolymorphicError, \":from option must be an array\" unless options[:from].is_a? Array \n options[:from].each{|plural| verify_pluralization_of(plural)}\n \n options[:as] ||= self.name.demodulize.underscore.to_sym\n options[:conflicts] = Array(options[:conflicts]) \n options[:foreign_key] ||= \"#{options[:as]}_id\"\n \n options[:association_foreign_key] = \n options[:polymorphic_key] ||= \"#{association_id._singularize}_id\"\n options[:polymorphic_type_key] ||= \"#{association_id._singularize}_type\"\n \n if options.has_key? :ignore_duplicates\n _logger_warn \"DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates\"\n options[:skip_duplicates] = options[:ignore_duplicates]\n end\n options[:skip_duplicates] = true unless options.has_key? :skip_duplicates\n options[:dependent] = :destroy unless options.has_key? :dependent\n options[:conditions] = sanitize_sql(options[:conditions])\n \n # options[:finder_sql] ||= \"(options[:polymorphic_key]\n \n options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name))\n \n # set up namespaces if we have a namespace key\n # XXX needs test coverage\n if options[:namespace]\n namespace = options[:namespace].to_s.chomp(\"/\") + \"/\"\n options[:from].map! do |child|\n \"#{namespace}#{child}\".to_sym\n end\n options[:through] = \"#{namespace}#{options[:through]}\".to_sym\n end\n \n options[:join_class_name] ||= options[:through]._classify \n options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from])\n options[:select] ||= build_select(association_id, options[:table_aliases]) \n \n options[:through] = \"#{options[:through]}_as_#{options[:singular_reverse_association_id]}\" if options[:singular_reverse_association_id]\n options[:through] = demodulate(options[:through]).to_sym\n \n options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension)) \n options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), \"Join\") \n options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), \"Parent\") \n \n # create the reflection object \n returning(create_reflection(:has_many_polymorphs, association_id, options, self)) do |reflection| \n # set up the other related associations \n create_join_association(association_id, reflection)\n create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n create_has_many_through_associations_for_children_to_parent(association_id, reflection) \n end \n end\n \n private\n \n\n # table mapping for use at the instantiation point \n \n def build_table_aliases(from)\n # for the targets\n returning({}) do |aliases|\n from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index|\n begin\n table = plural._as_class.table_name\n rescue NameError => e\n raise PolymorphicError, \"Could not find a valid class for #{plural.inspect} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\\\"module/#{plural}\\\" instead.\"\n end\n begin\n plural._as_class.columns.map(&:name).each_with_index do |field, f_index|\n aliases[\"#{table}.#{field}\"] = \"t#{t_index}_r#{f_index}\"\n end\n rescue ActiveRecord::StatementInvalid => e\n _logger_warn \"Looks like your table doesn't exist for #{plural.to_s._classify}.\\nError #{e}\\nSkipping...\"\n end\n end\n end\n end\n \n def build_select(association_id, aliases)\n # instantiate has to know which reflection the results are coming from\n ([\"\\'#{self.name}\\' AS polymorphic_parent_class\", \n \"\\'#{association_id}\\' AS polymorphic_association_id\"] + \n aliases.map do |table, _alias|\n \"#{table} AS #{_alias}\"\n end.sort).join(\", \")\n end\n \n # method sub-builders\n \n def create_join_association(association_id, reflection)\n \n options = {\n :foreign_key => reflection.options[:foreign_key], \n :dependent => reflection.options[:dependent], \n :class_name => reflection.klass.name, \n :extend => reflection.options[:join_extend]\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true),\n # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true)\n }\n \n if reflection.options[:foreign_type_key] \n type_check = \"#{reflection.options[:join_class_name].constantize.quoted_table_name}.#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}\"\n conjunction = options[:conditions] ? \" AND \" : nil\n options[:conditions] = \"#{options[:conditions]}#{conjunction}#{type_check}\"\n options[:as] = reflection.options[:as]\n end\n \n has_many(reflection.options[:through], options)\n \n inject_before_save_into_join_table(association_id, reflection) \n end\n \n def inject_before_save_into_join_table(association_id, reflection)\n sti_hook = \"sti_class_rewrite\"\n rewrite_procedure = %[self.send(:#{reflection.options[:polymorphic_type_key]}=, self.#{reflection.options[:polymorphic_type_key]}.constantize.base_class.name)]\n \n # XXX should be abstracted?\n reflection.klass.class_eval %[ \n unless instance_methods.include? \"before_save_with_#{sti_hook}\"\n if instance_methods.include? \"before_save\" \n alias_method :before_save_without_#{sti_hook}, :before_save \n def before_save_with_#{sti_hook}\n before_save_without_#{sti_hook}\n #{rewrite_procedure}\n end\n else\n def before_save_with_#{sti_hook}\n #{rewrite_procedure}\n end \n end\n alias_method :before_save, :before_save_with_#{sti_hook}\n end\n ] \n end\n \n def create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n \n child_pluralization_map(association_id, reflection).each do |plural, singular|\n if singular == reflection.options[:as]\n raise PolymorphicError, if reflection.options[:is_double]\n \"You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes.\"\n else\n \"You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model.\" \n end\n end\n \n parent = self\n plural._as_class.instance_eval do \n # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?)\n unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym \n \n # the join table\n through = \"#{reflection.options[:through]}#{'_as_child' if parent == self}\".to_sym\n has_many(through,\n :as => association_id._singularize, \n# :source => association_id._singularize, \n# :source_type => reflection.options[:polymorphic_type_key], \n :class_name => reflection.klass.name,\n :dependent => reflection.options[:dependent], \n :extend => reflection.options[:join_extend],\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass),\n :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass)\n )\n \n # the association to the target's parents\n association = \"#{reflection.options[:as]._pluralize}#{\"_of_#{association_id}\" if reflection.options[:rename_individual_collections]}\".to_sym \n has_many(association, \n :through => through, \n :class_name => parent.name,\n :source => reflection.options[:as], \n :foreign_key => reflection.options[:foreign_key],\n :extend => reflection.options[:parent_extend],\n :conditions => reflection.options[:parent_conditions],\n :order => reflection.options[:parent_order],\n :offset => reflection.options[:parent_offset],\n :limit => reflection.options[:parent_limit],\n :group => reflection.options[:parent_group])\n \n# debugger if association == :parents\n# \n# nil\n \n end \n end\n end\n end\n \n def create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n #puts \":source => #{child}\"\n current_association = demodulate(child_association_map(association_id, reflection)[plural])\n source = demodulate(singular)\n \n if reflection.options[:conflicts].include? plural\n # XXX check this\n current_association = \"#{association_id._singularize}_#{current_association}\" if reflection.options[:conflicts].include? self.name.tableize.to_sym\n source = \"#{source}_as_#{association_id._singularize}\".to_sym\n end \n \n # make push/delete accessible from the individual collections but still operate via the general collection\n extension_module = self.class_eval %[\n module #{self.name + current_association._classify + \"PolymorphicChildAssociationExtension\"}\n def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end \n alias :<< :push\n def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end\n def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end\n self\n end] \n \n has_many(current_association.to_sym, \n :through => reflection.options[:through], \n :source => association_id._singularize,\n :source_type => plural._as_class.base_class.name,\n :class_name => plural._as_class.name, # make STI not conflate subtypes\n :extend => (Array(extension_module) + reflection.options[:extend]),\n :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class),\n :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class),\n :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class)\n )\n \n end\n end\n \n # some support methods\n \n def child_pluralization_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, plural._singularize]\n end.flatten]\n end\n \n def child_association_map(association_id, reflection) \n Hash[*reflection.options[:from].map do |plural|\n [plural, \"#{association_id._singularize.to_s + \"_\" if reflection.options[:rename_individual_collections]}#{plural}\".to_sym]\n end.flatten]\n end \n \n def demodulate(s)\n s.to_s.gsub('/', '_').to_sym\n end\n \n def build_join_table_symbol(association_id, name)\n [name.to_s, association_id.to_s].sort.join(\"_\").to_sym\n end\n \n def all_classes_for(association_id, reflection)\n klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)]\n klasses += klasses.map(&:base_class)\n klasses.uniq\n end\n \n def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false) \n # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it\n return unless string\n string = string.dup\n # _logger_debug \"devolving #{string} for #{klass}\"\n inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved\n [klass, klass.base_class, reflection.klass, reflection.klass.base_class])\n inappropriate_classes.map do |klass|\n klass.columns.map do |column| \n [klass.table_name, column.name]\n end.map do |table, column|\n [\"#{table}.#{column}\", \"`#{table}`.#{column}\", \"#{table}.`#{column}`\", \"`#{table}`.`#{column}`\"]\n end\n end.flatten.sort_by(&:size).reverse.each do |quoted_reference| \n # _logger_debug \"devolved #{quoted_reference} to NULL\"\n # XXX clause removal would go here \n string.gsub!(quoted_reference, \"NULL\")\n end\n # _logger_debug \"altered to #{string}\"\n string\n end\n \n def verify_pluralization_of(sym)\n sym = sym.to_s\n singular = sym.singularize\n plural = singular.pluralize\n raise PolymorphicError, \"Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?\" unless sym == plural\n end \n \n def spiked_create_extension_module(association_id, extensions, identifier = nil) \n module_extensions = extensions.select{|e| e.is_a? Module}\n proc_extensions = extensions.select{|e| e.is_a? Proc }\n \n # support namespaced anonymous blocks as well as multiple procs\n proc_extensions.each_with_index do |proc_extension, index|\n module_name = \"#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}\"\n the_module = self.class_eval \"module #{module_name}; self; end\" # XXX hrm\n the_module.class_eval &proc_extension\n module_extensions << the_module\n end\n module_extensions\n end\n \n end\n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n=begin rdoc\n\nClass methods added to ActiveRecord::Base for setting up polymorphic associations.\n\n== Notes\n\nSTI association targets must enumerated and named. For example, if Dog and Cat both inherit from Animal, you still need to say [:dogs, :cats], and not [:animals].\n\nNamespaced models follow the Rails underscore convention. ZooAnimal::Lion becomes :'zoo_animal/lion'.\n\nYou do not need to set up any other associations other than for either the regular method or the double. The join associations and all individual and reverse associations are generated for you. However, a join model and table are required.\n\nThere is a tentative report that you can make the parent model be its own join model, but this is untested.\n\n=end\n module PolymorphicClassMethods\n\n RESERVED_DOUBLES_KEYS = [:conditions, :order, :limit, :offset, :extend, :skip_duplicates,\n :join_extend, :dependent, :rename_individual_collections,\n :namespace] #:nodoc:\n\n=begin rdoc\n\nThis method creates a doubled-sided polymorphic relationship. It must be called on the join model:\n\n class Devouring < ActiveRecord::Base\n belongs_to :eater, :polymorphic => true\n belongs_to :eaten, :polymorphic => true\n\n acts_as_double_polymorphic_join(\n :eaters => [:dogs, :cats],\n :eatens => [:cats, :birds]\n )\n end\n\nThe method works by defining one or more special has_many_polymorphs association on every model in the target lists, depending on which side of the association it is on. Double self-references will work.\n\nThe two association names and their value arrays are the only required parameters.\n\n== Available options\n\nThese options are passed through to targets on both sides of the association. If you want to affect only one side, prepend the key with the name of that side. For example, :eaters_extend.\n\n:dependent:: Accepts :destroy, :nullify, or :delete_all. Controls how the join record gets treated on any association delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"\\_of_#{association_name}\".\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:conditions:: An array or string of conditions for the SQL WHERE clause.\n:order:: A string for the SQL ORDER BY clause.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n\n=end\n def acts_as_double_polymorphic_join options={}, &extension\n\n collections, options = extract_double_collections(options)\n\n # handle the block\n options[:extend] = (if options[:extend]\n Array(options[:extend]) + [extension]\n else\n extension\n end) if extension\n\n collection_option_keys = make_general_option_keys_specific!(options, collections)\n\n join_name = self.name.tableize.to_sym\n collections.each do |association_id, children|\n parent_hash_key = (collections.keys - [association_id]).first # parents are the entries in the _other_ children array\n\n begin\n parent_foreign_key = self.reflect_on_association(parent_hash_key._singularize).primary_key_name\n rescue NoMethodError\n raise PolymorphicError, \"Couldn't find 'belongs_to' association for :#{parent_hash_key._singularize} in #{self.name}.\" unless parent_foreign_key\n end\n\n parents = collections[parent_hash_key]\n conflicts = (children & parents) # set intersection\n parents.each do |plural_parent_name|\n\n parent_class = plural_parent_name._as_class\n singular_reverse_association_id = parent_hash_key._singularize\n\n internal_options = {\n :is_double => true,\n :from => children,\n :as => singular_reverse_association_id,\n :through => join_name.to_sym,\n :foreign_key => parent_foreign_key,\n :foreign_type_key => parent_foreign_key.to_s.sub(/_id$/, '_type'),\n :singular_reverse_association_id => singular_reverse_association_id,\n :conflicts => conflicts\n }\n\n general_options = Hash[*options._select do |key, value|\n collection_option_keys[association_id].include? key and !value.nil?\n end.map do |key, value|\n [key.to_s[association_id.to_s.length+1..-1].to_sym, value]\n end._flatten_once] # rename side-specific options to general names\n\n general_options.each do |key, value|\n # avoid clobbering keys that appear in both option sets\n if internal_options[key]\n general_options[key] = Array(value) + Array(internal_options[key])\n end\n end\n\n parent_class.send(:has_many_polymorphs, association_id, internal_options.merge(general_options))\n\n if conflicts.include? plural_parent_name\n # unify the alternate sides of the conflicting children\n (conflicts).each do |method_name|\n unless parent_class.instance_methods.include?(method_name)\n parent_class.send(:define_method, method_name) do\n (self.send(\"#{singular_reverse_association_id}_#{method_name}\") +\n self.send(\"#{association_id._singularize}_#{method_name}\")).freeze\n end\n end\n end\n\n # unify the join model... join model is always renamed for doubles, unlike child associations\n unless parent_class.instance_methods.include?(join_name)\n parent_class.send(:define_method, join_name) do\n (self.send(\"#{join_name}_as_#{singular_reverse_association_id}\") +\n self.send(\"#{join_name}_as_#{association_id._singularize}\")).freeze\n end\n end\n else\n unless parent_class.instance_methods.include?(join_name)\n # ensure there are no forward slashes in the aliased join_name_method (occurs when namespaces are used)\n join_name_method = join_name.to_s.gsub('/', '_').to_sym\n parent_class.send(:alias_method, join_name_method, \"#{join_name_method}_as_#{singular_reverse_association_id}\")\n end\n end\n\n end\n end\n end\n\n=begin rdoc\n\nThis method createds a single-sided polymorphic relationship.\n\n class Petfood < ActiveRecord::Base\n has_many_polymorphs :eaters, :from => [:dogs, :cats, :birds]\n end\n\nThe only required parameter, aside from the association name, is :from.\n\nThe method generates a number of associations aside from the polymorphic one. In this example Petfood also gets dogs, cats, and birds, and Dog, Cat, and Bird get petfoods. (The reverse association to the parents is always plural.)\n\n== Available options\n\n:from:: An array of symbols representing the target models. Required.\n:as:: A symbol for the parent's interface in the join--what the parent 'acts as'.\n:through:: A symbol representing the class of the join model. Follows Rails defaults if not supplied (the parent and the association names, alphabetized, concatenated with an underscore, and singularized).\n:dependent:: Accepts :destroy, :nullify, :delete_all. Controls how the join record gets treated on any associate delete (whether from the polymorph or from an individual collection); defaults to :destroy.\n:skip_duplicates:: If true, will check to avoid pushing already associated records (but also triggering a database load). Defaults to true.\n:rename_individual_collections:: If true, all individual collections are prepended with the polymorph name, and the children's parent collection is appended with \"_of_#{association_name}\". For example, zoos becomes zoos_of_animals. This is to help avoid method name collisions in crowded classes.\n:extend:: One or an array of mixed modules and procs, which are applied to the polymorphic association (usually to define custom methods).\n:join_extend:: One or an array of mixed modules and procs, which are applied to the join association.\n:parent_extend:: One or an array of mixed modules and procs, which are applied to the target models' association to the parents.\n:conditions:: An array or string of conditions for the SQL WHERE clause.\n:parent_conditions:: An array or string of conditions which are applied to the target models' association to the parents.\n:order:: A string for the SQL ORDER BY clause.\n:parent_order:: A string for the SQL ORDER BY which is applied to the target models' association to the parents.\n:group:: An array or string of conditions for the SQL GROUP BY clause. Affects the polymorphic and individual associations.\n:limit:: An integer. Affects the polymorphic and individual associations.\n:offset:: An integer. Only affects the polymorphic association.\n:namespace:: A symbol. Prepended to all the models in the :from and :through keys. This is especially useful for Camping, which namespaces models by default.\n:uniq:: If true, the records returned are passed through a pure-Ruby uniq before they are returned. Rarely needed.\n:foreign_key:: The column name for the parent's id in the join.\n:foreign_type_key:: The column name for the parent's class name in the join, if the parent itself is polymorphic. Rarely needed--if you're thinking about using this, you almost certainly want to use acts_as_double_polymorphic_join() instead.\n:polymorphic_key:: The column name for the child's id in the join.\n:polymorphic_type_key:: The column name for the child's class name in the join.\n\nIf you pass a block, it gets converted to a Proc and added to :extend.\n\n== On condition nullification\n\nWhen you request an individual association, non-applicable but fully-qualified fields in the polymorphic association's :conditions, :order, and :group options get changed to NULL. For example, if you set :conditions => \"dogs.name != 'Spot'\", when you request .cats, the conditions string is changed to NULL != 'Spot'.\n\nBe aware, however, that NULL != 'Spot' returns false due to SQL's 3-value logic. Instead, you need to use the :conditions string \"dogs.name IS NULL OR dogs.name != 'Spot'\" to get the behavior you probably expect for negative matches.\n\n=end\n def has_many_polymorphs(association_id, options = {}, &extension)\n _logger_debug \"associating #{self}.#{association_id}\"\n reflection = create_has_many_polymorphs_reflection(association_id, options, &extension)\n # puts \"Created reflection #{reflection.inspect}\"\n # configure_dependency_for_has_many(reflection)\n collection_reader_method(reflection, PolymorphicAssociation)\n end\n\n # Composed method that assigns option defaults, builds the reflection\n # object, and sets up all the related associations on the parent, join,\n # and targets.\n def create_has_many_polymorphs_reflection(association_id, options, &extension) #:nodoc:\n options.assert_valid_keys(\n :from,\n :as,\n :through,\n :foreign_key,\n :foreign_type_key,\n :polymorphic_key, # same as :association_foreign_key\n :polymorphic_type_key,\n :dependent, # default :destroy, only affects the join table\n :skip_duplicates, # default true, only affects the polymorphic collection\n :ignore_duplicates, # deprecated\n :is_double,\n :rename_individual_collections,\n :reverse_association_id, # not used\n :singular_reverse_association_id,\n :conflicts,\n :extend,\n :join_class_name,\n :join_extend,\n :parent_extend,\n :table_aliases,\n :select, # applies to the polymorphic relationship\n :conditions, # applies to the polymorphic relationship, the children, and the join\n # :include,\n :parent_conditions,\n :parent_order,\n :order, # applies to the polymorphic relationship, the children, and the join\n :group, # only applies to the polymorphic relationship and the children\n :limit, # only applies to the polymorphic relationship and the children\n :offset, # only applies to the polymorphic relationship\n :parent_order,\n :parent_group,\n :parent_limit,\n :parent_offset,\n # :source,\n :namespace,\n :uniq, # XXX untested, only applies to the polymorphic relationship\n # :finder_sql,\n # :counter_sql,\n # :before_add,\n # :after_add,\n # :before_remove,\n # :after_remove\n :dummy\n )\n\n # validate against the most frequent configuration mistakes\n verify_pluralization_of(association_id)\n raise PolymorphicError, \":from option must be an array\" unless options[:from].is_a? Array\n options[:from].each{|plural| verify_pluralization_of(plural)}\n\n options[:as] ||= self.name.demodulize.underscore.to_sym\n options[:conflicts] = Array(options[:conflicts])\n options[:foreign_key] ||= \"#{options[:as]}_id\"\n\n options[:association_foreign_key] =\n options[:polymorphic_key] ||= \"#{association_id._singularize}_id\"\n options[:polymorphic_type_key] ||= \"#{association_id._singularize}_type\"\n\n if options.has_key? :ignore_duplicates\n _logger_warn \"DEPRECATION WARNING: please use :skip_duplicates instead of :ignore_duplicates\"\n options[:skip_duplicates] = options[:ignore_duplicates]\n end\n options[:skip_duplicates] = true unless options.has_key? :skip_duplicates\n options[:dependent] = :destroy unless options.has_key? :dependent\n options[:conditions] = sanitize_sql(options[:conditions])\n\n # options[:finder_sql] ||= \"(options[:polymorphic_key]\n\n options[:through] ||= build_join_table_symbol(association_id, (options[:as]._pluralize or self.table_name))\n\n # set up namespaces if we have a namespace key\n # XXX needs test coverage\n if options[:namespace]\n namespace = options[:namespace].to_s.chomp(\"/\") + \"/\"\n options[:from].map! do |child|\n \"#{namespace}#{child}\".to_sym\n end\n options[:through] = \"#{namespace}#{options[:through]}\".to_sym\n end\n\n options[:join_class_name] ||= options[:through]._classify\n options[:table_aliases] ||= build_table_aliases([options[:through]] + options[:from])\n options[:select] ||= build_select(association_id, options[:table_aliases])\n\n options[:through] = \"#{options[:through]}_as_#{options[:singular_reverse_association_id]}\" if options[:singular_reverse_association_id]\n options[:through] = demodulate(options[:through]).to_sym\n\n options[:extend] = spiked_create_extension_module(association_id, Array(options[:extend]) + Array(extension))\n options[:join_extend] = spiked_create_extension_module(association_id, Array(options[:join_extend]), \"Join\")\n options[:parent_extend] = spiked_create_extension_module(association_id, Array(options[:parent_extend]), \"Parent\")\n\n # create the reflection object\n create_reflection(:has_many_polymorphs, association_id, options, self).tap do |reflection|\n # set up the other related associations\n create_join_association(association_id, reflection)\n create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n end\n end\n\n private\n\n def extract_double_collections(options)\n collections = options._select do |key, value|\n value.is_a? Array and key.to_s !~ /(#{RESERVED_DOUBLES_KEYS.map(&:to_s).join('|')})$/\n end\n\n raise PolymorphicError, \"Couldn't understand options in acts_as_double_polymorphic_join. Valid parameters are your two class collections, and then #{RESERVED_DOUBLES_KEYS.inspect[1..-2]}, with optionally your collection names prepended and joined with an underscore.\" unless collections.size == 2\n\n options = options._select do |key, value|\n !collections[key]\n end\n\n [collections, options]\n end\n\n def make_general_option_keys_specific!(options, collections)\n collection_option_keys = Hash[*collections.keys.map do |key|\n [key, RESERVED_DOUBLES_KEYS.map{|option| \"#{key}_#{option}\".to_sym}]\n end._flatten_once]\n\n collections.keys.each do |collection|\n options.each do |key, value|\n next if collection_option_keys.values.flatten.include? key\n # shift the general options to the individual sides\n collection_key = \"#{collection}_#{key}\".to_sym\n collection_value = options[collection_key]\n case key\n when :conditions\n collection_value, value = sanitize_sql(collection_value), sanitize_sql(value)\n options[collection_key] = (collection_value ? \"(#{collection_value}) AND (#{value})\" : value)\n when :order\n options[collection_key] = (collection_value ? \"#{collection_value}, #{value}\" : value)\n when :extend, :join_extend\n options[collection_key] = Array(collection_value) + Array(value)\n else\n options[collection_key] ||= value\n end\n end\n end\n\n collection_option_keys\n end\n\n # table mapping for use at the instantiation point\n\n def build_table_aliases(from)\n # for the targets\n {}.tap do |aliases|\n from.map(&:to_s).sort.map(&:to_sym).each_with_index do |plural, t_index|\n begin\n table = plural._as_class.table_name\n rescue NameError => e\n raise PolymorphicError, \"Could not find a valid class for #{plural.inspect} (tried #{plural.to_s._classify}). If it's namespaced, be sure to specify it as :\\\"module/#{plural}\\\" instead.\"\n end\n begin\n plural._as_class.columns.map(&:name).each_with_index do |field, f_index|\n aliases[\"#{table}.#{field}\"] = \"t#{t_index}_r#{f_index}\"\n end\n rescue ActiveRecord::StatementInvalid => e\n _logger_warn \"Looks like your table doesn't exist for #{plural.to_s._classify}.\\nError #{e}\\nSkipping...\"\n end\n end\n end\n end\n\n def build_select(association_id, aliases)\n # instantiate has to know which reflection the results are coming from\n ([\"\\'#{self.name}\\' AS polymorphic_parent_class\",\n \"\\'#{association_id}\\' AS polymorphic_association_id\"] +\n aliases.map do |table, _alias|\n \"#{table} AS #{_alias}\"\n end.sort).join(\", \")\n end\n\n # method sub-builders\n\n def create_join_association(association_id, reflection)\n\n options = {\n :foreign_key => reflection.options[:foreign_key],\n :dependent => reflection.options[:dependent],\n :class_name => reflection.klass.name,\n :extend => reflection.options[:join_extend]\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n # :order => devolve(association_id, reflection, reflection.options[:order], reflection.klass, true),\n # :conditions => devolve(association_id, reflection, reflection.options[:conditions], reflection.klass, true)\n }\n\n if reflection.options[:foreign_type_key]\n type_check = \"#{reflection.options[:join_class_name].constantize.quoted_table_name}.#{reflection.options[:foreign_type_key]} = #{quote_value(self.base_class.name)}\"\n conjunction = options[:conditions] ? \" AND \" : nil\n options[:conditions] = \"#{options[:conditions]}#{conjunction}#{type_check}\"\n options[:as] = reflection.options[:as]\n end\n\n has_many(reflection.options[:through], options)\n\n inject_before_save_into_join_table(association_id, reflection)\n end\n\n def inject_before_save_into_join_table(association_id, reflection)\n sti_hook = \"sti_class_rewrite\"\n polymorphic_type_key = reflection.options[:polymorphic_type_key]\n\n reflection.klass.class_eval %{\n unless [self._save_callbacks.map(&:raw_filter)].flatten.include?(:#{sti_hook})\n before_save :#{sti_hook}\n\n def #{sti_hook}\n self.send(:#{polymorphic_type_key}=, self.#{polymorphic_type_key}.constantize.base_class.name)\n end\n end\n }\n end\n\n def create_has_many_through_associations_for_children_to_parent(association_id, reflection)\n\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n if singular == reflection.options[:as]\n raise PolymorphicError, if reflection.options[:is_double]\n \"You can't give either of the sides in a double-polymorphic join the same name as any of the individual target classes.\"\n else\n \"You can't have a self-referential polymorphic has_many :through without renaming the non-polymorphic foreign key in the join model.\"\n end\n end\n\n parent = self\n plural._as_class.instance_eval do\n # this shouldn't be called at all during doubles; there is no way to traverse to a double polymorphic parent (XXX is that right?)\n unless reflection.options[:is_double] or reflection.options[:conflicts].include? self.name.tableize.to_sym\n\n # the join table\n through = \"#{reflection.options[:through]}#{'_as_child' if parent == self}\".to_sym\n has_many(through,\n :as => association_id._singularize,\n# :source => association_id._singularize,\n # :source_type => reflection.options[:polymorphic_type_key],\n :class_name => reflection.klass.name,\n :dependent => reflection.options[:dependent],\n :extend => reflection.options[:join_extend],\n # :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:parent_order], reflection.klass),\n :conditions => devolve(association_id, reflection, reflection.options[:parent_conditions], reflection.klass)\n )\n\n # the association to the target's parents\n association = \"#{reflection.options[:as]._pluralize}#{\"_of_#{association_id}\" if reflection.options[:rename_individual_collections]}\".to_sym\n has_many(association,\n :through => through,\n :class_name => parent.name,\n :source => reflection.options[:as],\n :foreign_key => reflection.options[:foreign_key],\n :extend => reflection.options[:parent_extend],\n :conditions => reflection.options[:parent_conditions],\n :order => reflection.options[:parent_order],\n :offset => reflection.options[:parent_offset],\n :limit => reflection.options[:parent_limit],\n :group => reflection.options[:parent_group])\n\n# debugger if association == :parents\n#\n# nil\n\n end\n end\n end\n end\n\n def create_has_many_through_associations_for_parent_to_children(association_id, reflection)\n child_pluralization_map(association_id, reflection).each do |plural, singular|\n #puts \":source => #{child}\"\n current_association = demodulate(child_association_map(association_id, reflection)[plural])\n source = demodulate(singular)\n\n if reflection.options[:conflicts].include? plural\n # XXX check this\n current_association = \"#{association_id._singularize}_#{current_association}\" if reflection.options[:conflicts].include? self.name.tableize.to_sym\n source = \"#{source}_as_#{association_id._singularize}\".to_sym\n end\n\n # make push/delete accessible from the individual collections but still operate via the general collection\n extension_module = self.class_eval %[\n module #{self.name + current_association._classify + \"PolymorphicChildAssociationExtension\"}\n def push *args; proxy_owner.send(:#{association_id}).send(:push, *args); self; end\n alias :<< :push\n def delete *args; proxy_owner.send(:#{association_id}).send(:delete, *args); end\n def clear; proxy_owner.send(:#{association_id}).send(:clear, #{singular._classify}); end\n self\n end]\n\n has_many(current_association.to_sym,\n :through => reflection.options[:through],\n :source => association_id._singularize,\n :source_type => plural._as_class.base_class.name,\n :class_name => plural._as_class.name, # make STI not conflate subtypes\n :extend => (Array(extension_module) + reflection.options[:extend]),\n :limit => reflection.options[:limit],\n # :offset => reflection.options[:offset],\n :order => devolve(association_id, reflection, reflection.options[:order], plural._as_class),\n :conditions => devolve(association_id, reflection, reflection.options[:conditions], plural._as_class),\n :group => devolve(association_id, reflection, reflection.options[:group], plural._as_class)\n )\n\n end\n end\n\n # some support methods\n\n def child_pluralization_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, plural._singularize]\n end.flatten]\n end\n\n def child_association_map(association_id, reflection)\n Hash[*reflection.options[:from].map do |plural|\n [plural, \"#{association_id._singularize.to_s + \"_\" if reflection.options[:rename_individual_collections]}#{plural}\".to_sym]\n end.flatten]\n end\n\n def demodulate(s)\n s.to_s.gsub('/', '_').to_sym\n end\n\n def build_join_table_symbol(association_id, name)\n [name.to_s, association_id.to_s].sort.join(\"_\").to_sym\n end\n\n def all_classes_for(association_id, reflection)\n klasses = [self, reflection.klass, *child_pluralization_map(association_id, reflection).keys.map(&:_as_class)]\n klasses += klasses.map(&:base_class)\n klasses.uniq\n end\n\n def devolve(association_id, reflection, string, klass, remove_inappropriate_clauses = false)\n # XXX remove_inappropriate_clauses is not implemented; we'll wait until someone actually needs it\n return unless string\n string = string.dup\n # _logger_debug \"devolving #{string} for #{klass}\"\n inappropriate_classes = (all_classes_for(association_id, reflection) - # the join class must always be preserved\n [klass, klass.base_class, reflection.klass, reflection.klass.base_class])\n inappropriate_classes.map do |klass|\n klass.columns.map do |column|\n [klass.table_name, column.name]\n end.map do |table, column|\n [\"#{table}.#{column}\", \"`#{table}`.#{column}\", \"#{table}.`#{column}`\", \"`#{table}`.`#{column}`\"]\n end\n end.flatten.sort_by(&:size).reverse.each do |quoted_reference|\n # _logger_debug \"devolved #{quoted_reference} to NULL\"\n # XXX clause removal would go here\n string.gsub!(quoted_reference, \"NULL\")\n end\n # _logger_debug \"altered to #{string}\"\n string\n end\n\n def verify_pluralization_of(sym)\n sym = sym.to_s\n singular = sym.singularize\n plural = singular.pluralize\n raise PolymorphicError, \"Pluralization rules not set up correctly. You passed :#{sym}, which singularizes to :#{singular}, but that pluralizes to :#{plural}, which is different. Maybe you meant :#{plural} to begin with?\" unless sym == plural\n end\n\n def spiked_create_extension_module(association_id, extensions, identifier = nil)\n module_extensions = extensions.select{|e| e.is_a? Module}\n proc_extensions = extensions.select{|e| e.is_a? Proc }\n\n # support namespaced anonymous blocks as well as multiple procs\n proc_extensions.each_with_index do |proc_extension, index|\n module_name = \"#{self.to_s}#{association_id._classify}Polymorphic#{identifier}AssociationExtension#{index}\"\n the_module = self.class_eval \"module #{module_name}; self; end\" # XXX hrm\n the_module.class_eval &proc_extension\n module_extensions << the_module\n end\n module_extensions\n end\n end\n end\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/reflection.rb", "file_before": "module ActiveRecord #:nodoc:\n module Reflection #:nodoc:\n \n module ClassMethods #:nodoc:\n \n # Update the default reflection switch so that :has_many_polymorphs types get instantiated. \n # It's not a composed method so we have to override the whole thing.\n def create_reflection(macro, name, options, active_record)\n case macro\n when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many\n klass = options[:through] ? ThroughReflection : AssociationReflection\n reflection = klass.new(macro, name, options, active_record)\n when :composed_of\n reflection = AggregateReflection.new(macro, name, options, active_record)\n # added by has_many_polymorphs #\n when :has_many_polymorphs\n reflection = PolymorphicReflection.new(macro, name, options, active_record)\n end\n write_inheritable_hash :reflections, name => reflection\n reflection\n end\n \n end\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n \n=begin rdoc\n\nThe reflection built by the has_many_polymorphs method. \n\nInherits from ActiveRecord::Reflection::AssociationReflection.\n\n=end\n\n class PolymorphicReflection < ThroughReflection\n # Stub out the validity check. Has_many_polymorphs checks validity on macro creation, not on reflection.\n def check_validity! \n # nothing\n end \n\n # Return the source reflection.\n def source_reflection\n # normally is the has_many to the through model, but we return ourselves, \n # since there isn't a real source class for a polymorphic target\n self\n end \n \n # Set the classname of the target. Uses the join class name.\n def class_name\n # normally is the classname of the association target\n @class_name ||= options[:join_class_name]\n end\n \n end\n \n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Reflection #:nodoc:\n\n module ClassMethods #:nodoc:\n\n # Update the default reflection switch so that :has_many_polymorphs types get instantiated.\n # It's not a composed method so we have to override the whole thing.\n def create_reflection(macro, name, options, active_record)\n case macro\n when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many\n klass = options[:through] ? ThroughReflection : AssociationReflection\n reflection = klass.new(macro, name, options, active_record)\n when :composed_of\n reflection = AggregateReflection.new(macro, name, options, active_record)\n # added by has_many_polymorphs #\n when :has_many_polymorphs\n reflection = PolymorphicReflection.new(macro, name, options, active_record)\n end\n write_inheritable_hash :reflections, name => reflection\n reflection\n end\n\n end\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n\n=begin rdoc\n\nThe reflection built by the has_many_polymorphs method.\n\nInherits from ActiveRecord::Reflection::AssociationReflection.\n\n=end\n\n class PolymorphicReflection < ThroughReflection\n # Stub out the validity check. Has_many_polymorphs checks validity on macro creation, not on reflection.\n def check_validity!\n # nothing\n end\n\n # Return the source reflection.\n def source_reflection\n # normally is the has_many to the through model, but we return ourselves,\n # since there isn't a real source class for a polymorphic target\n self\n end\n\n # Set the classname of the target. Uses the join class name.\n def class_name\n # normally is the classname of the association target\n @class_name ||= options[:join_class_name]\n end\n\n end\n\n end\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/association.rb", "file_before": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n \n class PolymorphicError < ActiveRecordError #:nodoc:\n end \n \n class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc:\n end\n \n # The association class for a has_many_polymorphs association.\n class PolymorphicAssociation < HasManyThroughAssociation\n\n # Push a record onto the association. Triggers a database load for a uniqueness check only if :skip_duplicates is true. Return value is undefined.\n def <<(*records)\n return if records.empty?\n\n if @reflection.options[:skip_duplicates]\n _logger_debug \"Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue\"\n load_target\n end\n \n @reflection.klass.transaction do\n flatten_deeper(records).each do |record|\n if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record?\n raise PolymorphicError, \"You can't associate unsaved records.\" \n end\n next if @reflection.options[:skip_duplicates] and @target.include? record\n @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record))\n @target << record if loaded?\n end\n end\n \n self\n end\n \n alias :push :<<\n alias :concat :<< \n \n # Runs a find against the association contents, returning the matched records. All regular find options except :include are supported.\n def find(*args)\n opts = args._extract_options!\n opts.delete :include\n super(*(args + [opts]))\n end \n \n def construct_scope\n _logger_warn \"Warning; not all usage scenarios for polymorphic scopes are supported yet.\"\n super\n end\n \n # Deletes a record from the association. Return value is undefined.\n def delete(*records)\n records = flatten_deeper(records)\n records.reject! {|record| @target.delete(record) if record.new_record?}\n return if records.empty?\n \n @reflection.klass.transaction do\n records.each do |record|\n joins = @reflection.through_reflection.name\n @owner.send(joins).delete(@owner.send(joins).select do |join|\n join.send(@reflection.options[:polymorphic_key]) == record.id and \n join.send(@reflection.options[:polymorphic_type_key]) == \"#{record.class.base_class}\"\n end)\n @target.delete(record)\n end\n end\n end\n \n # Clears all records from the association. Returns an empty array.\n def clear(klass = nil)\n load_target\n return if @target.empty?\n \n if klass\n delete(@target.select {|r| r.is_a? klass })\n else\n @owner.send(@reflection.through_reflection.name).clear\n @target.clear\n end\n []\n end\n \n protected\n\n# undef :sum\n# undef :create!\n\n def construct_quoted_owner_attributes(*args) #:nodoc:\n # no access to returning() here? why not?\n type_key = @reflection.options[:foreign_type_key]\n h = {@reflection.primary_key_name => @owner.id}\n h[type_key] = @owner.class.base_class.name if type_key\n h\n end\n\n def construct_from #:nodoc:\n # build the FROM part of the query, in this case, the polymorphic join table\n @reflection.klass.quoted_table_name\n end\n\n def construct_owner #:nodoc:\n # the table name for the owner object's class\n @owner.class.quoted_table_name\n end\n \n def construct_owner_key #:nodoc:\n # the primary key field for the owner object\n @owner.class.primary_key\n end\n\n def construct_select(custom_select = nil) #:nodoc:\n # build the select query\n selected = custom_select || @reflection.options[:select]\n end\n\n def construct_joins(custom_joins = nil) #:nodoc:\n # build the string of default joins\n \"JOIN #{construct_owner} AS polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} \" + \n @reflection.options[:from].map do |plural|\n klass = plural._as_class\n \"LEFT JOIN #{klass.quoted_table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.quoted_table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}\"\n end.uniq.join(\" \") + \" #{custom_joins}\"\n end\n\n def construct_conditions #:nodoc:\n # build the fully realized condition string\n conditions = construct_quoted_owner_attributes.map do |field, value|\n \"#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}\" if value\n end\n conditions << custom_conditions if custom_conditions\n \"(\" + conditions.compact.join(') AND (') + \")\"\n end\n\n def custom_conditions #:nodoc:\n # custom conditions... not as messy as has_many :through because our joins are a little smarter\n if @reflection.options[:conditions]\n \"(\" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + \")\"\n end\n end\n\n alias :construct_owner_attributes :construct_quoted_owner_attributes\n alias :conditions :custom_conditions # XXX possibly not necessary\n alias :sql_conditions :custom_conditions # XXX ditto \n\n # construct attributes for join for a particular record\n def construct_join_attributes(record) #:nodoc:\n {@reflection.options[:polymorphic_key] => record.id, \n @reflection.options[:polymorphic_type_key] => \"#{record.class.base_class}\", \n @reflection.options[:foreign_key] => @owner.id}.merge(@reflection.options[:foreign_type_key] ? \n {@reflection.options[:foreign_type_key] => \"#{@owner.class.base_class}\"} : {}) # for double-sided relationships\n end\n \n def build(attrs = nil) #:nodoc:\n raise PolymorphicMethodNotSupportedError, \"You can't associate new records.\"\n end \n\n end \n \n end\nend\n", "file_after": "module ActiveRecord #:nodoc:\n module Associations #:nodoc:\n\n class PolymorphicError < ActiveRecordError #:nodoc:\n end\n\n class PolymorphicMethodNotSupportedError < ActiveRecordError #:nodoc:\n end\n\n # The association class for a has_many_polymorphs association.\n class PolymorphicAssociation < HasManyThroughAssociation\n\n # Push a record onto the association. Triggers a database load for a uniqueness check only if :skip_duplicates is true. Return value is undefined.\n def <<(*records)\n return if records.empty?\n\n if @reflection.options[:skip_duplicates]\n _logger_debug \"Loading instances for polymorphic duplicate push check; use :skip_duplicates => false and perhaps a database constraint to avoid this possible performance issue\"\n load_target\n end\n\n @reflection.klass.transaction do\n flatten_deeper(records).each do |record|\n if @owner.new_record? or not record.respond_to?(:new_record?) or record.new_record?\n raise PolymorphicError, \"You can't associate unsaved records.\"\n end\n next if @reflection.options[:skip_duplicates] and @target.include? record\n @owner.send(@reflection.through_reflection.name).proxy_target << @reflection.klass.create!(construct_join_attributes(record))\n @target << record if loaded?\n end\n end\n\n self\n end\n\n alias :push :<<\n alias :concat :<<\n\n # Runs a find against the association contents, returning the matched records. All regular find options except :include are supported.\n def find(*args)\n opts = args._extract_options!\n opts.delete :include\n super(*(args + [opts]))\n end\n\n def construct_scope\n _logger_warn \"Warning; not all usage scenarios for polymorphic scopes are supported yet.\"\n super\n end\n\n # Deletes a record from the association. Return value is undefined.\n def delete(*records)\n records = flatten_deeper(records)\n records.reject! {|record| @target.delete(record) if record.new_record?}\n return if records.empty?\n\n @reflection.klass.transaction do\n records.each do |record|\n joins = @reflection.through_reflection.name\n @owner.send(joins).delete(@owner.send(joins).select do |join|\n join.send(@reflection.options[:polymorphic_key]) == record.id and\n join.send(@reflection.options[:polymorphic_type_key]) == \"#{record.class.base_class}\"\n end)\n @target.delete(record)\n end\n end\n end\n\n # Clears all records from the association. Returns an empty array.\n def clear(klass = nil)\n load_target\n return if @target.empty?\n\n if klass\n delete(@target.select {|r| r.is_a? klass })\n else\n @owner.send(@reflection.through_reflection.name).clear\n @target.clear\n end\n []\n end\n\n protected\n\n# undef :sum\n# undef :create!\n\n def construct_quoted_owner_attributes(*args) #:nodoc:\n # no access to returning() here? why not?\n type_key = @reflection.options[:foreign_type_key]\n h = {@reflection.primary_key_name => @owner.id}\n h[type_key] = @owner.class.base_class.name if type_key\n h\n end\n\n def construct_from #:nodoc:\n # build the FROM part of the query, in this case, the polymorphic join table\n @reflection.klass.quoted_table_name\n end\n\n def construct_owner #:nodoc:\n # the table name for the owner object's class\n @owner.class.quoted_table_name\n end\n\n def construct_owner_key #:nodoc:\n # the primary key field for the owner object\n @owner.class.primary_key\n end\n\n def construct_select(custom_select = nil) #:nodoc:\n # build the select query\n selected = custom_select || @reflection.options[:select]\n end\n\n def construct_joins(custom_joins = nil) #:nodoc:\n # build the string of default joins\n \"JOIN #{construct_owner} AS polymorphic_parent ON #{construct_from}.#{@reflection.options[:foreign_key]} = polymorphic_parent.#{construct_owner_key} \" +\n @reflection.options[:from].map do |plural|\n klass = plural._as_class\n \"LEFT JOIN #{klass.quoted_table_name} ON #{construct_from}.#{@reflection.options[:polymorphic_key]} = #{klass.quoted_table_name}.#{klass.primary_key} AND #{construct_from}.#{@reflection.options[:polymorphic_type_key]} = #{@reflection.klass.quote_value(klass.base_class.name)}\"\n end.uniq.join(\" \") + \" #{custom_joins}\"\n end\n\n def construct_conditions #:nodoc:\n # build the fully realized condition string\n conditions = construct_quoted_owner_attributes.map do |field, value|\n \"#{construct_from}.#{field} = #{@reflection.klass.quote_value(value)}\" if value\n end\n conditions << custom_conditions if custom_conditions\n \"(\" + conditions.compact.join(') AND (') + \")\"\n end\n\n def custom_conditions #:nodoc:\n # custom conditions... not as messy as has_many :through because our joins are a little smarter\n if @reflection.options[:conditions]\n \"(\" + interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) + \")\"\n end\n end\n\n alias :construct_owner_attributes :construct_quoted_owner_attributes\n alias :conditions :custom_conditions # XXX possibly not necessary\n alias :sql_conditions :custom_conditions # XXX ditto\n\n # construct attributes for join for a particular record\n def construct_join_attributes(record) #:nodoc:\n {\n @reflection.options[:polymorphic_key] => record.id,\n @reflection.options[:polymorphic_type_key] => \"#{record.class.base_class}\",\n @reflection.options[:foreign_key] => @owner.id\n }.merge(\n @reflection.options[:foreign_type_key] ?\n { @reflection.options[:foreign_type_key] => \"#{@owner.class.base_class}\" } :\n {}\n ) # for double-sided relationships\n end\n\n def build(attrs = nil) #:nodoc:\n raise PolymorphicMethodNotSupportedError, \"You can't associate new records.\"\n end\n\n end\n\n end\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs/support_methods.rb", "file_before": "\nclass String\n\n # Changes an underscored string into a class reference.\n def _as_class\n # classify expects self to be plural\n self.classify.constantize\n end\n\n # For compatibility with the Symbol extensions.\n alias :_singularize :singularize\n alias :_pluralize :pluralize\n alias :_classify :classify\nend\n\nclass Symbol\n \n # Changes an underscored symbol into a class reference.\n def _as_class; self.to_s._as_class; end\n \n # Changes a plural symbol into a singular symbol.\n def _singularize; self.to_s.singularize.to_sym; end\n\n # Changes a singular symbol into a plural symbol.\n def _pluralize; self.to_s.pluralize.to_sym; end\n\n # Changes a symbol into a class name string.\n def _classify; self.to_s.classify; end\nend\n\nclass Array\n\n # Flattens the first level of self.\n def _flatten_once\n self.inject([]){|r, el| r + Array(el)}\n end\n\n # Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217 \n def _extract_options!\n last.is_a?(::Hash) ? pop : {}\n end\nend\n\nclass Hash\n\n # An implementation of select that returns a Hash.\n def _select\n if RUBY_VERSION >= \"1.9\"\n Hash[*self.select {|k, v| yield k, v }.flatten]\n else\n Hash[*self.select do |key, value|\n yield key, value\n end._flatten_once]\n end\n end\nend\n\nclass Object\n\n # Returns the metaclass of self.\n def _metaclass; (class << self; self; end); end\n\n # Logger shortcut.\n def _logger_debug s\n s = \"** has_many_polymorphs: #{s}\"\n Rails.logger.debug(s) if Rails and Rails.logger\n end \n\n # Logger shortcut. \n def _logger_warn s\n s = \"** has_many_polymorphs: #{s}\"\n if Rails and Rails.logger\n Rails.logger.warn(s) \n else\n $stderr.puts(s)\n end \n end\n \nend\n\nclass ActiveRecord::Base\n\n # Return the base class name as a string.\n def _base_class_name\n self.class.base_class.name.to_s\n end\n \nend\n", "file_after": "\nclass String\n\n # Changes an underscored string into a class reference.\n def _as_class\n # classify expects self to be plural\n self.classify.constantize\n end\n\n # For compatibility with the Symbol extensions.\n alias :_singularize :singularize\n alias :_pluralize :pluralize\n alias :_classify :classify\nend\n\nclass Symbol\n\n # Changes an underscored symbol into a class reference.\n def _as_class; self.to_s._as_class; end\n\n # Changes a plural symbol into a singular symbol.\n def _singularize; self.to_s.singularize.to_sym; end\n\n # Changes a singular symbol into a plural symbol.\n def _pluralize; self.to_s.pluralize.to_sym; end\n\n # Changes a symbol into a class name string.\n def _classify; self.to_s.classify; end\nend\n\nclass Array\n\n # Flattens the first level of self.\n def _flatten_once\n self.inject([]){|r, el| r + Array(el)}\n end\n\n # Rails 1.2.3 compatibility method. Copied from http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/core_ext/array/extract_options.rb?rev=7217\n def _extract_options!\n last.is_a?(::Hash) ? pop : {}\n end\nend\n\nclass Hash\n\n # An implementation of select that returns a Hash.\n def _select\n if RUBY_VERSION >= \"1.9\"\n Hash[*self.select {|k, v| yield k, v }.flatten]\n else\n Hash[*self.select do |key, value|\n yield key, value\n end._flatten_once]\n end\n end\nend\n\nclass Object\n\n # Returns the metaclass of self.\n def _metaclass; (class << self; self; end); end\n\n # Logger shortcut.\n def _logger_debug s\n s = \"** has_many_polymorphs: #{s}\"\n Rails.logger.debug(s) if Rails and Rails.logger\n end\n\n # Logger shortcut.\n def _logger_warn s\n s = \"** has_many_polymorphs: #{s}\"\n if Rails and Rails.logger\n Rails.logger.warn(s)\n else\n $stderr.puts(s)\n end\n end\n\nend\n\nclass ActiveRecord::Base\n\n # Return the base class name as a string.\n def _base_class_name\n self.class.base_class.name.to_s\n end\n\nend\n"} -{"repo": "jystewart/has_many_polymorphs", "pr_number": 1, "filename": "lib/has_many_polymorphs.rb", "file_before": "require 'active_record'\nrequire 'has_many_polymorphs/reflection'\nrequire 'has_many_polymorphs/association'\nrequire 'has_many_polymorphs/class_methods'\n\nrequire 'has_many_polymorphs/support_methods'\nrequire 'has_many_polymorphs/base'\n\nclass ActiveRecord::Base\n extend ActiveRecord::Associations::PolymorphicClassMethods \nend\n\nif ENV['HMP_DEBUG'] || (Rails.env.development? || Rails.env.test?) && ENV['USER'] == 'eweaver'\n require 'has_many_polymorphs/debugging_tools' \nend\n\nrequire 'has_many_polymorphs/railtie'\n\n_logger_debug \"loaded ok\"\n", "file_after": "require 'active_record'\nrequire 'has_many_polymorphs/reflection'\nrequire 'has_many_polymorphs/association'\nrequire 'has_many_polymorphs/class_methods'\n\nrequire 'has_many_polymorphs/support_methods'\nrequire 'has_many_polymorphs/base'\n\nclass ActiveRecord::Base\n extend ActiveRecord::Associations::PolymorphicClassMethods\nend\n\nif ENV['HMP_DEBUG'] && (Rails.env.development? || Rails.env.test?)\n require 'has_many_polymorphs/debugging_tools'\nend\n\nrequire 'has_many_polymorphs/railtie'\n\n_logger_debug \"loaded ok\"\n"} -{"repo": "colbygk/log4r", "pr_number": 57, "filename": "lib/log4r/yamlconfigurator.rb", "file_before": "# :include: rdoc/yamlconfigurator\n#\n# == Other Info\n#\n# Version: $Id$\n\nrequire \"log4r/logger\"\nrequire \"log4r/outputter/staticoutputter\"\nrequire \"log4r/logserver\"\nrequire \"log4r/outputter/remoteoutputter\"\n\nrequire 'yaml'\n\nmodule Log4r\n # Gets raised when Configurator encounters bad YAML.\n class ConfigError < Exception\n end\n\n # See log4r/yamlconfigurator.rb\n class YamlConfigurator\n @@params = Hash.new\n\n # Get a parameter's value\n def self.[](param); @@params[param] end\n # Define a parameter with a value\n def self.[]=(param, value); @@params[param] = value end\n\n\n def self.custom_levels( levels)\n return Logger.root if levels.size == 0\n for i in 0...levels.size\n name = levels[i].to_s\n if name =~ /\\s/ or name !~ /^[A-Z]/\n raise TypeError, \"#{name} is not a valid Ruby Constant name\", caller\n end\n end\n Log4r.define_levels *levels\n end\n\n # Given a filename, loads the YAML configuration for Log4r.\n def self.load_yaml_file( filename)\n actual_load( File.open( filename))\n end\n\n # You can load a String YAML configuration instead of a file.\n def self.load_yaml_string( string)\n actual_load( string)\n end\n\n #######\n private\n #######\n\n def self.actual_load( yaml_docs)\n log4r_config = nil\n YAML.load_documents( yaml_docs){ |doc|\n doc.has_key?( 'log4r_config') and log4r_config = doc['log4r_config'] and break\n }\n if log4r_config.nil?\n raise ConfigError, \n \"Key 'log4r_config:' not defined in yaml documents\", caller[1..-1]\n end\n decode_yaml( log4r_config)\n end\n \n def self.decode_yaml( cfg)\n decode_pre_config( cfg['pre_config'])\n cfg['outputters'].each{ |op| decode_outputter( op)}\n cfg['loggers'].each{ |lo| decode_logger( lo)}\n cfg['logserver'].each{ |lo| decode_logserver( lo)} unless cfg['logserver'].nil?\n end\n\n def self.decode_pre_config( pre)\n return Logger.root if pre.nil?\n decode_custom_levels( pre['custom_levels'])\n global_config( pre['global'])\n global_config( pre['root'])\n decode_parameters( pre['parameters'])\n end\n\n def self.decode_custom_levels( levels)\n return Logger.root if levels.nil?\n begin custom_levels( levels)\n rescue TypeError => te\n raise ConfigError, te.message, caller[1..-4]\n end\n end\n \n def self.global_config( e)\n return if e.nil?\n globlev = e['level']\n return if globlev.nil?\n lev = LNAMES.index(globlev) # find value in LNAMES\n Log4rTools.validate_level(lev, 4) # choke on bad level\n Logger.global.level = lev\n end\n\n def self.decode_parameters( params)\n params.each{ |p| @@params[p['name']] = p['value']} unless params.nil?\n end\n\n def self.decode_outputter( op)\n # fields\n name = op['name']\n type = op['type']\n level = op['level']\n only_at = op['only_at']\n # validation\n raise ConfigError, \"Outputter missing name\", caller[1..-3] if name.nil?\n raise ConfigError, \"Outputter missing type\", caller[1..-3] if type.nil?\n Log4rTools.validate_level(LNAMES.index(level)) unless level.nil?\n only_levels = []\n unless only_at.nil?\n for lev in only_at\n alev = LNAMES.index(lev)\n Log4rTools.validate_level(alev, 3)\n only_levels.push alev\n end\n end\n\n formatter = decode_formatter( op['formatter'])\n\n opts = {}\n opts[:level] = LNAMES.index(level) unless level.nil?\n opts[:formatter] = formatter unless formatter.nil?\n opts.merge!(decode_hash_params(op))\n begin\n Outputter[name] = Log4r.const_get(type).new name, opts\n rescue Exception => ae\n raise ConfigError, \n \"Problem creating outputter: #{ae.message}\", caller[1..-3]\n end\n Outputter[name].only_at( *only_levels) if only_levels.size > 0\n Outputter[name]\n end\n\n def self.decode_formatter( fo)\n return nil if fo.nil?\n type = fo['type'] \n raise ConfigError, \"Formatter missing type\", caller[1..-4] if type.nil?\n begin\n return Log4r.const_get(type).new(decode_hash_params(fo))\n rescue Exception => ae\n raise ConfigError,\n \"Problem creating outputter: #{ae.message}\", caller[1..-4]\n end\n end\n\n ExcludeParams = %w{formatter level name type only_at}\n\n # Does the fancy parameter to hash argument transformation\n def self.decode_hash_params(ph)\n case ph\n when Hash\n ph.inject({}){|a,(k,v)| a[k] = self.decode_hash_params(v); a}\n when Array\n ph.map{|v| self.decode_hash_params(v)}\n when String\n self.paramsub(ph)\n else\n ph\n end\n end\n\n # Substitues any #{foo} in the YAML with Parameter['foo']\n def self.paramsub(str)\n @@params.each {|param, value|\n str = str.sub(\"\\#{#{param}}\", value)\n }\n str\n end\n\n def self.decode_logger( lo)\n l = Logger.new lo['name']\n decode_logger_common( l, lo)\n end\n\n def self.decode_logserver( lo)\n name = lo['name']\n uri = lo['uri']\n l = LogServer.new name, uri\n decode_logger_common(l, lo)\n end\n\n def self.decode_logger_common( l, lo)\n level = lo['level']\n additive = lo['additive']\n trace = lo['trace']\n l.level = LNAMES.index( level) unless level.nil?\n l.additive = additive unless additive.nil?\n l.trace = trace unless trace.nil?\n # and now for outputters\n outs = lo['outputters']\n outs.each {|n| l.add n.strip} unless outs.nil?\n end\n end\nend\n\n", "file_after": "# :include: rdoc/yamlconfigurator\n#\n# == Other Info\n#\n# Version: $Id$\n\nrequire \"log4r/logger\"\nrequire \"log4r/outputter/staticoutputter\"\nrequire \"log4r/logserver\"\nrequire \"log4r/outputter/remoteoutputter\"\n\nrequire 'yaml'\n\nmodule Log4r\n # Gets raised when Configurator encounters bad YAML.\n class ConfigError < Exception\n end\n\n # See log4r/yamlconfigurator.rb\n class YamlConfigurator\n @@params = Hash.new\n\n # Get a parameter's value\n def self.[](param); @@params[param] end\n # Define a parameter with a value\n def self.[]=(param, value); @@params[param] = value end\n\n\n def self.custom_levels( levels)\n return Logger.root if levels.size == 0\n for i in 0...levels.size\n name = levels[i].to_s\n if name =~ /\\s/ or name !~ /^[A-Z]/\n raise TypeError, \"#{name} is not a valid Ruby Constant name\", caller\n end\n end\n Log4r.define_levels *levels\n end\n\n # Given a filename, loads the YAML configuration for Log4r.\n def self.load_yaml_file( filename)\n actual_load( File.open( filename))\n end\n\n # You can load a String YAML configuration instead of a file.\n def self.load_yaml_string( string)\n actual_load( string)\n end\n\n #######\n private\n #######\n\n def self.actual_load( yaml_docs)\n log4r_config = nil\n YAML.load_stream( yaml_docs){ |doc|\n doc.has_key?( 'log4r_config') and log4r_config = doc['log4r_config'] and break\n }\n if log4r_config.nil?\n raise ConfigError, \n \"Key 'log4r_config:' not defined in yaml documents\", caller[1..-1]\n end\n decode_yaml( log4r_config)\n end\n \n def self.decode_yaml( cfg)\n decode_pre_config( cfg['pre_config'])\n cfg['outputters'].each{ |op| decode_outputter( op)}\n cfg['loggers'].each{ |lo| decode_logger( lo)}\n cfg['logserver'].each{ |lo| decode_logserver( lo)} unless cfg['logserver'].nil?\n end\n\n def self.decode_pre_config( pre)\n return Logger.root if pre.nil?\n decode_custom_levels( pre['custom_levels'])\n global_config( pre['global'])\n global_config( pre['root'])\n decode_parameters( pre['parameters'])\n end\n\n def self.decode_custom_levels( levels)\n return Logger.root if levels.nil?\n begin custom_levels( levels)\n rescue TypeError => te\n raise ConfigError, te.message, caller[1..-4]\n end\n end\n \n def self.global_config( e)\n return if e.nil?\n globlev = e['level']\n return if globlev.nil?\n lev = LNAMES.index(globlev) # find value in LNAMES\n Log4rTools.validate_level(lev, 4) # choke on bad level\n Logger.global.level = lev\n end\n\n def self.decode_parameters( params)\n params.each{ |p| @@params[p['name']] = p['value']} unless params.nil?\n end\n\n def self.decode_outputter( op)\n # fields\n name = op['name']\n type = op['type']\n level = op['level']\n only_at = op['only_at']\n # validation\n raise ConfigError, \"Outputter missing name\", caller[1..-3] if name.nil?\n raise ConfigError, \"Outputter missing type\", caller[1..-3] if type.nil?\n Log4rTools.validate_level(LNAMES.index(level)) unless level.nil?\n only_levels = []\n unless only_at.nil?\n for lev in only_at\n alev = LNAMES.index(lev)\n Log4rTools.validate_level(alev, 3)\n only_levels.push alev\n end\n end\n\n formatter = decode_formatter( op['formatter'])\n\n opts = {}\n opts[:level] = LNAMES.index(level) unless level.nil?\n opts[:formatter] = formatter unless formatter.nil?\n opts.merge!(decode_hash_params(op))\n begin\n Outputter[name] = Log4r.const_get(type).new name, opts\n rescue Exception => ae\n raise ConfigError, \n \"Problem creating outputter: #{ae.message}\", caller[1..-3]\n end\n Outputter[name].only_at( *only_levels) if only_levels.size > 0\n Outputter[name]\n end\n\n def self.decode_formatter( fo)\n return nil if fo.nil?\n type = fo['type'] \n raise ConfigError, \"Formatter missing type\", caller[1..-4] if type.nil?\n begin\n return Log4r.const_get(type).new(decode_hash_params(fo))\n rescue Exception => ae\n raise ConfigError,\n \"Problem creating outputter: #{ae.message}\", caller[1..-4]\n end\n end\n\n ExcludeParams = %w{formatter level name type only_at}\n\n # Does the fancy parameter to hash argument transformation\n def self.decode_hash_params(ph)\n case ph\n when Hash\n ph.inject({}){|a,(k,v)| a[k] = self.decode_hash_params(v); a}\n when Array\n ph.map{|v| self.decode_hash_params(v)}\n when String\n self.paramsub(ph)\n else\n ph\n end\n end\n\n # Substitues any #{foo} in the YAML with Parameter['foo']\n def self.paramsub(str)\n @@params.each {|param, value|\n str = str.sub(\"\\#{#{param}}\", value)\n }\n str\n end\n\n def self.decode_logger( lo)\n l = Logger.new lo['name']\n decode_logger_common( l, lo)\n end\n\n def self.decode_logserver( lo)\n name = lo['name']\n uri = lo['uri']\n l = LogServer.new name, uri\n decode_logger_common(l, lo)\n end\n\n def self.decode_logger_common( l, lo)\n level = lo['level']\n additive = lo['additive']\n trace = lo['trace']\n l.level = LNAMES.index( level) unless level.nil?\n l.additive = additive unless additive.nil?\n l.trace = trace unless trace.nil?\n # and now for outputters\n outs = lo['outputters']\n outs.each {|n| l.add n.strip} unless outs.nil?\n end\n end\nend\n\n"} -{"repo": "shokai/ImageResize-ruby", "pr_number": 2, "filename": "lib/ImageResize/Image.rb", "file_before": "module Image\n\n $VERBOSE = nil\n \n def Image.cmd\n jar_path = File.expand_path(File.dirname(__FILE__)).split(/\\//)\n jar_path.pop\n jar_path.pop\n resizer = \"#{jar_path.join('/')}/java/ImageResize.jar\"\n \"java -jar #{resizer}\"\n end\n \n def Image.resize(img_in, img_out, width, height)\n puts `#{Image.cmd} resize #{img_in} #{img_out} #{width} #{height}`\n end\n\n def Image.formats\n lines = `#{Image.cmd} formats`\n read_formats = nil\n write_formats = nil\n for line in lines.split(/[\\r\\n]/) do\n rw, format = line.split(/\\:/)\n formats = format.split(/,/).map{|f|f.downcase}.uniq.sort\n if rw == 'read'\n read_formats = formats\n elsif rw == 'write'\n write_formats = formats\n end\n end\n return read_formats, write_formats\n end\n\n def Image.read_formats\n r,w = Image.formats\n r\n end\n \n def Image.write_formats\n r,w = Image.formats\n w\n end\n \nend\n", "file_after": "module Image\n\n $VERBOSE = nil\n \n def Image.cmd\n jar_path = File.expand_path(File.dirname(__FILE__)).split(/\\//)\n jar_path.pop\n jar_path.pop\n resizer = \"#{jar_path.join('/')}/java/ImageResize.jar\"\n \"java -jar #{resizer}\"\n end\n \n def Image.resize(img_in, img_out, width, height)\n puts `#{Image.cmd} resize \"#{img_in}\" \"#{img_out}\" #{width} #{height}`\n end\n\n def Image.formats\n lines = `#{Image.cmd} formats`\n read_formats = nil\n write_formats = nil\n for line in lines.split(/[\\r\\n]/) do\n rw, format = line.split(/\\:/)\n formats = format.split(/,/).map{|f|f.downcase}.uniq.sort\n if rw == 'read'\n read_formats = formats\n elsif rw == 'write'\n write_formats = formats\n end\n end\n return read_formats, write_formats\n end\n\n def Image.read_formats\n r,w = Image.formats\n r\n end\n \n def Image.write_formats\n r,w = Image.formats\n w\n end\n \nend\n"} -{"repo": "defunkt/choice", "pr_number": 17, "filename": "lib/choice/lazyhash.rb", "file_before": "module Choice\n\n # This class lets us get away with really bad, horrible, lazy hash accessing.\n # Like so:\n # hash = LazyHash.new\n # hash[:someplace] = \"somewhere\"\n # puts hash[:someplace]\n # puts hash['someplace']\n # puts hash.someplace\n #\n # If you'd like, you can pass in a current hash when initializing to convert\n # it into a lazyhash. Or you can use the .to_lazyhash method attached to the\n # Hash object (evil!).\n class LazyHash < Hash\n\n # Keep the old methods around.\n alias_method :old_store, :store\n alias_method :old_fetch, :fetch\n\n # You can pass in a normal hash to convert it to a LazyHash.\n def initialize(hash = nil)\n hash.each { |key, value| self[key] = value } if !hash.nil? && hash.is_a?(Hash)\n end\n\n # Wrapper for []\n def store(key, value)\n self[key] = value\n end\n\n # Wrapper for []=\n def fetch(key)\n self[key]\n end\n\n # Store every key as a string.\n def []=(key, value)\n key = key.to_s if key.is_a? Symbol\n self.old_store(key, value)\n end\n\n # Every key is stored as a string. Like a normal hash, nil is returned if\n # the key does not exist.\n def [](key)\n key = key.to_s if key.is_a? Symbol\n self.old_fetch(key) rescue return nil\n end\n\n # You can use hash.something or hash.something = 'thing' since this is\n # truly a lazy hash.\n def method_missing(meth, *args)\n meth = meth.to_s\n if meth =~ /=/\n self[meth.sub('=','')] = args.first\n else\n self[meth]\n end\n end\n\n end\nend\n\n# Really ugly, horrible, extremely fun hack.\nclass Hash #:nodoc:\n def to_lazyhash\n return Choice::LazyHash.new(self)\n end\nend\n", "file_after": "module Choice\n\n # This class lets us get away with really bad, horrible, lazy hash accessing.\n # Like so:\n # hash = LazyHash.new\n # hash[:someplace] = \"somewhere\"\n # puts hash[:someplace]\n # puts hash['someplace']\n # puts hash.someplace\n #\n # If you'd like, you can pass in a current hash when initializing to convert\n # it into a lazyhash. Or you can use the .to_lazyhash method attached to the\n # Hash object (evil!).\n class LazyHash < Hash\n\n # Keep the old methods around.\n alias_method :old_store, :store\n alias_method :old_fetch, :fetch\n\n # You can pass in a normal hash to convert it to a LazyHash.\n def initialize(hash = nil)\n hash.each { |key, value| self[key] = value } if hash && hash.is_a?(Hash)\n end\n\n # Wrapper for []\n def store(key, value)\n self[key] = value\n end\n\n # Wrapper for []=\n def fetch(key)\n self[key]\n end\n\n # Store every key as a string.\n def []=(key, value)\n key = key.to_s if key.is_a?(Symbol)\n old_store(key, value)\n end\n\n # Every key is stored as a string. Like a normal hash, nil is returned if\n # the key does not exist.\n def [](key)\n key = key.to_s if key.is_a?(Symbol)\n old_fetch(key) rescue return nil\n end\n\n # You can use hash.something or hash.something = 'thing' since this is\n # truly a lazy hash.\n def method_missing(meth, *args)\n meth = meth.to_s\n if meth =~ /=/\n self[meth.sub('=', '')] = args.first\n else\n self[meth]\n end\n end\n\n end\nend\n\n# Really ugly, horrible, extremely fun hack.\nclass Hash #:nodoc:\n def to_lazyhash\n Choice::LazyHash.new(self)\n end\nend\n"} +version https://git-lfs.github.com/spec/v1 +oid sha256:402ce0a8a5f15e5868512e08631d2aedf758c5c748b12d62f2fe6120ca610cda +size 11590572