KXStudio Website https://kx.studio/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2443 lines
116KB

  1. <?php
  2. /**
  3. * Class: Admin Controller
  4. * The logic behind the Admin area.
  5. */
  6. class AdminController {
  7. # Boolean: $displayed
  8. # Has anything been displayed?
  9. public $displayed = false;
  10. # Array: $context
  11. # Contains the context for various admin pages, to be passed to the Twig templates.
  12. public $context = array();
  13. # String: $selected_bookmarklet
  14. # Holds the name of the Feather to be selected when they open the bookmarklet.
  15. public $selected_bookmarklet;
  16. # String: $base
  17. # The base path for this controller.
  18. public $base = "admin";
  19. # Boolean: $feed
  20. # Is the current page a feed?
  21. public $feed = false;
  22. /**
  23. * Function: __construct
  24. * Prepares Twig.
  25. */
  26. private function __construct() {
  27. $this->admin_theme = fallback($_SESSION['admin_theme'], "default");
  28. $this->theme = new Twig_Loader(MAIN_DIR."/admin/themes/".$this->admin_theme,
  29. (is_writable(INCLUDES_DIR."/caches") and !DEBUG) ?
  30. INCLUDES_DIR."/caches" :
  31. null);
  32. $this->default = new Twig_Loader(MAIN_DIR."/admin/themes/default",
  33. (is_writable(INCLUDES_DIR."/caches") and !DEBUG) ?
  34. INCLUDES_DIR."/caches" :
  35. null);
  36. }
  37. /**
  38. * Function: parse
  39. * Determines the action.
  40. */
  41. public function parse($route) {
  42. $visitor = Visitor::current();
  43. # Protect non-responder functions.
  44. if (in_array($route->action, array("__construct", "parse", "subnav_context", "display", "current")))
  45. show_404();
  46. if (empty($route->action) or $route->action == "write") {
  47. # "Write > Post", if they can add posts or drafts.
  48. if (($visitor->group->can("add_post") or $visitor->group->can("add_draft")) and
  49. !empty(Config::current()->enabled_feathers))
  50. return $route->action = "write_post";
  51. # "Write > Page", if they can add pages.
  52. if ($visitor->group->can("add_page"))
  53. return $route->action = "write_page";
  54. }
  55. if (empty($route->action) or $route->action == "manage") {
  56. # "Manage > Posts", if they can manage any posts.
  57. if (Post::any_editable() or Post::any_deletable())
  58. return $route->action = "manage_posts";
  59. # "Manage > Pages", if they can manage pages.
  60. if ($visitor->group->can("edit_page") or $visitor->group->can("delete_page"))
  61. return $route->action = "manage_pages";
  62. # "Manage > Users", if they can manage users.
  63. if ($visitor->group->can("edit_user") or $visitor->group->can("delete_user"))
  64. return $route->action = "manage_users";
  65. # "Manage > Groups", if they can manage groups.
  66. if ($visitor->group->can("edit_group") or $visitor->group->can("delete_group"))
  67. return $route->action = "manage_groups";
  68. }
  69. if (empty($route->action) or $route->action == "settings") {
  70. # "General Settings", if they can configure the installation.
  71. if ($visitor->group->can("change_settings"))
  72. return $route->action = "general_settings";
  73. }
  74. if (empty($route->action) or $route->action == "extend") {
  75. # "Modules", if they can configure the installation.
  76. if ($visitor->group->can("toggle_extensions"))
  77. return $route->action = "modules";
  78. }
  79. Trigger::current()->filter($route->action, "admin_determine_action");
  80. if (!isset($route->action))
  81. show_403(__("Access Denied"), __("You do not have sufficient privileges to view this area."));
  82. }
  83. /**
  84. * Function: write
  85. * Post writing.
  86. */
  87. public function write_post() {
  88. $visitor = Visitor::current();
  89. if (!$visitor->group->can("add_post", "add_draft"))
  90. show_403(__("Access Denied"), __("You do not have sufficient privileges to create posts."));
  91. $config = Config::current();
  92. if (empty($config->enabled_feathers))
  93. error(__("No Feathers"), __("Please install a feather or two in order to add a post."));
  94. Trigger::current()->filter($options, array("write_post_options", "post_options"));
  95. fallback($_GET['feather'], reset($config->enabled_feathers));
  96. $this->display("write_post",
  97. array("groups" => Group::find(array("order" => "id ASC")),
  98. "options" => $options,
  99. "feathers" => Feathers::$instances,
  100. "feather" => Feathers::$instances[$_GET['feather']]));
  101. }
  102. /**
  103. * Function: bookmarklet
  104. * Post writing, from the bookmarklet.
  105. */
  106. public function bookmarklet() {
  107. $visitor = Visitor::current();
  108. if (!$visitor->group->can("add_post", "add_draft"))
  109. show_403(__("Access Denied"), __("You do not have sufficient privileges to create posts."));
  110. $config = Config::current();
  111. if (empty($config->enabled_feathers))
  112. error(__("No Feathers"), __("Please install a feather or two in order to add a post."));
  113. if (!isset($this->selected_bookmarklet))
  114. fallback($feather, $config->enabled_feathers[0]);
  115. else
  116. $feather = $this->selected_bookmarklet;
  117. fallback($_GET['url']);
  118. fallback($_GET['title']);
  119. fallback($_GET['selection']);
  120. $this->display("bookmarklet",
  121. array("done" => isset($_GET['done']),
  122. "feathers" => Feathers::$instances,
  123. "selected_feather" => Feathers::$instances[$feather],
  124. "args" => array("url" => stripslashes($_GET['url']),
  125. "page_url" => stripslashes($_GET['url']),
  126. "page_link" => '(via <a href="'.stripslashes($_GET['url']).'">'.$_GET['title'].'</a>)',
  127. "title" => stripslashes($_GET['title']),
  128. "page_title" => stripslashes($_GET['title']),
  129. "selection" => stripslashes($_GET['selection']))));
  130. }
  131. /**
  132. * Function: add_post
  133. * Adds a post when the form is submitted.
  134. */
  135. public function add_post() {
  136. $visitor = Visitor::current();
  137. if (!$visitor->group->can("add_post", "add_draft"))
  138. show_403(__("Access Denied"), __("You do not have sufficient privileges to create posts."));
  139. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  140. show_403(__("Access Denied"), __("Invalid security key."));
  141. if (!isset($_POST['draft']) and !$visitor->group->can("add_post"))
  142. $_POST['draft'] = 'true';
  143. $post = Feathers::$instances[$_POST['feather']]->submit();
  144. if (!$post->redirect)
  145. $post->redirect = "/admin/?action=write_post";
  146. if (!isset($_POST['bookmarklet']))
  147. Flash::notice(__("Post created!"), $post->redirect);
  148. else
  149. redirect($post->redirect);
  150. }
  151. /**
  152. * Function: edit_post
  153. * Post editing.
  154. */
  155. public function edit_post() {
  156. if (empty($_GET['id']))
  157. error(__("No ID Specified"), __("An ID is required to edit a post."));
  158. $post = new Post($_GET['id'], array("drafts" => true, "filter" => false));
  159. if (!$post->editable())
  160. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit this post."));
  161. Trigger::current()->filter($options, array("edit_post_options", "post_options"), $post);
  162. $this->display("edit_post",
  163. array("post" => $post,
  164. "groups" => Group::find(array("order" => "id ASC")),
  165. "options" => $options,
  166. "feather" => Feathers::$instances[$post->feather]));
  167. }
  168. /**
  169. * Function: update_post
  170. * Updates a post when the form is submitted.
  171. */
  172. public function update_post() {
  173. $post = new Post($_POST['id'], array("drafts" => true));
  174. if ($post->no_results)
  175. Flash::warning(__("Post not found."), "/admin/?action=manage_posts");
  176. if (!$post->editable())
  177. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit this post."));
  178. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  179. show_403(__("Access Denied"), __("Invalid security key."));
  180. Feathers::$instances[$post->feather]->update($post);
  181. if (!isset($_POST['ajax']))
  182. Flash::notice(_f("Post updated. <a href=\"%s\">View Post &rarr;</a>",
  183. array($post->url())),
  184. "/admin/?action=manage_posts");
  185. else
  186. exit((string) $_POST['id']);
  187. }
  188. /**
  189. * Function: delete_post
  190. * Post deletion (confirm page).
  191. */
  192. public function delete_post() {
  193. if (empty($_GET['id']))
  194. error(__("No ID Specified"), __("An ID is required to delete a post."));
  195. $post = new Post($_GET['id'], array("drafts" => true));
  196. if (!$post->deletable())
  197. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete this post."));
  198. $this->display("delete_post", array("post" => $post));
  199. }
  200. /**
  201. * Function: destroy_post
  202. * Destroys a post (the real deal).
  203. */
  204. public function destroy_post() {
  205. if (empty($_POST['id']))
  206. error(__("No ID Specified"), __("An ID is required to delete a post."));
  207. if ($_POST['destroy'] == "bollocks")
  208. redirect("/admin/?action=manage_posts");
  209. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  210. show_403(__("Access Denied"), __("Invalid security key."));
  211. $post = new Post($_POST['id'], array("drafts" => true));
  212. if (!$post->deletable())
  213. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete this post."));
  214. Post::delete($_POST['id']);
  215. Flash::notice(__("Post deleted."), "/admin/?action=manage_posts");
  216. }
  217. /**
  218. * Function: manage_posts
  219. * Post managing.
  220. */
  221. public function manage_posts() {
  222. if (!Post::any_editable() and !Post::any_deletable())
  223. show_403(__("Access Denied"), __("You do not have sufficient privileges to manage any posts."));
  224. fallback($_GET['query'], "");
  225. list($where, $params) = keywords($_GET['query'], "post_attributes.value LIKE :query OR url LIKE :query", "post_attributes");
  226. if (!empty($_GET['month']))
  227. $where["created_at like"] = $_GET['month']."-%";
  228. $visitor = Visitor::current();
  229. if (!$visitor->group->can("view_draft", "edit_draft", "edit_post", "delete_draft", "delete_post"))
  230. $where["user_id"] = $visitor->id;
  231. $results = Post::find(array("placeholders" => true,
  232. "drafts" => true,
  233. "where" => $where,
  234. "params" => $params));
  235. $ids = array();
  236. foreach ($results[0] as $result)
  237. $ids[] = $result["id"];
  238. if (!empty($ids))
  239. $posts = new Paginator(Post::find(array("placeholders" => true,
  240. "drafts" => true,
  241. "where" => array("id" => $ids))),
  242. 25);
  243. else
  244. $posts = new Paginator(array());
  245. foreach ($posts->paginated as &$post) {
  246. if (preg_match_all("/\{([0-9]+)\}/", $post->status, $matches)) {
  247. $groups = array();
  248. $groupClasses = array();
  249. foreach ($matches[1] as $id) {
  250. $group = new Group($id);
  251. $groups[] = "<span class=\"group_prefix\">Group:</span> ".$group->name;
  252. $groupClasses[] = "group-".$id;
  253. }
  254. $post->status_name = join(", ", $groups);
  255. $post->status_class = join(" ", $groupClasses);
  256. } else {
  257. $post->status_name = camelize($post->status, true);
  258. $post->status_class = $post->status;
  259. }
  260. }
  261. $this->display("manage_posts", array("posts" => $posts));
  262. }
  263. /**
  264. * Function: write_page
  265. * Page creation.
  266. */
  267. public function write_page() {
  268. if (!Visitor::current()->group->can("add_page"))
  269. show_403(__("Access Denied"), __("You do not have sufficient privileges to create pages."));
  270. $this->display("write_page", array("pages" => Page::find()));
  271. }
  272. /**
  273. * Function: add_page
  274. * Adds a page when the form is submitted.
  275. */
  276. public function add_page() {
  277. if (!Visitor::current()->group->can("add_page"))
  278. show_403(__("Access Denied"), __("You do not have sufficient privileges to create pages."));
  279. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  280. show_403(__("Access Denied"), __("Invalid security key."));
  281. if (empty($_POST['title']) and empty($_POST['slug']))
  282. error(__("Error"), __("Title and slug cannot be blank."));
  283. $page = Page::add($_POST['title'],
  284. $_POST['body'],
  285. null,
  286. $_POST['parent_id'],
  287. !empty($_POST['show_in_list']),
  288. 0,
  289. (!empty($_POST['slug']) ? $_POST['slug'] : sanitize($_POST['title'])));
  290. Flash::notice(__("Page created!"), $page->url());
  291. }
  292. /**
  293. * Function: edit_page
  294. * Page editing.
  295. */
  296. public function edit_page() {
  297. if (!Visitor::current()->group->can("edit_page"))
  298. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit this page."));
  299. if (empty($_GET['id']))
  300. error(__("No ID Specified"), __("An ID is required to edit a page."));
  301. $this->display("edit_page",
  302. array("page" => new Page($_GET['id'], array("filter" => false)),
  303. "pages" => Page::find(array("where" => array("id not" => $_GET['id'])))));
  304. }
  305. /**
  306. * Function: update_page
  307. * Updates a page when the form is submitted.
  308. */
  309. public function update_page() {
  310. if (!Visitor::current()->group->can("edit_page"))
  311. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit pages."));
  312. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  313. show_403(__("Access Denied"), __("Invalid security key."));
  314. if (empty($_POST['title']) and empty($_POST['slug']))
  315. error(__("Error"), __("Title and slug cannot be blank."));
  316. $page = new Page($_POST['id']);
  317. if ($page->no_results)
  318. Flash::warning(__("Page not found."), "/admin/?action=manage_pages");
  319. $page->update($_POST['title'], $_POST['body'], null, $_POST['parent_id'], !empty($_POST['show_in_list']), $page->list_order, null, $_POST['slug']);
  320. if (!isset($_POST['ajax']))
  321. Flash::notice(_f("Page updated. <a href=\"%s\">View Page &rarr;</a>",
  322. array($page->url())),
  323. "/admin/?action=manage_pages");
  324. }
  325. /**
  326. * Function: reorder_pages
  327. * Reorders pages.
  328. */
  329. public function reorder_pages() {
  330. foreach ($_POST['list_order'] as $id => $order) {
  331. $page = new Page($id);
  332. $page->update($page->title, $page->body, null, $page->parent_id, $page->show_in_list, $order, null, $page->url);
  333. }
  334. Flash::notice(__("Pages reordered."), "/admin/?action=manage_pages");
  335. }
  336. /**
  337. * Function: delete_page
  338. * Page deletion (confirm page).
  339. */
  340. public function delete_page() {
  341. if (!Visitor::current()->group->can("delete_page"))
  342. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete pages."));
  343. if (empty($_GET['id']))
  344. error(__("No ID Specified"), __("An ID is required to delete a page."));
  345. $this->display("delete_page", array("page" => new Page($_GET['id'])));
  346. }
  347. /**
  348. * Function: destroy_page
  349. * Destroys a page.
  350. */
  351. public function destroy_page() {
  352. if (!Visitor::current()->group->can("delete_page"))
  353. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete pages."));
  354. if (empty($_POST['id']))
  355. error(__("No ID Specified"), __("An ID is required to delete a post."));
  356. if ($_POST['destroy'] == "bollocks")
  357. redirect("/admin/?action=manage_pages");
  358. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  359. show_403(__("Access Denied"), __("Invalid security key."));
  360. $page = new Page($_POST['id']);
  361. if (!$page->no_results)
  362. foreach ($page->children as $child)
  363. if (isset($_POST['destroy_children']))
  364. Page::delete($child->id, true);
  365. else
  366. $child->update($child->title, $child->body, 0, $child->show_in_list, $child->list_order, $child->url);
  367. Page::delete($_POST['id']);
  368. Flash::notice(__("Page deleted."), "/admin/?action=manage_pages");
  369. }
  370. /**
  371. * Function: manage_pages
  372. * Page managing.
  373. */
  374. public function manage_pages() {
  375. $visitor = Visitor::current();
  376. if (!$visitor->group->can("edit_page") and !$visitor->group->can("delete_page"))
  377. show_403(__("Access Denied"), __("You do not have sufficient privileges to manage pages."));
  378. fallback($_GET['query'], "");
  379. list($where, $params) = keywords($_GET['query'], "title LIKE :query OR body LIKE :query", "pages");
  380. $this->display("manage_pages",
  381. array("pages" => new Paginator(Page::find(array("placeholders" => true,
  382. "where" => $where,
  383. "params" => $params)), 25)));
  384. }
  385. /**
  386. * Function: new_user
  387. * User creation.
  388. */
  389. public function new_user() {
  390. if (!Visitor::current()->group->can("add_user"))
  391. show_403(__("Access Denied"), __("You do not have sufficient privileges to add users."));
  392. $config = Config::current();
  393. $this->display("new_user",
  394. array("default_group" => new Group($config->default_group),
  395. "groups" => Group::find(array("where" => array("id not" => array($config->guest_group,
  396. $config->default_group)),
  397. "order" => "id DESC"))));
  398. }
  399. /**
  400. * Function: add_user
  401. * Add a user when the form is submitted.
  402. */
  403. public function add_user() {
  404. if (!Visitor::current()->group->can("add_user"))
  405. show_403(__("Access Denied"), __("You do not have sufficient privileges to add users."));
  406. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  407. show_403(__("Access Denied"), __("Invalid security key."));
  408. if (empty($_POST['login']))
  409. error(__("Error"), __("Please enter a username for your account."));
  410. $check = new User(array("login" => $_POST['login']));
  411. if (!$check->no_results)
  412. error(__("Error"), __("That username is already in use."));
  413. if (empty($_POST['password1']) or empty($_POST['password2']))
  414. error(__("Error"), __("Password cannot be blank."));
  415. elseif ($_POST['password1'] != $_POST['password2'])
  416. error(__("Error"), __("Passwords do not match."));
  417. if (empty($_POST['email']))
  418. error(__("Error"), __("E-mail address cannot be blank."));
  419. elseif (!preg_match("/^[_A-z0-9-]+((\.|\+)[_A-z0-9-]+)*@[A-z0-9-]+(\.[A-z0-9-]+)*(\.[A-z]{2,4})$/", $_POST['email']))
  420. error(__("Error"), __("Invalid e-mail address."));
  421. if (!empty($_POST['website']) and strpos($_POST['website'], '://') === false) {
  422. $_POST['website'] = 'http://' . $_POST['website'];
  423. }
  424. User::add($_POST['login'],
  425. $_POST['password1'],
  426. $_POST['email'],
  427. $_POST['full_name'],
  428. $_POST['website'],
  429. $_POST['group']);
  430. Flash::notice(__("User added."), "/admin/?action=manage_users");
  431. }
  432. /**
  433. * Function: edit_user
  434. * User editing.
  435. */
  436. public function edit_user() {
  437. if (!Visitor::current()->group->can("edit_user"))
  438. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit this user."));
  439. if (empty($_GET['id']))
  440. error(__("No ID Specified"), __("An ID is required to edit a user."));
  441. $this->display("edit_user",
  442. array("user" => new User($_GET['id']),
  443. "groups" => Group::find(array("order" => "id ASC",
  444. "where" => array("id not" => Config::current()->guest_group)))));
  445. }
  446. /**
  447. * Function: update_user
  448. * Updates a user when the form is submitted.
  449. */
  450. public function update_user() {
  451. if (empty($_POST['id']))
  452. error(__("No ID Specified"), __("An ID is required to edit a user."));
  453. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  454. show_403(__("Access Denied"), __("Invalid security key."));
  455. $visitor = Visitor::current();
  456. if (!$visitor->group->can("edit_user"))
  457. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit users."));
  458. $check_name = new User(null, array("where" => array("login" => $_POST['login'],
  459. "id not" => $_POST['id'])));
  460. if (!$check_name->no_results)
  461. Flash::notice(_f("Login &#8220;%s&#8221; is already in use.", array($_POST['login'])),
  462. "/admin/?action=edit_user&id=".$_POST['id']);
  463. $user = new User($_POST['id']);
  464. if ($user->no_results)
  465. Flash::warning(__("User not found."), "/admin/?action=manage_user");
  466. $password = (!empty($_POST['new_password1']) and $_POST['new_password1'] == $_POST['new_password2']) ?
  467. User::hashPassword($_POST['new_password1']) :
  468. $user->password ;
  469. $website = (!empty($_POST['website']) and strpos($_POST['website'], '://') === false) ?
  470. $_POST['website'] = 'http://' . $_POST['website'] :
  471. $_POST['website'] ;
  472. $user->update($_POST['login'], $password, $_POST['email'], $_POST['full_name'], $website, $_POST['group']);
  473. if ($_POST['id'] == $visitor->id)
  474. $_SESSION['password'] = $password;
  475. Flash::notice(__("User updated."), "/admin/?action=manage_users");
  476. }
  477. /**
  478. * Function: delete_user
  479. * User deletion.
  480. */
  481. public function delete_user() {
  482. if (!Visitor::current()->group->can("delete_user"))
  483. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete users."));
  484. if (empty($_GET['id']))
  485. error(__("No ID Specified"), __("An ID is required to delete a user."));
  486. $this->display("delete_user",
  487. array("user" => new User($_GET['id']),
  488. "users" => User::find(array("where" => array("id not" => $_GET['id'])))));
  489. }
  490. /**
  491. * Function: destroy_user
  492. * Destroys a user.
  493. */
  494. public function destroy_user() {
  495. if (!Visitor::current()->group->can("delete_user"))
  496. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete users."));
  497. if (empty($_POST['id']))
  498. error(__("No ID Specified"), __("An ID is required to delete a user."));
  499. if ($_POST['destroy'] == "bollocks")
  500. redirect("/admin/?action=manage_users");
  501. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  502. show_403(__("Access Denied"), __("Invalid security key."));
  503. $sql = SQL::current();
  504. $user = new User($_POST['id']);
  505. if (isset($_POST['posts'])) {
  506. if ($_POST['posts'] == "delete")
  507. foreach ($user->post as $post)
  508. Post::delete($post->id);
  509. elseif ($_POST['posts'] == "move")
  510. $sql->update("posts",
  511. array("user_id" => $user->id),
  512. array("user_id" => $_POST['move_posts']));
  513. }
  514. if (isset($_POST['pages'])) {
  515. if ($_POST['pages'] == "delete")
  516. foreach ($user->page as $page)
  517. Page::delete($page->id);
  518. elseif ($_POST['pages'] == "move")
  519. $sql->update("pages",
  520. array("user_id" => $user->id),
  521. array("user_id" => $_POST['move_pages']));
  522. }
  523. User::delete($_POST['id']);
  524. Flash::notice(__("User deleted."), "/admin/?action=manage_users");
  525. }
  526. /**
  527. * Function: manage_users
  528. * User managing.
  529. */
  530. public function manage_users() {
  531. $visitor = Visitor::current();
  532. if (!$visitor->group->can("edit_user") and !$visitor->group->can("delete_user") and !$visitor->group->can("add_user"))
  533. show_403(__("Access Denied"), __("You do not have sufficient privileges to manage users."));
  534. fallback($_GET['query'], "");
  535. list($where, $params) = keywords($_GET['query'], "login LIKE :query OR full_name LIKE :query OR email LIKE :query OR website LIKE :query", "users");
  536. $this->display("manage_users",
  537. array("users" => new Paginator(User::find(array("placeholders" => true,
  538. "where" => $where,
  539. "params" => $params)),
  540. 25)));
  541. }
  542. /**
  543. * Function: new_group
  544. * Group creation.
  545. */
  546. public function new_group() {
  547. if (!Visitor::current()->group->can("add_group"))
  548. show_403(__("Access Denied"), __("You do not have sufficient privileges to create groups."));
  549. $this->display("new_group",
  550. array("permissions" => SQL::current()->select("permissions", "*", array("group_id" => 0))->fetchAll()));
  551. }
  552. /**
  553. * Function: add_group
  554. * Adds a group when the form is submitted.
  555. */
  556. public function add_group() {
  557. if (!Visitor::current()->group->can("add_group"))
  558. show_403(__("Access Denied"), __("You do not have sufficient privileges to create groups."));
  559. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  560. show_403(__("Access Denied"), __("Invalid security key."));
  561. Group::add($_POST['name'], array_keys($_POST['permissions']));
  562. Flash::notice(__("Group added."), "/admin/?action=manage_groups");
  563. }
  564. /**
  565. * Function: edit_group
  566. * Group editing.
  567. */
  568. public function edit_group() {
  569. if (!Visitor::current()->group->can("edit_group"))
  570. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit groups."));
  571. if (empty($_GET['id']))
  572. error(__("No ID Specified"), __("An ID is required to edit a group."));
  573. $this->display("edit_group",
  574. array("group" => new Group($_GET['id']),
  575. "permissions" => SQL::current()->select("permissions", "*", array("group_id" => 0))->fetchAll()));
  576. }
  577. /**
  578. * Function: update_group
  579. * Updates a group when the form is submitted.
  580. */
  581. public function update_group() {
  582. if (!Visitor::current()->group->can("edit_group"))
  583. show_403(__("Access Denied"), __("You do not have sufficient privileges to edit groups."));
  584. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  585. show_403(__("Access Denied"), __("Invalid security key."));
  586. $permissions = array_keys($_POST['permissions']);
  587. $check_name = new Group(null, array("where" => array("name" => $_POST['name'],
  588. "id not" => $_POST['id'])));
  589. if (!$check_name->no_results)
  590. Flash::notice(_f("Group name &#8220;%s&#8221; is already in use.", array($_POST['name'])),
  591. "/admin/?action=edit_group&id=".$_POST['id']);
  592. $group = new Group($_POST['id']);
  593. if ($group->no_results)
  594. Flash::warning(__("Group not found."), "/admin/?action=manage_groups");
  595. $group->update($_POST['name'], $permissions);
  596. Flash::notice(__("Group updated."), "/admin/?action=manage_groups");
  597. }
  598. /**
  599. * Function: delete_group
  600. * Group deletion (confirm page).
  601. */
  602. public function delete_group() {
  603. if (!Visitor::current()->group->can("delete_group"))
  604. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete groups."));
  605. if (empty($_GET['id']))
  606. error(__("No ID Specified"), __("An ID is required to delete a group."));
  607. $this->display("delete_group",
  608. array("group" => new Group($_GET['id']),
  609. "groups" => Group::find(array("where" => array("id not" => $_GET['id']),
  610. "order" => "id ASC"))));
  611. }
  612. /**
  613. * Function: destroy_group
  614. * Destroys a group.
  615. */
  616. public function destroy_group() {
  617. if (!Visitor::current()->group->can("delete_group"))
  618. show_403(__("Access Denied"), __("You do not have sufficient privileges to delete groups."));
  619. if (!isset($_POST['id']))
  620. error(__("No ID Specified"), __("An ID is required to delete a group."));
  621. if ($_POST['destroy'] == "bollocks")
  622. redirect("/admin/?action=manage_groups");
  623. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  624. show_403(__("Access Denied"), __("Invalid security key."));
  625. $group = new Group($_POST['id']);
  626. foreach ($group->users as $user)
  627. $user->update($user->login, $user->password, $user->email, $user->full_name, $user->website, $_POST['move_group']);
  628. $config = Config::current();
  629. if (!empty($_POST['default_group']))
  630. $config->set("default_group", $_POST['default_group']);
  631. if (!empty($_POST['guest_group']))
  632. $config->set("guest_group", $_POST['guest_group']);
  633. Group::delete($_POST['id']);
  634. Flash::notice(__("Group deleted."), "/admin/?action=manage_groups");
  635. }
  636. /**
  637. * Function: manage_groups
  638. * Group managing.
  639. */
  640. public function manage_groups() {
  641. $visitor = Visitor::current();
  642. if (!$visitor->group->can("edit_group") and !$visitor->group->can("delete_group") and !$visitor->group->can("add_group"))
  643. show_403(__("Access Denied"), __("You do not have sufficient privileges to manage groups."));
  644. if (!empty($_GET['search'])) {
  645. $user = new User(array("login" => $_GET['search']));
  646. if (!$user->no_results)
  647. $groups = new Paginator(array($user->group), 10);
  648. else
  649. $groups = new Paginator(array(), 10);
  650. } else
  651. $groups = new Paginator(Group::find(array("placeholders" => true, "order" => "id ASC")), 10);
  652. $this->display("manage_groups",
  653. array("groups" => $groups));
  654. }
  655. /**
  656. * Function: export
  657. * Export posts, pages, etc.
  658. */
  659. public function export() {
  660. if (!Visitor::current()->group->can("add_post"))
  661. show_403(__("Access Denied"), __("You do not have sufficient privileges to export content."));
  662. if (empty($_POST))
  663. return $this->display("export");
  664. $config = Config::current();
  665. $trigger = Trigger::current();
  666. $route = Route::current();
  667. $exports = array();
  668. if (isset($_POST['posts'])) {
  669. list($where, $params) = keywords($_POST['filter_posts'], "post_attributes.value LIKE :query OR url LIKE :query", "post_attributes");
  670. if (!empty($_GET['month']))
  671. $where["created_at like"] = $_GET['month']."-%";
  672. $visitor = Visitor::current();
  673. if (!$visitor->group->can("view_draft", "edit_draft", "edit_post", "delete_draft", "delete_post"))
  674. $where["user_id"] = $visitor->id;
  675. $results = Post::find(array("placeholders" => true,
  676. "drafts" => true,
  677. "where" => $where,
  678. "params" => $params));
  679. $ids = array();
  680. foreach ($results[0] as $result)
  681. $ids[] = $result["id"];
  682. if (!empty($ids))
  683. $posts = Post::find(array("drafts" => true,
  684. "where" => array("id" => $ids),
  685. "order" => "id ASC"),
  686. array("filter" => false));
  687. else
  688. $posts = new Paginator(array());
  689. $latest_timestamp = 0;
  690. foreach ($posts as $post)
  691. if (strtotime($post->created_at) > $latest_timestamp)
  692. $latest_timestamp = strtotime($post->created_at);
  693. $id = substr(strstr($config->url, "//"), 2);
  694. $id = str_replace("#", "/", $id);
  695. $id = preg_replace("/(".preg_quote(parse_url($config->url, PHP_URL_HOST)).")/", "\\1,".date("Y", $latest_timestamp).":", $id, 1);
  696. $posts_atom = '<?xml version="1.0" encoding="utf-8"?>'."\r";
  697. $posts_atom.= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:chyrp="http://chyrp.net/export/1.0/">'."\r";
  698. $posts_atom.= ' <title>'.fix($config->name).' Posts</title>'."\r";
  699. $posts_atom.= ' <subtitle>'.fix($config->description).'</subtitle>'."\r";
  700. $posts_atom.= ' <id>tag:'.parse_url($config->url, PHP_URL_HOST).','.date("Y", $latest_timestamp).':Chyrp</id>'."\r";
  701. $posts_atom.= ' <updated>'.date("c", $latest_timestamp).'</updated>'."\r";
  702. $posts_atom.= ' <link href="'.$config->url.'" rel="self" type="application/atom+xml" />'."\r";
  703. $posts_atom.= ' <generator uri="http://chyrp.net/" version="'.CHYRP_VERSION.'">Chyrp</generator>'."\r";
  704. foreach ($posts as $post) {
  705. $title = fix($post->title(), false);
  706. fallback($title, ucfirst($post->feather)." Post #".$post->id);
  707. $updated = ($post->updated) ? $post->updated_at : $post->created_at ;
  708. $tagged = substr(strstr(url("id/".$post->id), "//"), 2);
  709. $tagged = str_replace("#", "/", $tagged);
  710. $tagged = preg_replace("/(".preg_quote(parse_url($post->url(), PHP_URL_HOST)).")/", "\\1,".when("Y-m-d", $updated).":", $tagged, 1);
  711. $url = $post->url();
  712. $posts_atom.= ' <entry xml:base="'.fix($url).'">'."\r";
  713. $posts_atom.= ' <title type="html">'.$title.'</title>'."\r";
  714. $posts_atom.= ' <id>tag:'.$tagged.'</id>'."\r";
  715. $posts_atom.= ' <updated>'.when("c", $updated).'</updated>'."\r";
  716. $posts_atom.= ' <published>'.when("c", $post->created_at).'</published>'."\r";
  717. $posts_atom.= ' <link href="'.fix($trigger->filter($url, "post_export_url", $post)).'" />'."\r";
  718. $posts_atom.= ' <author chyrp:user_id="'.$post->user_id.'">'."\r";
  719. $posts_atom.= ' <name>'.fix(oneof($post->user->full_name, $post->user->login)).'</name>'."\r";
  720. if (!empty($post->user->website))
  721. $posts_atom.= ' <uri>'.fix($post->user->website).'</uri>'."\r";
  722. $posts_atom.= ' <chyrp:login>'.fix($post->user->login).'</chyrp:login>'."\r";
  723. $posts_atom.= ' </author>'."\r";
  724. $posts_atom.= ' <content>'."\r";
  725. foreach ($post->attributes as $key => $val)
  726. $posts_atom.= ' <'.$key.'>'.fix($val).'</'.$key.'>'."\r";
  727. $posts_atom.= ' </content>'."\r";
  728. foreach (array("feather", "clean", "url", "pinned", "status") as $attr)
  729. $posts_atom.= ' <chyrp:'.$attr.'>'.fix($post->$attr).'</chyrp:'.$attr.'>'."\r";
  730. $trigger->filter($posts_atom, "posts_export", $post);
  731. $posts_atom.= ' </entry>'."\r";
  732. }
  733. $posts_atom.= '</feed>'."\r";
  734. $exports["posts.atom"] = $posts_atom;
  735. }
  736. if (isset($_POST['pages'])) {
  737. list($where, $params) = keywords($_POST['filter_pages'], "title LIKE :query OR body LIKE :query", "pages");
  738. $pages = Page::find(array("where" => $where, "params" => $params, "order" => "id ASC"),
  739. array("filter" => false));
  740. $latest_timestamp = 0;
  741. foreach ($pages as $page)
  742. if (strtotime($page->created_at) > $latest_timestamp)
  743. $latest_timestamp = strtotime($page->created_at);
  744. $pages_atom = '<?xml version="1.0" encoding="utf-8"?>'."\r";
  745. $pages_atom.= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:chyrp="http://chyrp.net/export/1.0/">'."\r";
  746. $pages_atom.= ' <title>'.fix($config->name).' Pages</title>'."\r";
  747. $pages_atom.= ' <subtitle>'.fix($config->description).'</subtitle>'."\r";
  748. $pages_atom.= ' <id>tag:'.parse_url($config->url, PHP_URL_HOST).','.date("Y", $latest_timestamp).':Chyrp</id>'."\r";
  749. $pages_atom.= ' <updated>'.date("c", $latest_timestamp).'</updated>'."\r";
  750. $pages_atom.= ' <link href="'.$config->url.'" rel="self" type="application/atom+xml" />'."\r";
  751. $pages_atom.= ' <generator uri="http://chyrp.net/" version="'.CHYRP_VERSION.'">Chyrp</generator>'."\r";
  752. foreach ($pages as $page) {
  753. $updated = ($page->updated) ? $page->updated_at : $page->created_at ;
  754. $tagged = substr(strstr($page->url(), "//"), 2);
  755. $tagged = str_replace("#", "/", $tagged);
  756. $tagged = preg_replace("/(".preg_quote(parse_url($page->url(), PHP_URL_HOST)).")/", "\\1,".when("Y-m-d", $updated).":", $tagged, 1);
  757. $url = $page->url();
  758. $pages_atom.= ' <entry xml:base="'.fix($url).'" chyrp:parent_id="'.$page->parent_id.'">'."\r";
  759. $pages_atom.= ' <title type="html">'.fix($page->title).'</title>'."\r";
  760. $pages_atom.= ' <id>tag:'.$tagged.'</id>'."\r";
  761. $pages_atom.= ' <updated>'.when("c", $updated).'</updated>'."\r";
  762. $pages_atom.= ' <published>'.when("c", $page->created_at).'</published>'."\r";
  763. $pages_atom.= ' <link href="'.fix($trigger->filter($url, "page_export_url", $page)).'" />'."\r";
  764. $pages_atom.= ' <author chyrp:user_id="'.fix($page->user_id).'">'."\r";
  765. $pages_atom.= ' <name>'.fix(oneof($page->user->full_name, $page->user->login)).'</name>'."\r";
  766. if (!empty($page->user->website))
  767. $pages_atom.= ' <uri>'.fix($page->user->website).'</uri>'."\r";
  768. $pages_atom.= ' <chyrp:login>'.fix($page->user->login).'</chyrp:login>'."\r";
  769. $pages_atom.= ' </author>'."\r";
  770. $pages_atom.= ' <content type="html">'.fix($page->body).'</content>'."\r";
  771. foreach (array("show_in_list", "list_order", "clean", "url") as $attr)
  772. $pages_atom.= ' <chyrp:'.$attr.'>'.fix($page->$attr).'</chyrp:'.$attr.'>'."\r";
  773. $trigger->filter($pages_atom, "pages_export", $page);
  774. $pages_atom.= ' </entry>'."\r";
  775. }
  776. $pages_atom.= '</feed>'."\r";
  777. $exports["pages.atom"] = $pages_atom;
  778. }
  779. if (isset($_POST['groups'])) {
  780. list($where, $params) = keywords($_POST['filter_groups'], "name LIKE :query", "groups");
  781. $groups = Group::find(array("where" => $where, "params" => $params, "order" => "id ASC"));
  782. $groups_yaml = array("groups" => array(),
  783. "permissions" => array());
  784. foreach (SQL::current()->select("permissions", "*", array("group_id" => 0))->fetchAll() as $permission)
  785. $groups_yaml["permissions"][$permission["id"]] = $permission["name"];
  786. foreach ($groups as $index => $group)
  787. $groups_yaml["groups"][$group->name] = $group->permissions;
  788. $exports["groups.yaml"] = YAML::dump($groups_yaml);
  789. }
  790. if (isset($_POST['users'])) {
  791. list($where, $params) = keywords($_POST['filter_users'], "login LIKE :query OR full_name LIKE :query OR email LIKE :query OR website LIKE :query", "users");
  792. $users = User::find(array("where" => $where, "params" => $params, "order" => "id ASC"));
  793. $users_yaml = array();
  794. foreach ($users as $user) {
  795. $users_yaml[$user->login] = array();
  796. foreach ($user as $name => $attr)
  797. if (!in_array($name, array("no_results", "group_id", "group", "id", "login", "belongs_to", "has_many", "has_one", "queryString")))
  798. $users_yaml[$user->login][$name] = $attr;
  799. elseif ($name == "group_id")
  800. $users_yaml[$user->login]["group"] = $user->group->name;
  801. }
  802. $exports["users.yaml"] = YAML::dump($users_yaml);
  803. }
  804. $trigger->filter($exports, "export");
  805. require INCLUDES_DIR."/lib/zip.php";
  806. $zip = new ZipFile();
  807. foreach ($exports as $filename => $content)
  808. $zip->addFile($content, $filename);
  809. $zip_contents = $zip->file();
  810. $filename = sanitize(camelize($config->name), false, true)."_Export_".date("Y-m-d");
  811. header("Content-type: application/octet-stream");
  812. header("Content-Disposition: attachment; filename=\"".$filename.".zip\"");
  813. header("Content-length: ".strlen($zip_contents)."\n\n");
  814. echo $zip_contents;
  815. }
  816. /**
  817. * Function: import
  818. * Importing content from other systems.
  819. */
  820. public function import() {
  821. if (!Visitor::current()->group->can("add_post"))
  822. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  823. $this->display("import");
  824. }
  825. /**
  826. * Function: import_chyrp
  827. * Chyrp importing.
  828. */
  829. public function import_chyrp() {
  830. if (empty($_POST))
  831. redirect("/admin/?action=import");
  832. if (!Visitor::current()->group->can("add_post"))
  833. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  834. if (isset($_FILES['posts_file']) and $_FILES['posts_file']['error'] == 0)
  835. if (!$posts = simplexml_load_file($_FILES['posts_file']['tmp_name']) or $posts->generator != "Chyrp")
  836. Flash::warning(__("Chyrp Posts export file is invalid."), "/admin/?action=import");
  837. if (isset($_FILES['pages_file']) and $_FILES['pages_file']['error'] == 0)
  838. if (!$pages = simplexml_load_file($_FILES['pages_file']['tmp_name']) or $pages->generator != "Chyrp")
  839. Flash::warning(__("Chyrp Pages export file is invalid."), "/admin/?action=import");
  840. if (ini_get("memory_limit") < 20)
  841. ini_set("memory_limit", "20M");
  842. $trigger = Trigger::current();
  843. $visitor = Visitor::current();
  844. $sql = SQL::current();
  845. function media_url_scan(&$value) {
  846. $config = Config::current();
  847. $regexp_url = preg_quote($_POST['media_url'], "/");
  848. if (preg_match_all("/{$regexp_url}([^\.\!,\?;\"\'<>\(\)\[\]\{\}\s\t ]+)\.([a-zA-Z0-9]+)/", $value, $media))
  849. foreach ($media[0] as $matched_url) {
  850. $filename = upload_from_url($matched_url);
  851. $value = str_replace($matched_url, $config->url.$config->uploads_path.$filename, $value);
  852. }
  853. }
  854. if (isset($_FILES['groups_file']) and $_FILES['groups_file']['error'] == 0) {
  855. $import = YAML::load($_FILES['groups_file']['tmp_name']);
  856. foreach ($import["groups"] as $name => $permissions)
  857. if (!$sql->count("groups", array("name" => $name)))
  858. $trigger->call("import_chyrp_group", Group::add($name, (array) $permissions));
  859. foreach ($import["permissions"] as $id => $name)
  860. if (!$sql->count("permissions", array("id" => $id)))
  861. $sql->insert("permissions", array("id" => $id, "name" => $name));
  862. }
  863. if (isset($_FILES['users_file']) and $_FILES['users_file']['error'] == 0) {
  864. $users = YAML::load($_FILES['users_file']['tmp_name']);
  865. foreach ($users as $login => $user) {
  866. $group_id = $sql->select("groups", "id", array("name" => $user["group"]), "id DESC")->fetchColumn();
  867. $group = ($group_id) ? $group_id : $config->default_group ;
  868. if (!$sql->count("users", array("login" => $login)))
  869. $user = User::add($login,
  870. $user["password"],
  871. $user["email"],
  872. $user["full_name"],
  873. $user["website"],
  874. $group,
  875. $user["joined_at"]);
  876. $trigger->call("import_chyrp_user", $user);
  877. }
  878. }
  879. if (isset($_FILES['posts_file']) and $_FILES['posts_file']['error'] == 0)
  880. foreach ($posts->entry as $entry) {
  881. $chyrp = $entry->children("http://chyrp.net/export/1.0/");
  882. $login = $entry->author->children("http://chyrp.net/export/1.0/")->login;
  883. $user_id = $sql->select("users", "id", array("login" => $login), "id DESC")->fetchColumn();
  884. $data = xml2arr($entry->content);
  885. $data["imported_from"] = "chyrp";
  886. if (!empty($_POST['media_url']))
  887. array_walk_recursive($data, "media_url_scan");
  888. $post = Post::add($data,
  889. $chyrp->clean,
  890. Post::check_url($chyrp->url),
  891. $chyrp->feather,
  892. ($user_id ? $user_id : $visitor->id),
  893. (bool) (int) $chyrp->pinned,
  894. $chyrp->status,
  895. datetime($entry->published),
  896. ($entry->updated == $entry->published) ?
  897. null :
  898. datetime($entry->updated),
  899. "",
  900. false);
  901. $trigger->call("import_chyrp_post", $entry, $post);
  902. }
  903. if (isset($_FILES['pages_file']) and $_FILES['pages_file']['error'] == 0)
  904. foreach ($pages->entry as $entry) {
  905. $chyrp = $entry->children("http://chyrp.net/export/1.0/");
  906. $attr = $entry->attributes("http://chyrp.net/export/1.0/");
  907. $login = $entry->author->children("http://chyrp.net/export/1.0/")->login;
  908. $user_id = $sql->select("users", "id", array("login" => $login), "id DESC")->fetchColumn();
  909. $page = Page::add($entry->title,
  910. $entry->content,
  911. ($user_id ? $user_id : $visitor->id),
  912. $attr->parent_id,
  913. (bool) (int) $chyrp->show_in_list,
  914. $chyrp->list_order,
  915. $chyrp->clean,
  916. Page::check_url($chyrp->url),
  917. datetime($entry->published),
  918. ($entry->updated == $entry->published) ? null : datetime($entry->updated));
  919. $trigger->call("import_chyrp_page", $entry, $page);
  920. }
  921. Flash::notice(__("Chyrp content successfully imported!"), "/admin/?action=import");
  922. }
  923. /**
  924. * Function: import_wordpress
  925. * WordPress importing.
  926. */
  927. public function import_wordpress() {
  928. if (empty($_POST))
  929. redirect("/admin/?action=import");
  930. if (!Visitor::current()->group->can("add_post"))
  931. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  932. $config = Config::current();
  933. if (!in_array("text", $config->enabled_feathers))
  934. error(__("Missing Feather"), __("Importing from WordPress requires the Text feather to be installed and enabled."));
  935. if (ini_get("memory_limit") < 20)
  936. ini_set("memory_limit", "20M");
  937. $trigger = Trigger::current();
  938. $stupid_xml = file_get_contents($_FILES['xml_file']['tmp_name']);
  939. $sane_xml = preg_replace(array("/<wp:comment_content>/", "/<\/wp:comment_content>/"),
  940. array("<wp:comment_content><![CDATA[", "]]></wp:comment_content>"),
  941. $stupid_xml);
  942. $sane_xml = str_replace(array("<![CDATA[<![CDATA[", "]]>]]>"),
  943. array("<![CDATA[", "]]>"),
  944. $sane_xml);
  945. if (!substr_count($sane_xml, "xmlns:excerpt"))
  946. $sane_xml = preg_replace("/xmlns:content=\"([^\"]+)\"(\s+)/m",
  947. "xmlns:content=\"\\1\"\\2xmlns:excerpt=\"http://wordpress.org/excerpt/1.0/\"\\2",
  948. $sane_xml);
  949. $fix_amps_count = 1;
  950. while ($fix_amps_count)
  951. $sane_xml = preg_replace("/<wp:meta_value>(.+)&(?!amp;)(.+)<\/wp:meta_value>/m",
  952. "<wp:meta_value>\\1&amp;\\2</wp:meta_value>",
  953. $sane_xml, -1, $fix_amps_count);
  954. # Remove null (x00) characters
  955. $sane_xml = str_replace("", "", $sane_xml);
  956. $xml = simplexml_load_string($sane_xml, "SimpleXMLElement", LIBXML_NOCDATA);
  957. if (!$xml or !substr_count($xml->channel->generator, "wordpress.org"))
  958. Flash::warning(__("File does not seem to be a valid WordPress export file, or could not be parsed. Please check your PHP error log."),
  959. "/admin/?action=import");
  960. foreach ($xml->channel->item as $item) {
  961. $wordpress = $item->children("http://wordpress.org/export/1.0/");
  962. $content = $item->children("http://purl.org/rss/1.0/modules/content/");
  963. if ($wordpress->status == "attachment" or $item->title == "zz_placeholder")
  964. continue;
  965. $regexp_url = preg_quote($_POST['media_url'], "/");
  966. if (!empty($_POST['media_url']) and
  967. preg_match_all("/{$regexp_url}([^\.\!,\?;\"\'<>\(\)\[\]\{\}\s\t ]+)\.([a-zA-Z0-9]+)/",
  968. $content->encoded,
  969. $media))
  970. foreach ($media[0] as $matched_url) {
  971. $filename = upload_from_url($matched_url);
  972. $content->encoded = str_replace($matched_url, $config->url.$config->uploads_path.$filename, $content->encoded);
  973. }
  974. $clean = (isset($wordpress->post_name)) ? $wordpress->post_name : sanitize($item->title) ;
  975. $pinned = (isset($wordpress->is_sticky)) ? $wordpress->is_sticky : 0 ;
  976. if (empty($wordpress->post_type) or $wordpress->post_type == "post") {
  977. $status_translate = array("publish" => "public",
  978. "draft" => "draft",
  979. "private" => "private",
  980. "static" => "public",
  981. "object" => "public",
  982. "inherit" => "public",
  983. "future" => "draft",
  984. "pending" => "draft");
  985. $data = array("title" => trim($item->title),
  986. "body" => trim($content->encoded),
  987. "imported_from" => "wordpress");
  988. $post = Post::add($data,
  989. $clean,
  990. Post::check_url($clean),
  991. "text",
  992. null,
  993. $pinned,
  994. $status_translate[(string) $wordpress->status],
  995. (string) ($wordpress->post_date == "0000-00-00 00:00:00" ? datetime() : $wordpress->post_date),
  996. null,
  997. "",
  998. false);
  999. $trigger->call("import_wordpress_post", $item, $post);
  1000. } elseif ($wordpress->post_type == "page") {
  1001. $page = Page::add(trim($item->title),
  1002. trim($content->encoded),
  1003. null,
  1004. 0,
  1005. true,
  1006. 0,
  1007. $clean,
  1008. Page::check_url($clean),
  1009. (string) ($wordpress->post_date == "0000-00-00 00:00:00" ? datetime() : $wordpress->post_date));
  1010. $trigger->call("import_wordpress_page", $item, $page);
  1011. }
  1012. }
  1013. Flash::notice(__("WordPress content successfully imported!"), "/admin/?action=import");
  1014. }
  1015. /**
  1016. * Function: import_tumblr
  1017. * Tumblr importing.
  1018. */
  1019. public function import_tumblr() {
  1020. if (empty($_POST))
  1021. redirect("/admin/?action=import");
  1022. if (!Visitor::current()->group->can("add_post"))
  1023. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  1024. $config = Config::current();
  1025. if (!in_array("text", $config->enabled_feathers) or
  1026. !in_array("video", $config->enabled_feathers) or
  1027. !in_array("audio", $config->enabled_feathers) or
  1028. !in_array("chat", $config->enabled_feathers) or
  1029. !in_array("photo", $config->enabled_feathers) or
  1030. !in_array("quote", $config->enabled_feathers) or
  1031. !in_array("link", $config->enabled_feathers))
  1032. error(__("Missing Feather"), __("Importing from Tumblr requires the Text, Video, Audio, Chat, Photo, Quote, and Link feathers to be installed and enabled."));
  1033. if (ini_get("memory_limit") < 20)
  1034. ini_set("memory_limit", "20M");
  1035. if (!parse_url($_POST['tumblr_url'], PHP_URL_SCHEME))
  1036. $_POST['tumblr_url'] = "http://".$_POST['tumblr_url'];
  1037. set_time_limit(3600);
  1038. $url = rtrim($_POST['tumblr_url'], "/")."/api/read?num=50";
  1039. $api = preg_replace("/<(\/?)([a-z]+)\-([a-z]+)/", "<\\1\\2_\\3", get_remote($url));
  1040. $api = preg_replace("/ ([a-z]+)\-([a-z]+)=/", " \\1_\\2=", $api);
  1041. $xml = simplexml_load_string($api);
  1042. if (!isset($xml->tumblelog))
  1043. Flash::warning(_f("Content could not be retrieved from the given URL. ". get_remote($url)),
  1044. "/admin/?action=import");
  1045. $already_in = $posts = array();
  1046. foreach ($xml->posts->post as $post) {
  1047. $posts[] = $post;
  1048. $already_in[] = $post->attributes()->id;
  1049. }
  1050. while ($xml->posts->attributes()->total > count($posts)) {
  1051. set_time_limit(3600);
  1052. $api = preg_replace("/<(\/?)([a-z]+)\-([a-z]+)/", "<\\1\\2_\\3", get_remote($url."&start=".count($posts)));
  1053. $api = preg_replace("/ ([a-z]+)\-([a-z]+)=/", " \\1_\\2=", $api);
  1054. $xml = simplexml_load_string($api, "SimpleXMLElement", LIBXML_NOCDATA);
  1055. foreach ($xml->posts->post as $post)
  1056. if (!in_array($post->attributes()->id, $already_in)) {
  1057. $posts[] = $post;
  1058. $already_in[] = $post->attributes()->id;
  1059. }
  1060. }
  1061. function reverse($a, $b) {
  1062. if (empty($a) or empty($b)) return 0;
  1063. return (strtotime($a->attributes()->date) < strtotime($b->attributes()->date)) ? -1 : 1 ;
  1064. }
  1065. set_time_limit(3600);
  1066. usort($posts, "reverse");
  1067. foreach ($posts as $key => $post) {
  1068. set_time_limit(3600);
  1069. if ($post->attributes()->type == "audio")
  1070. break; # Can't import Audio posts since Tumblr has the files locked in to Amazon.
  1071. $translate_types = array("regular" => "text", "conversation" => "chat");
  1072. $clean = "";
  1073. switch($post->attributes()->type) {
  1074. case "regular":
  1075. $title = fallback($post->regular_title);
  1076. $values = array("title" => $title,
  1077. "body" => $post->regular_body);
  1078. $clean = sanitize($title);
  1079. break;
  1080. case "video":
  1081. $values = array("embed" => $post->video_player,
  1082. "caption" => fallback($post->video_caption));
  1083. break;
  1084. case "conversation":
  1085. $title = fallback($post->conversation_title);
  1086. $lines = array();
  1087. foreach ($post->conversation_line as $line)
  1088. $lines[] = $line->attributes()->label." ".$line;
  1089. $values = array("title" => $title,
  1090. "dialogue" => implode("\n", $lines));
  1091. $clean = sanitize($title);
  1092. break;
  1093. case "photo":
  1094. $values = array("filename" => upload_from_url($post->photo_url[0]),
  1095. "caption" => fallback($post->photo_caption));
  1096. break;
  1097. case "quote":
  1098. $values = array("quote" => $post->quote_text,
  1099. "source" => preg_replace("/^&mdash; /", "",
  1100. fallback($post->quote_source)));
  1101. break;
  1102. case "link":
  1103. $name = fallback($post->link_text);
  1104. $values = array("name" => $name,
  1105. "source" => $post->link_url,
  1106. "description" => fallback($post->link_description));
  1107. $clean = sanitize($name);
  1108. break;
  1109. }
  1110. $values["imported_from"] = "tumblr";
  1111. $new_post = Post::add($values,
  1112. $clean,
  1113. Post::check_url($clean),
  1114. fallback($translate_types[(string) $post->attributes()->type], (string) $post->attributes()->type),
  1115. null,
  1116. null,
  1117. "public",
  1118. datetime((int) $post->attributes()->unix_timestamp),
  1119. null,
  1120. "",
  1121. false);
  1122. Trigger::current()->call("import_tumble", $post, $new_post);
  1123. }
  1124. Flash::notice(__("Tumblr content successfully imported!"), "/admin/?action=import");
  1125. }
  1126. /**
  1127. * Function: import_textpattern
  1128. * TextPattern importing.
  1129. */
  1130. public function import_textpattern() {
  1131. if (empty($_POST))
  1132. redirect("/admin/?action=import");
  1133. if (!Visitor::current()->group->can("add_post"))
  1134. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  1135. $config = Config::current();
  1136. $trigger = Trigger::current();
  1137. $dbcon = $dbsel = false;
  1138. if ($link = @mysql_connect($_POST['host'], $_POST['username'], $_POST['password'])) {
  1139. $dbcon = true;
  1140. $dbsel = @mysql_select_db($_POST['database'], $link);
  1141. }
  1142. if (!$dbcon or !$dbsel)
  1143. Flash::warning(__("Could not connect to the specified TextPattern database."),
  1144. "/admin/?action=import");
  1145. mysql_query("SET NAMES 'utf8'");
  1146. $get_posts = mysql_query("SELECT * FROM {$_POST['prefix']}textpattern ORDER BY ID ASC", $link) or error(__("Database Error"), mysql_error());
  1147. $posts = array();
  1148. while ($post = mysql_fetch_array($get_posts))
  1149. $posts[$post["ID"]] = $post;
  1150. foreach ($posts as $post) {
  1151. $regexp_url = preg_quote($_POST['media_url'], "/");
  1152. if (!empty($_POST['media_url']) and
  1153. preg_match_all("/{$regexp_url}([^\.\!,\?;\"\'<>\(\)\[\]\{\}\s\t ]+)\.([a-zA-Z0-9]+)/",
  1154. $post["Body"],
  1155. $media))
  1156. foreach ($media[0] as $matched_url) {
  1157. $filename = upload_from_url($matched_url);
  1158. $post["Body"] = str_replace($matched_url, $config->url.$config->uploads_path.$filename, $post["Body"]);
  1159. }
  1160. $status_translate = array(1 => "draft",
  1161. 2 => "private",
  1162. 3 => "draft",
  1163. 4 => "public",
  1164. 5 => "public");
  1165. $clean = fallback($post["url_title"], sanitize($post["Title"]));
  1166. $new_post = Post::add(array("title" => $post["Title"],
  1167. "body" => $post["Body"],
  1168. "imported_from" => "textpattern"),
  1169. $clean,
  1170. Post::check_url($clean),
  1171. "text",
  1172. null,
  1173. ($post["Status"] == "5"),
  1174. $status_translate[$post["Status"]],
  1175. $post["Posted"],
  1176. null,
  1177. "",
  1178. false);
  1179. $trigger->call("import_textpattern_post", $post, $new_post);
  1180. }
  1181. mysql_close($link);
  1182. Flash::notice(__("TextPattern content successfully imported!"), "/admin/?action=import");
  1183. }
  1184. /**
  1185. * Function: import_movabletype
  1186. * MovableType importing.
  1187. */
  1188. public function import_movabletype() {
  1189. if (empty($_POST))
  1190. redirect("/admin/?action=import");
  1191. if (!Visitor::current()->group->can("add_post"))
  1192. show_403(__("Access Denied"), __("You do not have sufficient privileges to import content."));
  1193. $config = Config::current();
  1194. $trigger = Trigger::current();
  1195. $dbcon = $dbsel = false;
  1196. if ($link = @mysql_connect($_POST['host'], $_POST['username'], $_POST['password'])) {
  1197. $dbcon = true;
  1198. $dbsel = @mysql_select_db($_POST['database'], $link);
  1199. }
  1200. if (!$dbcon or !$dbsel)
  1201. Flash::warning(__("Could not connect to the specified MovableType database."),
  1202. "/admin/?action=import");
  1203. mysql_query("SET NAMES 'utf8'");
  1204. $get_authors = mysql_query("SELECT * FROM mt_author ORDER BY author_id ASC", $link) or error(__("Database Error"), mysql_error());
  1205. $users = array();
  1206. while ($author = mysql_fetch_array($get_authors)) {
  1207. # Try to figure out if this author is the same as the person doing the import.
  1208. if ($author["author_name"] == Visitor::current()->login or
  1209. $author["author_nickname"] == Visitor::current()->login or
  1210. $author["author_nickname"] == Visitor::current()->full_name or
  1211. $author["author_url"] == Visitor::current()->website or
  1212. $author["author_email"] == Visitor::current()->email)
  1213. $users[$author["author_id"]] = Visitor::current();
  1214. else
  1215. $users[$author["author_id"]] = User::add($author["author_name"],
  1216. $author["author_password"],
  1217. $author["author_email"],
  1218. ($author["author_nickname"] != $author["author_name"] ?
  1219. $author["author_nickname"] :
  1220. ""),
  1221. $author["author_url"],
  1222. ($author["author_can_create_blog"] == "1" ?
  1223. Visitor::current()->group :
  1224. null),
  1225. $author["author_created_on"],
  1226. false);
  1227. }
  1228. $get_posts = mysql_query("SELECT * FROM mt_entry ORDER BY entry_id ASC", $link) or error(__("Database Error"), mysql_error());
  1229. $posts = array();
  1230. while ($post = mysql_fetch_array($get_posts))
  1231. $posts[$post["entry_id"]] = $post;
  1232. foreach ($posts as $post) {
  1233. $body = $post["entry_text"];
  1234. if (!empty($post["entry_text_more"]))
  1235. $body.= "\n\n<!--more-->\n\n".$post["entry_text_more"];
  1236. $regexp_url = preg_quote($_POST['media_url'], "/");
  1237. if (!empty($_POST['media_url']) and
  1238. preg_match_all("/{$regexp_url}([^\.\!,\?;\"\'<>\(\)\[\]\{\}\s\t ]+)\.([a-zA-Z0-9]+)/",
  1239. $body,
  1240. $media))
  1241. foreach ($media[0] as $matched_url) {
  1242. $filename = upload_from_url($matched_url);
  1243. $body = str_replace($matched_url, $config->url.$config->uploads_path.$filename, $body);
  1244. }
  1245. $status_translate = array(1 => "draft",
  1246. 2 => "public",
  1247. 3 => "draft",
  1248. 4 => "draft");
  1249. $clean = oneof($post["entry_basename"], sanitize($post["entry_title"]));
  1250. if (empty($post["entry_class"]) or $post["entry_class"] == "entry") {
  1251. $new_post = Post::add(array("title" => $post["entry_title"],
  1252. "body" => $body,
  1253. "imported_from" => "movabletype"),
  1254. $clean,
  1255. Post::check_url($clean),
  1256. "text",
  1257. @$users[$post["entry_author_id"]],
  1258. false,
  1259. $status_translate[$post["entry_status"]],
  1260. oneof(@$post["entry_authored_on"], @$post["entry_created_on"], datetime()),
  1261. $post["entry_modified_on"],
  1262. "",
  1263. false);
  1264. $trigger->call("import_movabletype_post", $post, $new_post, $link);
  1265. } elseif (@$post["entry_class"] == "page") {
  1266. $new_page = Page::add($post["entry_title"], $body, null, 0, true, 0, $clean, Page::check_url($clean));
  1267. $trigger->call("import_movabletype_page", $post, $new_page, $link);
  1268. }
  1269. }
  1270. mysql_close($link);
  1271. Flash::notice(__("MovableType content successfully imported!"), "/admin/?action=import");
  1272. }
  1273. /**
  1274. * Function: modules
  1275. * Module enabling/disabling.
  1276. */
  1277. public function modules() {
  1278. if (!Visitor::current()->group->can("toggle_extensions"))
  1279. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable modules."));
  1280. $config = Config::current();
  1281. $this->context["enabled_modules"] = $this->context["disabled_modules"] = array();
  1282. if (!$open = @opendir(MODULES_DIR))
  1283. return Flash::warning(__("Could not read modules directory."));
  1284. $classes = array();
  1285. while (($folder = readdir($open)) !== false) {
  1286. if (!file_exists(MODULES_DIR."/".$folder."/".$folder.".php") or !file_exists(MODULES_DIR."/".$folder."/info.yaml")) continue;
  1287. if (file_exists(MODULES_DIR."/".$folder."/locale/".$config->locale.".mo"))
  1288. load_translator($folder, MODULES_DIR."/".$folder."/locale/".$config->locale.".mo");
  1289. if (!isset($classes[$folder]))
  1290. $classes[$folder] = array($folder);
  1291. else
  1292. array_unshift($classes[$folder], $folder);
  1293. $info = YAML::load(MODULES_DIR."/".$folder."/info.yaml");
  1294. $info["conflicts_true"] = array();
  1295. $info["depends_true"] = array();
  1296. if (!empty($info["conflicts"])) {
  1297. $classes[$folder][] = "conflict";
  1298. foreach ((array) $info["conflicts"] as $conflict)
  1299. if (file_exists(MODULES_DIR."/".$conflict."/".$conflict.".php"))
  1300. $classes[$folder][] = "conflict_".$conflict;
  1301. }
  1302. $dependencies_needed = array();
  1303. if (!empty($info["depends"])) {
  1304. $classes[$folder][] = "depends";
  1305. foreach ((array) $info["depends"] as $dependency) {
  1306. if (!module_enabled($dependency)) {
  1307. if (!in_array("missing_dependency", $classes[$folder]))
  1308. $classes[$folder][] = "missing_dependency";
  1309. $classes[$folder][] = "needs_".$dependency;
  1310. $dependencies_needed[] = $dependency;
  1311. }
  1312. $classes[$folder][] = "depends_".$dependency;
  1313. fallback($classes[$dependency], array());
  1314. $classes[$dependency][] = "depended_by_".$folder;
  1315. }
  1316. }
  1317. fallback($info["name"], $folder);
  1318. fallback($info["version"], "0");
  1319. fallback($info["url"]);
  1320. fallback($info["description"]);
  1321. fallback($info["author"], array("name" => "", "url" => ""));
  1322. fallback($info["help"]);
  1323. $info["description"] = __($info["description"], $folder);
  1324. $info["description"] = preg_replace(array("/<code>(.+)<\/code>/se", "/<pre>(.+)<\/pre>/se"),
  1325. array("'<code>'.fix('\\1').'</code>'", "'<pre>'.fix('\\1').'</pre>'"),
  1326. $info["description"]);
  1327. $info["author"]["link"] = !empty($info["author"]["url"]) ?
  1328. '<a href="'.fix($info["author"]["url"]).'">'.fix($info["author"]["name"]).'</a>' :
  1329. $info["author"]["name"] ;
  1330. $category = (module_enabled($folder)) ? "enabled_modules" : "disabled_modules" ;
  1331. $this->context[$category][$folder] = array("name" => $info["name"],
  1332. "version" => $info["version"],
  1333. "url" => $info["url"],
  1334. "description" => $info["description"],
  1335. "author" => $info["author"],
  1336. "help" => $info["help"],
  1337. "classes" => $classes[$folder],
  1338. "dependencies_needed" => $dependencies_needed);
  1339. }
  1340. foreach ($this->context["enabled_modules"] as $module => &$attrs)
  1341. $attrs["classes"] = $classes[$module];
  1342. foreach ($this->context["disabled_modules"] as $module => &$attrs)
  1343. $attrs["classes"] = $classes[$module];
  1344. $this->display("modules");
  1345. }
  1346. /**
  1347. * Function: feathers
  1348. * Feather enabling/disabling.
  1349. */
  1350. public function feathers() {
  1351. if (!Visitor::current()->group->can("toggle_extensions"))
  1352. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable feathers."));
  1353. $config = Config::current();
  1354. $this->context["enabled_feathers"] = $this->context["disabled_feathers"] = array();
  1355. if (!$open = @opendir(FEATHERS_DIR))
  1356. return Flash::warning(__("Could not read feathers directory."));
  1357. while (($folder = readdir($open)) !== false) {
  1358. if (!file_exists(FEATHERS_DIR."/".$folder."/".$folder.".php") or !file_exists(FEATHERS_DIR."/".$folder."/info.yaml")) continue;
  1359. if (file_exists(FEATHERS_DIR."/".$folder."/locale/".$config->locale.".mo"))
  1360. load_translator($folder, FEATHERS_DIR."/".$folder."/locale/".$config->locale.".mo");
  1361. $info = YAML::load(FEATHERS_DIR."/".$folder."/info.yaml");
  1362. fallback($info["name"], $folder);
  1363. fallback($info["version"], "0");
  1364. fallback($info["url"]);
  1365. fallback($info["description"]);
  1366. fallback($info["author"], array("name" => "", "url" => ""));
  1367. fallback($info["help"]);
  1368. $info["description"] = __($info["description"], $folder);
  1369. $info["description"] = preg_replace("/<code>(.+)<\/code>/se", "'<code>'.fix('\\1').'</code>'", $info["description"]);
  1370. $info["description"] = preg_replace("/<pre>(.+)<\/pre>/se", "'<pre>'.fix('\\1').'</pre>'", $info["description"]);
  1371. $info["author"]["link"] = !empty($info["author"]["url"]) ?
  1372. '<a href="'.fix($info["author"]["url"]).'">'.fix($info["author"]["name"]).'</a>' :
  1373. $info["author"]["name"] ;
  1374. $category = (feather_enabled($folder)) ? "enabled_feathers" : "disabled_feathers" ;
  1375. $this->context[$category][$folder] = array("name" => $info["name"],
  1376. "version" => $info["version"],
  1377. "url" => $info["url"],
  1378. "description" => $info["description"],
  1379. "author" => $info["author"],
  1380. "help" => $info["help"]);
  1381. }
  1382. $this->display("feathers");
  1383. }
  1384. /**
  1385. * Function: themes
  1386. * Theme switching/previewing.
  1387. */
  1388. public function themes() {
  1389. $config = Config::current();
  1390. $this->context["preview"] = !empty($_SESSION['theme']) ? $_SESSION['theme'] : "" ;
  1391. $this->context["themes"] = array();
  1392. if (!$open = @opendir(THEMES_DIR))
  1393. return Flash::warning(__("Could not read themes directory."));
  1394. while (($folder = readdir($open)) !== false) {
  1395. if (!file_exists(THEMES_DIR."/".$folder."/info.yaml"))
  1396. continue;
  1397. if (file_exists(THEMES_DIR."/".$folder."/locale/".$config->locale.".mo"))
  1398. load_translator($folder, THEMES_DIR."/".$folder."/locale/".$config->locale.".mo");
  1399. $info = YAML::load(THEMES_DIR."/".$folder."/info.yaml");
  1400. fallback($info["name"], $folder);
  1401. fallback($info["version"], "0");
  1402. fallback($info["url"]);
  1403. fallback($info["description"]);
  1404. fallback($info["author"], array("name" => "", "url" => ""));
  1405. $info["author"]["link"] = !empty($info["author"]["url"]) ?
  1406. '<a href="'.$info["author"]["url"].'">'.$info["author"]["name"].'</a>' :
  1407. $info["author"]["name"] ;
  1408. $info["description"] = preg_replace("/<code>(.+)<\/code>/se",
  1409. "'<code>'.fix('\\1').'</code>'",
  1410. $info["description"]);
  1411. $info["description"] = preg_replace("/<pre>(.+)<\/pre>/se",
  1412. "'<pre>'.fix('\\1').'</pre>'",
  1413. $info["description"]);
  1414. $this->context["themes"][] = array("name" => $folder,
  1415. "screenshot" => (file_exists(THEMES_DIR."/".$folder."/screenshot.png") ?
  1416. $config->chyrp_url."/themes/".$folder."/screenshot.png" :
  1417. ""),
  1418. "info" => $info);
  1419. }
  1420. if (!$open = @opendir(ADMIN_THEMES_DIR))
  1421. return Flash::warning(__("Could not read themes directory."));
  1422. while (($folder = readdir($open)) !== false) {
  1423. if (!file_exists(ADMIN_THEMES_DIR."/".$folder."/info.yaml"))
  1424. continue;
  1425. if (file_exists(ADMIN_THEMES_DIR."/".$folder."/locale/".$config->locale.".mo"))
  1426. load_translator($folder, ADMIN_THEMES_DIR."/".$folder."/locale/".$config->locale.".mo");
  1427. $info = YAML::load(ADMIN_THEMES_DIR."/".$folder."/info.yaml");
  1428. fallback($info["name"], $folder);
  1429. fallback($info["version"], "0");
  1430. fallback($info["url"]);
  1431. fallback($info["description"]);
  1432. fallback($info["author"], array("name" => "", "url" => ""));
  1433. $info["author"]["link"] = !empty($info["author"]["url"]) ?
  1434. '<a href="'.$info["author"]["url"].'">'.$info["author"]["name"].'</a>' :
  1435. $info["author"]["name"] ;
  1436. $info["description"] = preg_replace("/<code>(.+)<\/code>/se",
  1437. "'<code>'.fix('\\1').'</code>'",
  1438. $info["description"]);
  1439. $info["description"] = preg_replace("/<pre>(.+)<\/pre>/se",
  1440. "'<pre>'.fix('\\1').'</pre>'",
  1441. $info["description"]);
  1442. $this->context["admin_themes"][] = array("name" => $folder,
  1443. "screenshot" => (file_exists(ADMIN_THEMES_DIR."/".$folder."/screenshot.png") ?
  1444. $config->chyrp_url."/admin/themes/".$folder."/screenshot.png" :
  1445. ""),
  1446. "info" => $info);
  1447. }
  1448. closedir($open);
  1449. $this->display("themes");
  1450. }
  1451. /**
  1452. * Function: enable
  1453. * Enables a module or feather.
  1454. */
  1455. public function enable() {
  1456. $config = Config::current();
  1457. $visitor = Visitor::current();
  1458. $type = (isset($_GET['module'])) ? "module" : "feather" ;
  1459. if (!$visitor->group->can("toggle_extensions"))
  1460. if ($type == "module")
  1461. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable modules."));
  1462. else
  1463. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable feathers."));
  1464. if ($type == "module" and module_enabled($_GET[$type]))
  1465. Flash::warning(__("Module already enabled."), "/admin/?action=modules");
  1466. if ($type == "feather" and feather_enabled($_GET[$type]))
  1467. Flash::warning(__("Feather already enabled."), "/admin/?action=feathers");
  1468. $enabled_array = ($type == "module") ? "enabled_modules" : "enabled_feathers" ;
  1469. $folder = ($type == "module") ? MODULES_DIR : FEATHERS_DIR ;
  1470. require $folder."/".$_GET[$type]."/".$_GET[$type].".php";
  1471. $class_name = camelize($_GET[$type]);
  1472. if ($type == "module" and !is_subclass_of($class_name, "Modules"))
  1473. Flash::warning(__("Item is not a module."), "/admin/?action=modules");
  1474. if ($type == "feather" and !is_subclass_of($class_name, "Feathers"))
  1475. Flash::warning(__("Item is not a feather."), "/admin/?action=feathers");
  1476. if (method_exists($class_name, "__install"))
  1477. call_user_func(array($class_name, "__install"));
  1478. $new = $config->$enabled_array;
  1479. array_push($new, $_GET[$type]);
  1480. $config->set($enabled_array, $new);
  1481. if (file_exists($folder."/".$_GET[$type]."/locale/".$config->locale.".mo"))
  1482. load_translator($_GET[$type], $folder."/".$_GET[$type]."/locale/".$config->locale.".mo");
  1483. $info = YAML::load($folder."/".$_GET[$type]."/info.yaml");
  1484. fallback($info["uploader"], false);
  1485. fallback($info["notifications"], array());
  1486. foreach ($info["notifications"] as &$notification)
  1487. $notification = __($notification, $_GET[$type]);
  1488. if ($info["uploader"])
  1489. if (!file_exists(MAIN_DIR.$config->uploads_path))
  1490. $info["notifications"][] = _f("Please create the <code>%s</code> directory at your Chyrp install's root and CHMOD it to 777.", array($config->uploads_path));
  1491. elseif (!is_writable(MAIN_DIR.$config->uploads_path))
  1492. $info["notifications"][] = _f("Please CHMOD <code>%s</code> to 777.", array($config->uploads_path));
  1493. foreach ($info["notifications"] as $message)
  1494. Flash::message($message);
  1495. if ($type == "module")
  1496. Flash::notice(_f("&#8220;%s&#8221; module enabled.",
  1497. array($info["name"])),
  1498. "/admin/?action=".pluralize($type));
  1499. elseif ($type == "feather")
  1500. Flash::notice(_f("&#8220;%s&#8221; feather enabled.",
  1501. array($info["name"])),
  1502. "/admin/?action=".pluralize($type));
  1503. }
  1504. /**
  1505. * Function: disable
  1506. * Disables a module or feather.
  1507. */
  1508. public function disable() {
  1509. $config = Config::current();
  1510. $visitor = Visitor::current();
  1511. $type = (isset($_GET['module'])) ? "module" : "feather" ;
  1512. if (!$visitor->group->can("toggle_extensions"))
  1513. if ($type == "module")
  1514. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable modules."));
  1515. else
  1516. show_403(__("Access Denied"), __("You do not have sufficient privileges to enable/disable feathers."));
  1517. if ($type == "module" and !module_enabled($_GET[$type]))
  1518. Flash::warning(__("Module already disabled."), "/admin/?action=modules");
  1519. if ($type == "feather" and !feather_enabled($_GET[$type]))
  1520. Flash::warning(__("Feather already disabled."), "/admin/?action=feathers");
  1521. $enabled_array = ($type == "module") ? "enabled_modules" : "enabled_feathers" ;
  1522. $folder = ($type == "module") ? MODULES_DIR : FEATHERS_DIR ;
  1523. $class_name = camelize($_GET[$type]);
  1524. if (method_exists($class_name, "__uninstall"))
  1525. call_user_func(array($class_name, "__uninstall"), false);
  1526. $config->set(($type == "module" ? "enabled_modules" : "enabled_feathers"),
  1527. array_diff($config->$enabled_array, array($_GET[$type])));
  1528. $info = YAML::load($folder."/".$_GET[$type]."/info.yaml");
  1529. if ($type == "module")
  1530. Flash::notice(_f("&#8220;%s&#8221; module disabled.",
  1531. array($info["name"])),
  1532. "/admin/?action=".pluralize($type));
  1533. elseif ($type == "feather")
  1534. Flash::notice(_f("&#8220;%s&#8221; feather disabled.",
  1535. array($info["name"])),
  1536. "/admin/?action=".pluralize($type));
  1537. }
  1538. /**
  1539. * Function: change_theme
  1540. * Changes the theme.
  1541. */
  1542. public function change_theme() {
  1543. if (!Visitor::current()->group->can("change_settings"))
  1544. show_403(__("Access Denied"), __("You do not have sufficient privileges to change settings."));
  1545. if (empty($_GET['theme']))
  1546. error(__("No Theme Specified"), __("You did not specify a theme to switch to."));
  1547. $config = Config::current();
  1548. $config->set("theme", $_GET['theme']);
  1549. if (file_exists(THEMES_DIR."/".$_GET['theme']."/locale/".$config->locale.".mo"))
  1550. load_translator($_GET['theme'], THEMES_DIR."/".$_GET['theme']."/locale/".$config->locale.".mo");
  1551. $info = YAML::load(THEMES_DIR."/".$_GET['theme']."/info.yaml");
  1552. fallback($info["notifications"], array());
  1553. foreach ($info["notifications"] as &$notification)
  1554. $notification = __($notification, $_GET['theme']);
  1555. foreach ($info["notifications"] as $message)
  1556. Flash::message($message);
  1557. # Clear the caches made by the previous theme.
  1558. foreach ((array) glob(INCLUDES_DIR."/caches/*.cache") as $cache)
  1559. @unlink($cache);
  1560. Flash::notice(_f("Theme changed to &#8220;%s&#8221;.", array($info["name"])), "/admin/?action=themes");
  1561. }
  1562. /**
  1563. * Function: theme
  1564. * Changes the admin theme.
  1565. */
  1566. public function change_admin_theme() {
  1567. if (empty($_GET['theme']))
  1568. error(__("No Theme Specified"), __("You did not specify a theme to switch to."));
  1569. $config = Config::current();
  1570. $_SESSION['admin_theme'] = $_GET['theme'];
  1571. if (file_exists(ADMIN_THEMES_DIR."/".$_GET['theme']."/locale/".$config->locale.".mo"))
  1572. load_translator($_GET['theme'], ADMIN_THEMES_DIR."/".$_GET['theme']."/locale/".$config->locale.".mo");
  1573. $info = YAML::load(ADMIN_THEMES_DIR."/".$_GET['theme']."/info.yaml");
  1574. fallback($info["notifications"], array());
  1575. foreach ($info["notifications"] as &$notification)
  1576. $notification = __($notification, $_GET['theme']);
  1577. foreach ($info["notifications"] as $message)
  1578. Flash::message($message);
  1579. # Clear the caches made by the previous theme.
  1580. foreach (glob(INCLUDES_DIR."/caches/*.cache") as $cache)
  1581. @unlink($cache);
  1582. Flash::notice(_f("Admin theme changed to &#8220;%s&#8221;.", array($info["name"])), "/admin/?action=themes");
  1583. }
  1584. /**
  1585. * Function: preview_theme
  1586. * Previews the theme.
  1587. */
  1588. public function preview_theme() {
  1589. if (!Visitor::current()->group->can("change_settings"))
  1590. show_403(__("Access Denied"), __("You do not have sufficient privileges to preview themes."));
  1591. if (empty($_GET['theme']))
  1592. error(__("No Theme Specified"), __("You did not specify a theme to preview."));
  1593. $info = YAML::load(THEMES_DIR."/".$_GET['theme']."/info.yaml");
  1594. # Clear the caches made by the previous theme.
  1595. foreach (glob(INCLUDES_DIR."/caches/*.cache") as $cache)
  1596. @unlink($cache);
  1597. if (!empty($_SESSION['theme'])) {
  1598. unset($_SESSION['theme']);
  1599. Flash::notice(_f("Stopped previewing &#8220;%s&#8221;.", array($info["name"])), "/admin/?action=themes");
  1600. } else {
  1601. $_SESSION['theme'] = $_GET['theme'];
  1602. Flash::notice(_f("Previewing theme &#8220;%s&#8221;. Press the theme's &#8220;Preview&#8221; button again to stop previewing.", array($info["name"])), "/");
  1603. }
  1604. }
  1605. /**
  1606. * Function: general_settings
  1607. * General Settings page.
  1608. */
  1609. public function general_settings() {
  1610. if (!Visitor::current()->group->can("change_settings"))
  1611. show_403(__("Access Denied"), __("You do not have sufficient privileges to change settings."));
  1612. $locales = array();
  1613. if ($open = opendir(INCLUDES_DIR."/locale/")) {
  1614. while (($folder = readdir($open)) !== false) {
  1615. $split = explode(".", $folder);
  1616. if (end($split) == "mo")
  1617. $locales[] = array("code" => $split[0], "name" => lang_code($split[0]));
  1618. }
  1619. closedir($open);
  1620. }
  1621. if (empty($_POST))
  1622. return $this->display("general_settings",
  1623. array("locales" => $locales,
  1624. "timezones" => timezones()));
  1625. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  1626. show_403(__("Access Denied"), __("Invalid security key."));
  1627. $config = Config::current();
  1628. $set = array($config->set("name", $_POST['name']),
  1629. $config->set("description", $_POST['description']),
  1630. $config->set("chyrp_url", rtrim($_POST['chyrp_url'], "/")),
  1631. $config->set("url", rtrim(oneof($_POST['url'], $_POST['chyrp_url']), "/")),
  1632. $config->set("email", $_POST['email']),
  1633. $config->set("timezone", $_POST['timezone']),
  1634. $config->set("locale", $_POST['locale']));
  1635. if (!in_array(false, $set))
  1636. Flash::notice(__("Settings updated."), "/admin/?action=general_settings");
  1637. }
  1638. /**
  1639. * Function: user_settings
  1640. * User Settings page.
  1641. */
  1642. public function user_settings() {
  1643. if (!Visitor::current()->group->can("change_settings"))
  1644. show_403(__("Access Denied"), __("You do not have sufficient privileges to change settings."));
  1645. if (empty($_POST))
  1646. return $this->display("user_settings", array("groups" => Group::find(array("order" => "id DESC"))));
  1647. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  1648. show_403(__("Access Denied"), __("Invalid security key."));
  1649. $config = Config::current();
  1650. $set = array($config->set("can_register", !empty($_POST['can_register'])),
  1651. $config->set("default_group", $_POST['default_group']),
  1652. $config->set("guest_group", $_POST['guest_group']));
  1653. if (!in_array(false, $set))
  1654. Flash::notice(__("Settings updated."), "/admin/?action=user_settings");
  1655. }
  1656. /**
  1657. * Function: content_settings
  1658. * Content Settings page.
  1659. */
  1660. public function content_settings() {
  1661. if (!Visitor::current()->group->can("change_settings"))
  1662. show_403(__("Access Denied"), __("You do not have sufficient privileges to change settings."));
  1663. if (empty($_POST))
  1664. return $this->display("content_settings");
  1665. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  1666. show_403(__("Access Denied"), __("Invalid security key."));
  1667. $config = Config::current();
  1668. $set = array($config->set("posts_per_page", $_POST['posts_per_page']),
  1669. $config->set("feed_items", $_POST['feed_items']),
  1670. $config->set("feed_url", $_POST['feed_url']),
  1671. $config->set("uploads_path", $_POST['uploads_path']),
  1672. $config->set("enable_trackbacking", !empty($_POST['enable_trackbacking'])),
  1673. $config->set("send_pingbacks", !empty($_POST['send_pingbacks'])),
  1674. $config->set("enable_xmlrpc", !empty($_POST['enable_xmlrpc'])),
  1675. $config->set("enable_ajax", !empty($_POST['enable_ajax'])));
  1676. if (!in_array(false, $set))
  1677. Flash::notice(__("Settings updated."), "/admin/?action=content_settings");
  1678. }
  1679. /**
  1680. * Function: route_settings
  1681. * Route Settings page.
  1682. */
  1683. public function route_settings() {
  1684. if (!Visitor::current()->group->can("change_settings"))
  1685. show_403(__("Access Denied"), __("You do not have sufficient privileges to change settings."));
  1686. if (empty($_POST))
  1687. return $this->display("route_settings");
  1688. if (!isset($_POST['hash']) or $_POST['hash'] != Config::current()->secure_hashkey)
  1689. show_403(__("Access Denied"), __("Invalid security key."));
  1690. $config = Config::current();
  1691. $set = array($config->set("clean_urls", !empty($_POST['clean_urls'])),
  1692. $config->set("post_url", $_POST['post_url']));
  1693. if (!in_array(false, $set))
  1694. Flash::notice(__("Settings updated."), "/admin/?action=route_settings");
  1695. }
  1696. /**
  1697. * Function: help
  1698. * Sets the $title and $body for various help IDs.
  1699. */
  1700. public function help() {
  1701. list($title, $body) = Trigger::current()->call("help_".$_GET['id']);
  1702. switch($_GET['id']) {
  1703. case "filtering_results":
  1704. $title = __("Filtering Results");
  1705. $body = "<p>".__("Use this to search for specific items. You can either enter plain text to match the item with, or use keywords:")."</pre>";
  1706. $body.= "<h2>".__("Keywords")."</h2>";
  1707. $body.= "<cite><strong>".__("Usage")."</strong>: <code>attr:val</code></cite>\n".__("Use this syntax to quickly match specific results. Keywords will modify the query to match items where <code>attr</code> is equal to <code>val</code> (case insensitive).");
  1708. break;
  1709. case "slugs":
  1710. $title = __("Post Slugs");
  1711. $body = __("Post slugs are strings to use for the URL of a post. They are directly respondible for the <code>(url)</code> attribute in a post's clean URL, or the <code>/?action=view&amp;url=<strong>foo</strong></code> in a post's dirty URL. A post slug should not contain any special characters other than hyphens.");
  1712. break;
  1713. case "trackbacks":
  1714. $title = __("Trackbacks");
  1715. $body = __("Trackbacks are special urls to posts from other blogs that your post is related to or references. The other blog will be notified of your post, and in some cases a comment will automatically be added to the post in question linking back to your post. It's basically a way to network between blogs via posts.");
  1716. break;
  1717. case "alternate_urls":
  1718. $title = __("Alternate URL");
  1719. $body = "<p>".__("An alternate URL will allow you to keep Chyrp in its own directory, while having your site URLs point to someplace else. For example, you could have Chyrp in a <code>/chyrp</code> directory, and have your site at <code>/</code>. There are two requirements for this to work.")."</p>\n\n";
  1720. $body.= "<ol>\n\t<li>".__("Create an <code>index.php</code> file in your destination directory with the following in it:")."\n\n";
  1721. $body.= "<pre><code>&lt;?php
  1722. require \"path/to/chyrp/index.php\";
  1723. ?&gt;</code></pre>";
  1724. $body.= "</li>\n\t<li>".__("Move the .htaccess file from the original Chyrp directory, and change the <code>RewriteBase</code> line to reflect the new website location.")."</li>\n</ol>";
  1725. }
  1726. require "help.php";
  1727. }
  1728. /**
  1729. * Function: subnav_context
  1730. * Generates the context variables for the subnav.
  1731. */
  1732. public function subnav_context($action) {
  1733. $trigger = Trigger::current();
  1734. $visitor = Visitor::current();
  1735. $this->context["subnav"] = array();
  1736. $subnav =& $this->context["subnav"];
  1737. $subnav["write"] = array();
  1738. $pages = array("manage" => array());
  1739. foreach (Config::current()->enabled_feathers as $index => $feather) {
  1740. $info = YAML::load(FEATHERS_DIR."/".$feather."/info.yaml");
  1741. $subnav["write"]["write_post&feather=".$feather] = array("title" => __($info["name"], $feather),
  1742. "show" => $visitor->group->can("add_draft", "add_post"),
  1743. "attributes" => ' id="list_feathers['.$feather.']"',
  1744. "selected" => (isset($_GET['feather']) and $_GET['feather'] == $feather) or
  1745. (!isset($_GET['feather']) and $action == "write_post" and !$index));
  1746. }
  1747. # Write navs
  1748. $subnav["write"]["write_page"] = array("title" => __("Page"),
  1749. "show" => $visitor->group->can("add_page"));
  1750. $trigger->filter($subnav["write"], array("admin_write_nav", "write_nav"));
  1751. $pages["write"] = array_merge(array("write_post"), array_keys($subnav["write"]));;
  1752. # Manage navs
  1753. $subnav["manage"] = array("manage_posts" => array("title" => __("Posts"),
  1754. "show" => (Post::any_editable() or Post::any_deletable()),
  1755. "selected" => array("edit_post", "delete_post")),
  1756. "manage_pages" => array("title" => __("Pages"),
  1757. "show" => ($visitor->group->can("edit_page", "delete_page")),
  1758. "selected" => array("edit_page", "delete_page")),
  1759. "manage_users" => array("title" => __("Users"),
  1760. "show" => ($visitor->group->can("add_user",
  1761. "edit_user",
  1762. "delete_user")),
  1763. "selected" => array("edit_user", "delete_user", "new_user")),
  1764. "manage_groups" => array("title" => __("Groups"),
  1765. "show" => ($visitor->group->can("add_group",
  1766. "edit_group",
  1767. "delete_group")),
  1768. "selected" => array("edit_group", "delete_group", "new_group")));
  1769. $trigger->filter($subnav["manage"], "manage_nav");
  1770. $subnav["manage"]["import"] = array("title" => __("Import"),
  1771. "show" => ($visitor->group->can("add_post")));
  1772. $subnav["manage"]["export"] = array("title" => __("Export"),
  1773. "show" => ($visitor->group->can("add_post")));
  1774. $pages["manage"][] = "new_user";
  1775. $pages["manage"][] = "new_group";
  1776. foreach (array_keys($subnav["manage"]) as $manage)
  1777. $pages["manage"] = array_merge($pages["manage"], array($manage,
  1778. preg_replace("/manage_(.+)/e",
  1779. "'edit_'.depluralize('\\1')",
  1780. $manage),
  1781. preg_replace("/manage_(.+)/e",
  1782. "'delete_'.depluralize('\\1')",
  1783. $manage)));
  1784. # Settings navs
  1785. $subnav["settings"] = array("general_settings" => array("title" => __("General"),
  1786. "show" => $visitor->group->can("change_settings")),
  1787. "content_settings" => array("title" => __("Content"),
  1788. "show" => $visitor->group->can("change_settings")),
  1789. "user_settings" => array("title" => __("Users"),
  1790. "show" => $visitor->group->can("change_settings")),
  1791. "route_settings" => array("title" => __("Routes"),
  1792. "show" => $visitor->group->can("change_settings")));
  1793. $trigger->filter($subnav["settings"], "settings_nav");
  1794. $pages["settings"] = array_keys($subnav["settings"]);
  1795. # Extend navs
  1796. $subnav["extend"] = array("modules" => array("title" => __("Modules"),
  1797. "show" => $visitor->group->can("toggle_extensions")),
  1798. "feathers" => array("title" => __("Feathers"),
  1799. "show" => $visitor->group->can("toggle_extensions")),
  1800. "themes" => array("title" => __("Themes"),
  1801. "show" => $visitor->group->can("toggle_extensions")));
  1802. $trigger->filter($subnav["extend"], "extend_nav");
  1803. $pages["extend"] = array_keys($subnav["extend"]);
  1804. foreach (array_keys($subnav) as $main_nav)
  1805. foreach ($trigger->filter($pages[$main_nav], $main_nav."_nav_pages") as $extend)
  1806. $subnav[$extend] =& $subnav[$main_nav];
  1807. foreach ($subnav as $main_nav => &$sub_nav)
  1808. foreach ($sub_nav as &$nav)
  1809. $nav["show"] = (!isset($nav["show"]) or $nav["show"]);
  1810. $trigger->filter($subnav, "admin_subnav");
  1811. }
  1812. /**
  1813. * Function: display
  1814. * Renders the page.
  1815. *
  1816. * Parameters:
  1817. * $action - The template file to display, in (theme dir)/pages.
  1818. * $context - Context for the template.
  1819. * $title - The title for the page. Defaults to a camlelization of the action, e.g. foo_bar -> Foo Bar.
  1820. */
  1821. public function display($action, $context = array(), $title = "") {
  1822. $this->displayed = true;
  1823. fallback($title, camelize($action, true));
  1824. $this->context = array_merge($context, $this->context);
  1825. $trigger = Trigger::current();
  1826. $trigger->filter($this->context, array("admin_context", "admin_context_".str_replace("/", "_", $action)));
  1827. # Are there any extension-added pages?
  1828. foreach (array("write" => array(),
  1829. "manage" => array("import", "export"),
  1830. "settings" => array(),
  1831. "extend" => array("modules", "feathers", "themes")) as $main_nav => $val) {
  1832. $$main_nav = $val;
  1833. $trigger->filter($$main_nav, $main_nav."_pages");
  1834. }
  1835. $visitor = Visitor::current();
  1836. $route = Route::current();
  1837. $this->context["theme"] = Theme::current();
  1838. $this->context["flash"] = Flash::current();
  1839. $this->context["trigger"] = $trigger;
  1840. $this->context["title"] = $title;
  1841. $this->context["site"] = Config::current();
  1842. $this->context["visitor"] = $visitor;
  1843. $this->context["logged_in"] = logged_in();
  1844. $this->context["route"] = $route;
  1845. $this->context["hide_admin"] = isset($_SESSION["hide_admin"]);
  1846. $this->context["now"] = time();
  1847. $this->context["version"] = CHYRP_VERSION;
  1848. $this->context["debug"] = DEBUG;
  1849. $this->context["feathers"] = Feathers::$instances;
  1850. $this->context["modules"] = Modules::$instances;
  1851. $this->context["admin_theme"] = $this->admin_theme;
  1852. $this->context["theme_url"] = Config::current()->chyrp_url."/admin/themes/".$this->admin_theme;
  1853. $this->context["POST"] = $_POST;
  1854. $this->context["GET"] = $_GET;
  1855. $this->context["navigation"] = array();
  1856. $show = array("write" => array($visitor->group->can("add_draft", "add_post", "add_page")),
  1857. "manage" => array($visitor->group->can("view_own_draft",
  1858. "view_draft",
  1859. "edit_own_draft",
  1860. "edit_own_post",
  1861. "edit_post",
  1862. "delete_own_draft",
  1863. "delete_own_post",
  1864. "delete_post",
  1865. "add_page",
  1866. "edit_page",
  1867. "delete_page",
  1868. "add_user",
  1869. "edit_user",
  1870. "delete_user",
  1871. "add_group",
  1872. "edit_group",
  1873. "delete_group")),
  1874. "settings" => array($visitor->group->can("change_settings")),
  1875. "extend" => array($visitor->group->can("toggle_extensions")));
  1876. foreach ($show as $name => &$arr)
  1877. $trigger->filter($arr, $name."_nav_show");
  1878. $this->context["navigation"]["write"] = array("title" => __("Write"),
  1879. "show" => in_array(true, $show["write"]),
  1880. "selected" => (in_array($action, $write) or
  1881. match("/^write_/", $action)));
  1882. $this->context["navigation"]["manage"] = array("title" => __("Manage"),
  1883. "show" => in_array(true, $show["manage"]),
  1884. "selected" => (in_array($action, $manage) or
  1885. match(array("/^manage_/",
  1886. "/^edit_/",
  1887. "/^delete_/",
  1888. "/^new_/"), $action)));
  1889. $this->context["navigation"]["settings"] = array("title" => __("Settings"),
  1890. "show" => in_array(true, $show["settings"]),
  1891. "selected" => (in_array($action, $settings) or
  1892. match("/_settings$/", $action)));
  1893. $this->context["navigation"]["extend"] = array("title" => __("Extend"),
  1894. "show" => in_array(true, $show["extend"]),
  1895. "selected" => (in_array($action, $extend)));
  1896. $this->subnav_context($route->action);
  1897. $trigger->filter($this->context["selected"], "nav_selected");
  1898. $this->context["sql_debug"] = SQL::current()->debug;
  1899. $file = MAIN_DIR."/admin/themes/%s/pages/".$action.".twig";
  1900. $template = file_exists(sprintf($file, $this->admin_theme)) ?
  1901. sprintf($file, $this->admin_theme) :
  1902. sprintf($file, "default");
  1903. $config = Config::current();
  1904. if (!file_exists($template)) {
  1905. foreach (array(MODULES_DIR => $config->enabled_modules,
  1906. FEATHERS_DIR => $config->enabled_feathers) as $path => $try)
  1907. foreach ($try as $extension)
  1908. if (file_exists($path."/".$extension."/pages/admin/".$action.".twig"))
  1909. $template = $path."/".$extension."/pages/admin/".$action.".twig";
  1910. if (!file_exists($template))
  1911. error(__("Template Missing"), _f("Couldn't load template: <code>%s</code>", array($template)));
  1912. }
  1913. # Try the theme first
  1914. try {
  1915. $this->theme->getTemplate($template)->display($this->context);
  1916. } catch (Exception $t) {
  1917. # Fallback to the default
  1918. try {
  1919. $this->default->getTemplate($template)->display($this->context);
  1920. } catch (Exception $e) {
  1921. $prettify = preg_replace("/([^:]+): (.+)/", "\\1: <code>\\2</code>", $e->getMessage());
  1922. $trace = debug_backtrace();
  1923. $twig = array("file" => $e->filename, "line" => $e->lineno);
  1924. array_unshift($trace, $twig);
  1925. error(__("Error"), $prettify, $trace);
  1926. }
  1927. }
  1928. }
  1929. /**
  1930. * Function: current
  1931. * Returns a singleton reference to the current class.
  1932. */
  1933. public static function & current() {
  1934. static $instance = null;
  1935. return $instance = (empty($instance)) ? new self() : $instance ;
  1936. }
  1937. }