Beispiel #1
0
 public function checkInput(array $args = array(), $suppress = 0, $priority = 'dd')
 {
     $isvalid = parent::checkInput($args, $suppress, $priority);
     // If the rest of the publication is valid, then do the access part
     // Note this is a collection of access properties; hence the complicated process of saving it
     if ($isvalid) {
         $access = DataPropertyMaster::getProperty(array('name' => 'access'));
         $prefix = $this->getFieldPrefix();
         // Only ignore the prefix if we are CREATING the base document
         // A translation would have a prefix of 0, which is valid
         if (empty($prefix) && $prefix !== '0') {
             $name = "dd_" . $this->properties['access']->id;
         } else {
             $name = $prefix . "_dd_" . $this->properties['access']->id;
         }
         $validprop = $access->checkInput($name . "_display");
         $displayaccess = $access->value;
         $isvalid = $isvalid && $validprop;
         $validprop = $access->checkInput($name . "_modify");
         $modifyaccess = $access->value;
         $isvalid = $isvalid && $validprop;
         $validprop = $access->checkInput($name . "_delete");
         $deleteaccess = $access->value;
         $isvalid = $isvalid && $validprop;
         $allaccess = array('display' => $displayaccess, 'modify' => $modifyaccess, 'delete' => $deleteaccess);
         $this->properties['access']->setValue($allaccess);
     }
     return $isvalid;
 }
Beispiel #2
0
 public function checkInput($name = '', $value = null)
 {
     $name = empty($name) ? 'dd_' . $this->id : $name;
     // store the fieldname for validations who need them (e.g. file uploads)
     $this->fieldname = $name;
     if (!isset($value)) {
         $invalid = array();
         $validity = true;
         $value = array();
         $textbox = DataPropertyMaster::getProperty(array('name' => 'textbox'));
         $textbox->validation_min_length = 3;
         for ($i = 1; $i <= $this->display_rows; $i++) {
             $isvalid = $textbox->checkInput($name . '_line_' . $i);
             if ($isvalid) {
                 $value['line_' . $i] = $textbox->value;
             } else {
                 $invalid[] = 'line_' . $i;
             }
             $validity = $validity && $isvalid;
         }
         if ($this->display_show_city) {
             $isvalid = $textbox->checkInput($name . '_city');
             if ($isvalid) {
                 $value['city'] = $textbox->value;
             } else {
                 $invalid[] = 'city';
             }
             $validity = $validity && $isvalid;
         }
         if ($this->display_show_province) {
             $province = DataPropertyMaster::getProperty(array('name' => 'statelisting'));
             $isvalid = $province->checkInput($name . '_province');
             if ($isvalid) {
                 $value['province'] = $province->value;
             } else {
                 $invalid[] = 'province';
             }
             $validity = $validity && $isvalid;
         }
         if ($this->display_show_postal_code) {
             list($isvalid, $value['postal_code']) = $this->fetchValue($name . '_postal_code');
             $validity = $validity && $isvalid;
         }
         if ($this->display_show_country) {
             $country = DataPropertyMaster::getProperty(array('name' => 'countrylisting'));
             $isvalid = $country->checkInput($name . '_country');
             if ($isvalid) {
                 $value['country'] = $country->value;
             } else {
                 $invalid[] = 'country';
             }
             $validity = $validity && $isvalid;
         }
     }
     if (!empty($invalid)) {
         $this->invalid = implode(',', $invalid);
     }
     $this->value = serialize($value);
     return $validity;
 }
Beispiel #3
0
/**
 * Publications Module
 *
 * @package modules
 * @subpackage publications module
 * @category Third Party Xaraya Module
 * @version 2.0.0
 * @copyright (C) 2011 Netspan AG
 * @license GPL {@link http://www.gnu.org/licenses/gpl.html}
 * @author Marc Lutolf <*****@*****.**>
 */
function publications_user_view_pages($args)
{
    extract($args);
    if (!xarSecurityCheck('ManagePublications')) {
        return;
    }
    // Accept a parameter to allow selection of a single tree.
    xarVarFetch('contains', 'id', $contains, 0, XARVAR_NOT_REQUIRED);
    $data = xarMod::apiFunc('publications', 'user', 'getpagestree', array('key' => 'index', 'dd_flag' => false, 'tree_contains_pid' => $contains));
    if (empty($data['pages'])) {
        // TODO: pass to template.
        return $data;
        //xarML('NO PAGES DEFINED');
    } else {
        $data['pages'] = xarMod::apiFunc('publications', 'tree', 'array_maptree', $data['pages']);
    }
    $data['contains'] = $contains;
    // Check modify and delete privileges on each page.
    // EditPage - allows basic changes, but no moving or renaming (good for sub-editors who manage content)
    // AddPage - new pages can be added (further checks may limit it to certain page types)
    // DeletePage - page can be renamed, moved and deleted
    if (!empty($data['pages'])) {
        // Bring in the access property for security checks
        sys::import('modules.dynamicdata.class.properties.master');
        $accessproperty = DataPropertyMaster::getProperty(array('name' => 'access'));
        $accessproperty->module = 'publications';
        $accessproperty->component = 'Page';
        foreach ($data['pages'] as $key => $page) {
            $thisinstance = $page['name'] . ':' . $page['ptid']['name'];
            // Do we have admin access?
            $args = array('instance' => $thisinstance, 'level' => 800);
            $adminaccess = $accessproperty->check($args);
            // Decide whether this page can be modified by the current user
            /*try {
                  $args = array(
                      'instance' => $thisinstance,
                      'group' => $page['access']['modify_access']['group'],
                      'level' => $page['access']['modify_access']['level'],
                  );
              } catch (Exception $e) {
                  $args = array();
              }*/
            $data['pages'][$key]['edit_allowed'] = $adminaccess || $accessproperty->check($args);
            /*
                        // Decide whether this page can be deleted by the current user
                       try {
                            $args = array(
                                'instance' => $thisinstance,
                                'group' => $page['access']['delete_access']['group'],
                                'level' => $page['access']['delete_access']['level'],
                            );
                        } catch (Exception $e) {
                            $args = array();
                        }*/
            $data['pages'][$key]['delete_allowed'] = $adminaccess || $accessproperty->check($args);
        }
    }
    return $data;
}
Beispiel #4
0
function publications_admin_updateconfig()
{
    // Confirm authorisation code
    if (!xarSecConfirmAuthKey()) {
        return;
    }
    // Get parameters
    //A lot of these probably are bools, still might there be a need to change the template to return
    //'true' and 'false' to use those...
    if (!xarVarFetch('settings', 'array', $settings, array(), XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('usetitleforurl', 'int', $usetitleforurl, xarModVars::get('publications', 'usetitleforurl'), XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('defaultstate', 'isset', $defaultstate, 0, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('defaultsort', 'isset', $defaultsort, 'date', XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('usealias', 'int', $usealias, 0, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('ptid', 'isset', $ptid, xarModVars::get('publications', 'defaultpubtype'), XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('multilanguage', 'int', $multilanguage, 0, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('tab', 'str:1:10', $data['tab'], 'global', XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarSecurityCheck('AdminPublications', 1, 'Publication', "{$ptid}:All:All:All")) {
        return;
    }
    if ($data['tab'] == 'global') {
        if (!xarVarFetch('defaultpubtype', 'isset', $defaultpubtype, 1, XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!xarVarFetch('sortpubtypes', 'isset', $sortpubtypes, 'id', XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!xarVarFetch('defaultlanguage', 'str:1:100', $defaultlanguage, xarModVars::get('publications', 'defaultlanguage'), XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!xarVarFetch('debugmode', 'checkbox', $debugmode, xarModVars::get('publications', 'debugmode'), XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!xarVarFetch('defaultfrontpage', 'str', $defaultfrontpage, xarModVars::get('publications', 'defaultfrontpage'), XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!xarVarFetch('defaultbackpage', 'str', $defaultbackpage, xarModVars::get('publications', 'defaultbackpage'), XARVAR_NOT_REQUIRED)) {
            return;
        }
        xarModVars::set('publications', 'defaultpubtype', $defaultpubtype);
        xarModVars::set('publications', 'sortpubtypes', $sortpubtypes);
        xarModVars::set('publications', 'defaultlanguage', $defaultlanguage);
        xarModVars::set('publications', 'debugmode', $debugmode);
        xarModVars::set('publications', 'usealias', $usealias);
        xarModVars::set('publications', 'usetitleforurl', $usetitleforurl);
        xarModVars::set('publications', 'defaultfrontpage', $defaultfrontpage);
        xarModVars::set('publications', 'defaultbackpage', $defaultbackpage);
        // Allow multilanguage only if the languages property is present
        sys::import('modules.dynamicdata.class.properties.registration');
        $types = PropertyRegistration::Retrieve();
        if (isset($types[30039])) {
            xarModVars::set('publications', 'multilanguage', $multilanguage);
        } else {
            xarModVars::set('publications', 'multilanguage', 0);
        }
        // Get the special pages.
        foreach (array('defaultpage', 'errorpage', 'notfoundpage', 'noprivspage') as $special_name) {
            unset($special_id);
            if (!xarVarFetch($special_name, 'id', $special_id, 0, XARVAR_NOT_REQUIRED)) {
                return;
            }
            xarModVars::set('publications', $special_name, $special_id);
        }
        if (xarDB::getType() == 'mysql') {
            if (!xarVarFetch('fulltext', 'isset', $fulltext, '', XARVAR_NOT_REQUIRED)) {
                return;
            }
            $oldval = xarModVars::get('publications', 'fulltextsearch');
            $index = 'i_' . xarDB::getPrefix() . '_publications_fulltext';
            if (empty($fulltext) && !empty($oldval)) {
                // Get database setup
                $dbconn = xarDB::getConn();
                $xartable = xarDB::getTables();
                $publicationstable = $xartable['publications'];
                // Drop fulltext index on publications table
                $query = "ALTER TABLE {$publicationstable} DROP INDEX {$index}";
                $result =& $dbconn->Execute($query);
                if (!$result) {
                    return;
                }
                xarModVars::set('publications', 'fulltextsearch', '');
            } elseif (!empty($fulltext) && empty($oldval)) {
                $searchfields = array('title', 'description', 'summary', 'body1', 'notes');
                //                $searchfields = explode(',',$fulltext);
                // Get database setup
                $dbconn = xarDB::getConn();
                $xartable = xarDB::getTables();
                $publicationstable = $xartable['publications'];
                // Add fulltext index on publications table
                $query = "ALTER TABLE {$publicationstable} ADD FULLTEXT {$index} (" . join(', ', $searchfields) . ")";
                $result =& $dbconn->Execute($query);
                if (!$result) {
                    return;
                }
                xarModVars::set('publications', 'fulltextsearch', join(',', $searchfields));
            }
        }
        // Module settings
        $data['module_settings'] = xarMod::apiFunc('base', 'admin', 'getmodulesettings', array('module' => 'publications'));
        $data['module_settings']->setFieldList('items_per_page, use_module_alias, module_alias_name, enable_short_urls, user_menu_link', 'use_module_icons');
        $isvalid = $data['module_settings']->checkInput();
        if (!$isvalid) {
            return xarTplModule('base', 'admin', 'modifyconfig', $data);
        } else {
            $itemid = $data['module_settings']->updateItem();
        }
        // Pull the base category ids from the template and save them
        $picker = DataPropertyMaster::getProperty(array('name' => 'categorypicker'));
        $picker->checkInput('basecid');
    } elseif ($data['tab'] == 'pubtypes') {
        // Get the publication type for this display and save the settings to it
        $pubtypeobject = DataObjectMaster::getObject(array('name' => 'publications_types'));
        $pubtypeobject->getItem(array('itemid' => $ptid));
        $configsettings = $pubtypeobject->properties['configuration']->getValue();
        $checkbox = DataPropertyMaster::getProperty(array('name' => 'checkbox'));
        $boxes = array('show_hitount', 'show_ratings', 'show_keywords', 'show_comments', 'show_prevnext', 'show_archives', 'show_publinks', 'show_pubcount', 'show_map', 'prevnextart', 'dot_transform', 'title_transform', 'show_categories', 'show_catcount', 'show_prevnext', 'allow_translations');
        foreach ($boxes as $box) {
            $isvalid = $checkbox->checkInput($box);
            if ($isvalid) {
                $settings[$box] = $checkbox->value;
            }
        }
        //        foreach ($configsettings as $key => $value)
        //            if (!isset($settings[$key])) $settings[$key] = 0;
        $isvalid = true;
        // Get the default access rules
        $access = DataPropertyMaster::getProperty(array('name' => 'access'));
        $validprop = $access->checkInput("access_add");
        $addaccess = $access->value;
        $isvalid = $isvalid && $validprop;
        $validprop = $access->checkInput("access_display");
        $displayaccess = $access->value;
        $isvalid = $isvalid && $validprop;
        $validprop = $access->checkInput("access_modify");
        $modifyaccess = $access->value;
        $isvalid = $isvalid && $validprop;
        $validprop = $access->checkInput("access_delete");
        $deleteaccess = $access->value;
        $isvalid = $isvalid && $validprop;
        $allaccess = array('add' => $addaccess, 'display' => $displayaccess, 'modify' => $modifyaccess, 'delete' => $deleteaccess);
        $pubtypeobject->properties['access']->setValue(serialize($allaccess));
        $pubtypeobject->properties['configuration']->setValue(serialize($settings));
        $pubtypeobject->updateItem(array('itemid' => $ptid));
        $pubtypes = xarModAPIFunc('publications', 'user', 'get_pubtypes');
        if ($usealias) {
            xarModSetAlias($pubtypes[$ptid]['name'], 'publications');
        } else {
            xarModDelAlias($pubtypes[$ptid]['name'], 'publications');
        }
    } elseif ($data['tab'] == 'redirects') {
        $redirects = DataPropertyMaster::getProperty(array('name' => 'array'));
        $redirects->display_column_definition['value'] = array(array("From", "To"), array(2, 2), array("", ""), array("", ""));
        $isvalid = $redirects->checkInput("redirects");
        xarModVars::set('publications', 'redirects', $redirects->value);
    }
    xarController::redirect(xarModURL('publications', 'admin', 'modifyconfig', array('ptid' => $ptid, 'tab' => $data['tab'])));
    return true;
}
Beispiel #5
0
function publications_userapi_getpages($args)
{
    extract($args);
    if (!xarVarValidate('enum:id:index:name:left:right', $key, true)) {
        $key = 'index';
    }
    // Define if we are looking for the number of pages or the pages themselves
    $count = empty($count) ? false : true;
    // Assemble the query
    sys::import('xaraya.structures.query');
    $xartable = xarDB::getTables();
    $q = new Query();
    $q->addtable($xartable['publications'], 'tpages');
    $q->addtable($xartable['publications_types'], 'pt');
    $q->join('pt.id', 'tpages.pubtype_id');
    if ($count) {
        $q->addfield('COUNT(*)');
    } else {
        $q->setdistinct(true);
        $q->addfield('tpages.id AS id');
        $q->addfield('tpages.name AS name');
        $q->addfield('tpages.title AS title');
        $q->addfield('tpages.pubtype_id AS ptid');
        $q->addfield('tpages.parent_id AS base_id');
        $q->addfield('tpages.sitemap_flag AS sitemap_flag');
        $q->addfield('tpages.menu_flag AS menu_flag');
        $q->addfield('tpages.locale AS locale');
        $q->addfield('tpages.leftpage_id AS leftpage_id');
        $q->addfield('tpages.rightpage_id AS rightpage_id');
        $q->addfield('tpages.parentpage_id AS parentpage');
        $q->addfield('tpages.access AS access');
        $q->addfield('tpages.state AS status');
        $q->addfield('pt.description AS pubtype_name');
    }
    if (isset($baseonly)) {
        $q->eq('tpages.parent_id', 0);
    }
    if (isset($name)) {
        $q->eq('tpages.name', (string) $name);
    }
    if (isset($status)) {
        // If a list of statuses have been provided, then select for any of them.
        if (strpos($status, ',') === false) {
            $numeric_status = convert_status($status);
            $q->eq('tpages.state', strtoupper($status));
        } else {
            $statuses = explode(',', strtoupper($status));
            $numeric_statuses = array();
            foreach ($statuses as $stat) {
                $numeric_statuses[] = convert_status($stat);
            }
            $q->in('tpages.state', $numeric_statuses);
        }
    }
    if (isset($id)) {
        $q->eq('tpages.id', (int) $id);
        $where[] = 'tpages.id = ?';
        $bind[] = (int) $id;
    } elseif (!empty($ids)) {
        $addwhere = array();
        foreach ($ids as $myid) {
            if (!empty($myid) && is_numeric($myid)) {
                $addwhere[] = (int) $myid;
            }
        }
        $q->in('tpages.state', $addwhere);
    }
    if (isset($itemtype)) {
        $q->eq('tpages.pubtype_id', (int) $itemtype);
    }
    if (isset($parent)) {
        $q->eq('tpages.parentpage_id', (int) $parent);
    }
    // Used to retrieve descendants.
    if (isset($left_range) && is_array($left_range)) {
        $q->between('tpages.leftpage_id', $left_range);
    }
    // Used to prune a single branch of the tree.
    if (isset($left_exclude) && is_array($left_exclude)) {
        //'tpages.leftpage_id NOT between ? AND ?' - does not work on some databases
        $c[] = $q->plt('tpages.leftpage_id', (int) $left_exclude[0]);
        $c[] = $q->pgt('tpages.leftpage_id', (int) $left_exclude[1]);
        $q->qor($c);
        unset($c);
    }
    // Used to retrieve ancestors.
    if (isset($wrap_range) && is_numeric($wrap_range)) {
        $c[] = $q->ple('tpages.leftpage_id', (int) $wrap_range[0]);
        $c[] = $q->pge('tpages.leftpage_id', (int) $left_range[1]);
        // can't be right: this is an array
        $q->qand($c);
        unset($c);
    }
    // If the request is to fetch a tree that *contains* a particular
    // page, then add the extra sub-queries in here.
    if (!empty($tree_contains_id) || !empty($tree_contains_name)) {
        $q->addtable($xartable['publications'], 'tpages_member');
        if (!empty($tree_contains_id)) {
            $q->eq('tpages_member.id', (int) $tree_contains_id);
        }
        if (!empty($tree_contains_name)) {
            $q->eq('tpages_member.name', (int) $tree_contains_name);
        }
        if (!empty($tree_ancestors)) {
            // We don't want the complete tree for the matching pages - just
            // their ancestors. This is useful for checking paths, without
            // fetching complete trees.
            $q->between('tpages_member.leftpage_id', 'expr:tpages.leftpage_id AND tpages.rightpage_id');
        } else {
            // Join to find the root page of the tree containing the required page.
            // This matches the complete tree for the root under the selected page.
            $q->addtable($xartable['publications'], 'tpages_root');
            $q->le('tpages_root.leftpage_id', 'expr:tpages_member.leftpage_id');
            $q->ge('tpages_root.rightpage_id', 'expr:tpages_member.rightpage_id');
            $q->between('tpages.leftpage_id', 'expr:tpages_root.leftpage_id AND tpages_root.rightpage_id');
            $q->eq('tpages_root.parentpage_id', 0);
        }
    }
    // This ordering cannot be changed
    // We want the pages in the order of the hierarchy.
    if (empty($count)) {
        $q->setorder('tpages.leftpage_id', 'ASC');
    }
    //    $q->qecho();
    $q->run();
    if ($count) {
        $pages = count($q->output());
    } else {
        $index = 0;
        $id2key = array();
        $pages = array();
        // Get all the page type details.
        $pagetypes = xarMod::apiFunc('publications', 'user', 'get_pubtypes', array('key' => 'id'));
        foreach ($q->output() as $row) {
            $id = (int) $row['id'];
            // At this point check the privileges of the page fetched.
            // To prevent broken trees, if a page is not assessible, prune
            // (ie discard) descendant pages of that page. Descendants will have
            // a left value between the left and right values of the
            // inaccessible page.
            if (!empty($prune_left)) {
                if ($row['leftpage_id'] <= $prune_left) {
                    // The current page is still a descendant of the unprivileged page.
                    continue;
                } else {
                    // We've reached a non-descendant - stop pruning now.
                    $prune_left = 0;
                }
            }
            // JDJ 2008-06-11: now only need ViewPublicationsPage to be able to select the page,
            // but ReadPublicationsPage to actually read it.
            // The lowest privilege will be inherited, so one page with only View privilege
            // will cause all descendent pages to have, at most, view privilege.
            // We still need to fetch full details of these view-only pages, but we must flag
            // then up in some way (status?). Displaying any of these pages would instead just
            // show the 'no privs' page.
            // Define admin access
            sys::import('modules.dynamicdata.class.properties.master');
            $accessproperty = DataPropertyMaster::getProperty(array('name' => 'access'));
            $typename = $pagetypes[$row['ptid']]['name'];
            $args = array('instance' => $row['name'] . ":" . $typename, 'level' => 800);
            $adminaccess = $accessproperty->check($args);
            $info = unserialize($row['access']);
            if (!empty($info['view_access'])) {
                // Decide whether the current user can create blocks of this type
                $args = array('module' => 'publications', 'component' => 'Page', 'instance' => $name . ":" . $typename, 'group' => $info['view_access']['group'], 'level' => $info['view_access']['level']);
                if (!$accessproperty->check($args)) {
                    // Save the right value. We need to skip all subsequent
                    // pages until we get to a page to the right of this one.
                    // The pages will be in 'left' order, so the descendants
                    // will be contiguous and will immediately follow this page.
                    $prune_left = $rightpage_id;
                    // Don't get this unless you are an admin
                    if (!$adminaccess) {
                        continue;
                    }
                }
            }
            if (!empty($overview_only_left) && $row['leftpage_id'] <= $overview_only_left) {
                // We have got past the overview-only page, so can reset the flag.
                $overview_only_left = 0;
            }
            if (!empty($info['display_access'])) {
                $args = array('module' => 'publications', 'component' => 'Page', 'instance' => $name . ":" . $typename, 'group' => $info['display_access']['group'], 'level' => $info['display_access']['level']);
                if (!$accessproperty->check($args)) {
                    // We have reached a page that allows only overview access.
                    // Flag all pages with the restricted view until we get past this page.
                    $overview_only_left = $row['rightpage_id'];
                    // Don't get this unless you are an admin
                    if (!$adminaccess) {
                        continue;
                    }
                }
            }
            if (!xarSecurityCheck('ReadPublications', 0, 'Page', $row['name'] . ':' . $typename, 'publications')) {
                // We have reached a page that allows only overview access.
                // Flag all pages with the restricted view until we get past this page.
                $overview_only_left = $row['rightpage_id'];
            }
            // Note: ['parent_id'] is the parent page ID,
            // but ['parent'] is the parent item key in the
            // pages array.
            $id2key[(int) $id] = ${$key};
            if ($key == 'id') {
                $parent_key = (int) $row['parentpage'];
            } else {
                if (isset($id2key[$row['parentpage']])) {
                    $parent_key = $id2key[$row['parentpage']];
                } else {
                    $parent_key = 0;
                }
            }
            $row['key'] = ${$key};
            $row['access'] = $info;
            $row['parent_key'] = (int) $parent_key;
            $row['left'] = (int) $row['leftpage_id'];
            $row['right'] = (int) $row['rightpage_id'];
            unset($row['leftpage_id']);
            unset($row['rightpage_id']);
            $pages[${$key}] = $row;
            $index += 1;
        }
    }
    return $pages;
}
Beispiel #6
0
/**
 * Import an object definition or an object item from XML
 */
function publications_adminapi_importpubtype($args)
{
    // Security check - we require ADMIN rights here
    if (!xarSecurityCheck('AdminPublications')) {
        return;
    }
    extract($args);
    if (empty($xml) && empty($file)) {
        $msg = xarML('Missing import file or XML content');
        throw new BadParameterException(null, $msg);
    } elseif (!empty($file) && (!file_exists($file) || !preg_match('/\\.xml$/', $file))) {
        $msg = xarML('Invalid import file');
        throw new BadParameterException(null, $msg);
    }
    $pubtypes = xarModAPIFunc('publications', 'user', 'get_pubtypes');
    $proptypes = DataPropertyMaster::getPropertyTypes();
    $name2id = array();
    foreach ($proptypes as $propid => $proptype) {
        $name2id[$proptype['name']] = $propid;
    }
    $prefix = xarDB::getPrefix();
    $prefix .= '_';
    if (!empty($file)) {
        $fp = @fopen($file, 'r');
        if (!$fp) {
            $msg = xarML('Unable to open import file');
            throw new BadParameterException(null, $msg);
        }
    } else {
        $lines = preg_split("/\r?\n/", $xml);
        $maxcount = count($lines);
    }
    $what = '';
    $count = 0;
    $ptid = 0;
    $objectname2objectid = array();
    $objectcache = array();
    $objectmaxid = array();
    while (!empty($file) && !feof($fp) || !empty($xml) && $count < $maxcount) {
        if (!empty($file)) {
            $line = fgets($fp, 4096);
        } else {
            $line = $lines[$count];
        }
        $count++;
        if (empty($what)) {
            if (preg_match('#<object name="(\\w+)">#', $line, $matches)) {
                // in case we import the object definition
                $object = array();
                $object['name'] = $matches[1];
                $what = 'object';
            } elseif (preg_match('#<items>#', $line)) {
                // in case we only import data
                $what = 'item';
            }
        } elseif ($what == 'object') {
            if (preg_match('#<([^>]+)>(.*)</\\1>#', $line, $matches)) {
                $key = $matches[1];
                $value = $matches[2];
                if (isset($object[$key])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Duplicate definition for #(1) key #(2) on line #(3)', 'object', xarVarPrepForDisplay($key), $count);
                    throw new DuplicateException(null, $msg);
                }
                $object[$key] = $value;
            } elseif (preg_match('#<config>#', $line)) {
                if (isset($object['config'])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Duplicate definition for #(1) key #(2) on line #(3)', 'object', 'config', $count);
                    throw new DuplicateException(null, $msg);
                }
                $config = array();
                $what = 'config';
            } elseif (preg_match('#<properties>#', $line)) {
                if (empty($object['name']) || empty($object['moduleid'])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Missing keys in object definition');
                    throw new BadParameterException(null, $msg);
                }
                // make sure we drop the object id, because it might already exist here
                unset($object['objectid']);
                $properties = array();
                $what = 'property';
            } elseif (preg_match('#<items>#', $line)) {
                $what = 'item';
            } elseif (preg_match('#</object>#', $line)) {
                $what = '';
            } else {
                // multi-line entries not relevant here
            }
        } elseif ($what == 'config') {
            if (preg_match('#<([^>]+)>(.*)</\\1>#', $line, $matches)) {
                $key = $matches[1];
                $value = $matches[2];
                if (isset($config[$key])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Duplicate definition for #(1) key #(2) on line #(3)', 'config', xarVarPrepForDisplay($key), $count);
                    throw new DuplicateException(null, $msg);
                }
                $config[$key] = $value;
            } elseif (preg_match('#</config>#', $line)) {
                // override default view if necessary
                $config['defaultview'] = 1;
                $object['config'] = serialize($config);
                $config = array();
                $what = 'object';
            } else {
                // multi-line entries not relevant here
            }
        } elseif ($what == 'property') {
            if (preg_match('#<property name="(\\w+)">#', $line, $matches)) {
                $property = array();
                $property['name'] = $matches[1];
            } elseif (preg_match('#</property>#', $line)) {
                if (empty($property['name']) || empty($property['type'])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Missing keys in property definition');
                    throw new BadParameterException(null, $msg);
                }
                // make sure we drop the property id, because it might already exist here
                unset($property['id']);
                // TODO: watch out for multi-sites
                // replace default xar_* table prefix with local one
                $property['source'] = preg_replace("/^xar_/", $prefix, $property['source']);
                // add this property to the list
                $properties[] = $property;
            } elseif (preg_match('#<([^>]+)>(.*)</\\1>#', $line, $matches)) {
                $key = $matches[1];
                $value = $matches[2];
                if (isset($property[$key])) {
                    if (!empty($file)) {
                        fclose($fp);
                    }
                    $msg = xarML('Duplicate definition for #(1) key #(2) on line #(3)', 'property', xarVarPrepForDisplay($key), $count);
                    throw new DuplicateException(null, $msg);
                }
                $property[$key] = $value;
            } elseif (preg_match('#</properties>#', $line)) {
                // 1. make sure we have a unique pubtype name
                foreach ($pubtypes as $pubid => $pubtype) {
                    if ($object['name'] == $pubtype['name']) {
                        $object['name'] .= '_' . time();
                        break;
                    }
                }
                // 2. fill in the pubtype field config
                $fields = array();
                $extra = array();
                foreach ($properties as $property) {
                    $field = $property['name'];
                    switch ($field) {
                        case 'id':
                        case 'pubtype_id':
                            // skip these
                            break;
                        case 'title':
                        case 'summary':
                        case 'body':
                        case 'notes':
                        case 'owner':
                        case 'pubdate':
                        case 'state':
                            // convert property type to string if necessary
                            if (is_numeric($property['type'])) {
                                if (isset($proptypes[$property['type']])) {
                                    $property['type'] = $proptypes[$property['type']]['name'];
                                } else {
                                    $property['type'] = 'static';
                                }
                            }
                            // reset disabled field labels to empty
                            if (empty($property['state'])) {
                                $property['label'] = '';
                            }
                            if (!isset($property['validation'])) {
                                $property['validation'] = '';
                            }
                            $fields[$field] = array('label' => $property['label'], 'format' => $property['type'], 'input' => $property['input'], 'validation' => $property['validation']);
                            break;
                        default:
                            // convert property type to numeric if necessary
                            if (!is_numeric($property['type'])) {
                                if (isset($name2id[$property['type']])) {
                                    $property['type'] = $name2id[$property['type']];
                                } else {
                                    $property['type'] = 1;
                                }
                            }
                            $extra[] = $property;
                            break;
                    }
                }
                // 3. create the pubtype
                $ptid = xarModAPIFunc('publications', 'admin', 'createpubtype', array('name' => $object['name'], 'descr' => $object['label'], 'config' => $fields));
                if (empty($ptid)) {
                    return;
                }
                // 4. set the module variables
                xarModVars::set('publications', 'settings.' . $ptid, $object['config']);
                xarModVars::set('publications', 'number_of_categories.' . $ptid, 0);
                xarModVars::set('publications', 'mastercids.' . $ptid, '');
                // 5. create a dynamic object if necessary
                if (count($extra) > 0) {
                    $object['itemtype'] = $ptid;
                    $object['config'] = '';
                    $object['isalias'] = 0;
                    $objectid = xarModAPIFunc('dynamicdata', 'admin', 'createobject', $object);
                    if (!isset($objectid)) {
                        if (!empty($file)) {
                            fclose($fp);
                        }
                        return;
                    }
                    // 6. create the dynamic properties
                    foreach ($extra as $property) {
                        $property['objectid'] = $objectid;
                        $property['moduleid'] = $object['moduleid'];
                        $property['itemtype'] = $object['itemtype'];
                        $prop_id = xarModAPIFunc('dynamicdata', 'admin', 'createproperty', $property);
                        if (!isset($prop_id)) {
                            if (!empty($file)) {
                                fclose($fp);
                            }
                            return;
                        }
                    }
                    // 7. check if we need to enable DD hooks for this pubtype
                    if (!xarModIsHooked('dynamicdata', 'publications')) {
                        xarModAPIFunc('modules', 'admin', 'enablehooks', array('callerModName' => 'publications', 'callerItemType' => $ptid, 'hookModName' => 'dynamicdata'));
                    }
                }
                $properties = array();
                $what = 'object';
            } elseif (preg_match('#<items>#', $line)) {
                $what = 'item';
            } elseif (preg_match('#</object>#', $line)) {
                $what = '';
            } else {
                // multi-line entries not relevant here
            }
        } elseif ($what == 'item') {
            /* skip this for publications
                        if (preg_match('#<([^> ]+) itemid="(\d+)">#',$line,$matches)) {
                            // find out what kind of item we're dealing with
                            $objectname = $matches[1];
                            $itemid = $matches[2];
                            if (empty($objectname2objectid[$objectname])) {
                                $objectinfo = DataObjectMaster::getObjectInfo(array('name' => $objectname));
                                if (isset($objectinfo) && !empty($objectinfo['objectid'])) {
                                    $objectname2objectid[$objectname] = $objectinfo['objectid'];
                                } else {
                                    if (!empty($file)) fclose($fp);
                                    $msg = xarML('Unknown #(1) "#(2)" on line #(3)','object',xarVarPrepForDisplay($objectname),$count);
                                    throw new BadParameterException(null, $msg);
                                }
                            }
                            $objectid = $objectname2objectid[$objectname];
                            $item = array();
                            // don't save the item id for now...
                        // TODO: keep the item id if we set some flag
                            //$item['itemid'] = $itemid;
                            $closeitem = $objectname;
                            $closetag = 'N/A';
                        } elseif (preg_match("#</$closeitem>#",$line)) {
                            // let's create the item now...
                            if (!isset($objectcache[$objectid])) {
                                $objectcache[$objectid] = new DataObject(array('objectid' => $objectid));
                            }
                            // set the item id to 0
                        // TODO: keep the item id if we set some flag
                            $item['itemid'] = 0;
                            // create the item
                            $itemid = $objectcache[$objectid]->createItem($item);
                            if (empty($itemid)) {
                                if (!empty($file)) fclose($fp);
                                return;
                            }
                            // keep track of the highest item id
                            if (empty($objectmaxid[$objectid]) || $objectmaxid[$objectid] < $itemid) {
                                $objectmaxid[$objectid] = $itemid;
                            }
                            $closeitem = 'N/A';
                            $closetag = 'N/A';
                        } elseif (preg_match('#<([^>]+)>(.*)</\1>#',$line,$matches)) {
                            $key = $matches[1];
                            $value = $matches[2];
                            if (isset($item[$key])) {
                                if (!empty($file)) fclose($fp);
                                $msg = xarML('Duplicate definition for #(1) key #(2) on line #(3)','item',xarVarPrepForDisplay($key),$count);
                                throw new DuplicateException(null, $msg);
                            }
                            $item[$key] = $value;
                            $closetag = 'N/A';
                        } elseif (preg_match('#<([^/>]+)>(.*)#',$line,$matches)) {
                            // multi-line entries *are* relevant here
                            $key = $matches[1];
                            $value = $matches[2];
                            if (isset($item[$key])) {
                                if (!empty($file)) fclose($fp);
                                $msg = xarML('Duplicate definition for #(1) key #(2)','item',xarVarPrepForDisplay($key));
                                throw new DuplicateException(null, $msg);
                            }
                            $item[$key] = $value;
                            $closetag = $key;
                        } elseif (preg_match("#(.*)</$closetag>#",$line,$matches)) {
                            // multi-line entries *are* relevant here
                            $value = $matches[1];
                            if (!isset($item[$closetag])) {
                                if (!empty($file)) fclose($fp);
                                $msg = xarML('Undefined #(1) key #(2)','item',xarVarPrepForDisplay($closetag));
                                throw new BadParameterException(null, $msg);
                            }
                            $item[$closetag] .= $value;
                            $closetag = 'N/A';
                        } elseif ($closetag != 'N/A') {
                            // multi-line entries *are* relevant here
                            if (!isset($item[$closetag])) {
                                if (!empty($file)) fclose($fp);
                                $msg = xarML('Undefined #(1) key #(2)','item',xarVarPrepForDisplay($closetag));
                                throw new BadParameterException(null, $msg);
                            }
                            $item[$closetag] .= $line;
                        } elseif (preg_match('#</items>#',$line)) {
            skip this for publications */
            if (preg_match('#</items>#', $line)) {
                $what = 'object';
            } elseif (preg_match('#</object>#', $line)) {
                $what = '';
            } else {
            }
        } else {
        }
    }
    if (!empty($file)) {
        fclose($fp);
    }
    return $ptid;
}
Beispiel #7
0
/**
 * Manage definition of instances for privileges (unfinished)
 *
 * @return array for template
 */
function publications_admin_privileges($args)
{
    extract($args);
    // fixed params
    if (!xarVarFetch('ptid', 'isset', $ptid, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('cid', 'isset', $cid, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('uid', 'isset', $uid, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('author', 'isset', $author, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('id', 'isset', $id, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('apply', 'isset', $apply, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extpid', 'isset', $extpid, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extname', 'isset', $extname, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extrealm', 'isset', $extrealm, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extmodule', 'isset', $extmodule, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extcomponent', 'isset', $extcomponent, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extinstance', 'isset', $extinstance, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('extlevel', 'isset', $extlevel, NULL, XARVAR_DONT_SET)) {
        return;
    }
    sys::import('modules.dynamicdata.class.properties.master');
    $categories = DataPropertyMaster::getProperty(array('name' => 'categories'));
    $cids = $categories->returnInput('privcategories');
    if (!empty($extinstance)) {
        $parts = explode(':', $extinstance);
        if (count($parts) > 0 && !empty($parts[0])) {
            $ptid = $parts[0];
        }
        if (count($parts) > 1 && !empty($parts[1])) {
            $cid = $parts[1];
        }
        if (count($parts) > 2 && !empty($parts[2])) {
            $uid = $parts[2];
        }
        if (count($parts) > 3 && !empty($parts[3])) {
            $id = $parts[3];
        }
    }
    if (empty($ptid) || $ptid == 'All' || !is_numeric($ptid)) {
        $ptid = 0;
        if (!xarSecurityCheck('AdminPublications')) {
            return;
        }
    } else {
        if (!xarSecurityCheck('AdminPublications', 1, 'Publication', "{$ptid}:All:All:All")) {
            return;
        }
    }
    // TODO: do something with cid for security check
    // TODO: figure out how to handle more than 1 category in instances
    if (empty($cid) || $cid == 'All' || !is_numeric($cid)) {
        $cid = 0;
    }
    if (empty($cid) && isset($cids) && is_array($cids)) {
        foreach ($cids as $catid) {
            if (!empty($catid)) {
                $cid = $catid;
                // bail out for now
                break;
            }
        }
    }
    if (empty($id) || $id == 'All' || !is_numeric($id)) {
        $id = 0;
    }
    $title = '';
    if (!empty($id)) {
        $article = xarModAPIFunc('publications', 'user', 'get', array('id' => $id, 'withcids' => true));
        if (empty($article)) {
            $id = 0;
        } else {
            // override whatever other params we might have here
            $ptid = $article['pubtype_id'];
            // TODO: review when we can handle multiple categories and/or subtrees in privilege instances
            if (!empty($article['cids']) && count($article['cids']) == 1) {
                // if we don't have a category, or if we have one but this article doesn't belong to it
                if (empty($cid) || !in_array($cid, $article['cids'])) {
                    // we'll take that category
                    $cid = $article['cids'][0];
                }
            } else {
                // we'll take no categories
                $cid = 0;
            }
            $uid = $article['owner'];
            $title = $article['title'];
        }
    }
    // TODO: figure out how to handle groups of users and/or the current user (later)
    if (strtolower($uid) == 'myself') {
        $uid = 'Myself';
        $author = 'Myself';
    } elseif (empty($uid) || $uid == 'All' || !is_numeric($uid) && strtolower($uid) != 'myself') {
        $uid = 0;
        if (!empty($author)) {
            $user = xarModAPIFunc('roles', 'user', 'get', array('name' => $author));
            if (!empty($user) && !empty($user['uid'])) {
                if (strtolower($author) == 'myself') {
                    $uid = 'Myself';
                } else {
                    $uid = $user['uid'];
                }
            } else {
                $author = '';
            }
        }
    } else {
        $author = '';
        /*
                $user = xarModAPIFunc('roles', 'user', 'get',
                                      array('uid' => $uid));
                if (!empty($user) && !empty($user['name'])) {
                    $author = $user['name'];
                }
        */
    }
    // define the new instance
    $newinstance = array();
    $newinstance[] = empty($ptid) ? 'All' : $ptid;
    $newinstance[] = empty($cid) ? 'All' : $cid;
    $newinstance[] = empty($uid) ? 'All' : $uid;
    $newinstance[] = empty($id) ? 'All' : $id;
    if (!empty($apply)) {
        // create/update the privilege
        $id = xarReturnPrivilege($extpid, $extname, $extrealm, $extmodule, $extcomponent, $newinstance, $extlevel);
        if (empty($id)) {
            return;
        }
        // throw back
        // redirect to the privilege
        xarController::redirect(xarModURL('privileges', 'admin', 'modifyprivilege', array('id' => $id)));
        return true;
    }
    // get the list of current authors
    $authorlist = xarModAPIFunc('publications', 'user', 'getauthors', array('ptid' => $ptid, 'cids' => empty($cid) ? array() : array($cid)));
    if (!empty($author) && isset($authorlist[$uid])) {
        $author = '';
    }
    if (empty($id)) {
        $numitems = xarModAPIFunc('publications', 'user', 'countitems', array('ptid' => $ptid, 'cids' => empty($cid) ? array() : array($cid), 'owner' => $uid));
    } else {
        $numitems = 1;
    }
    $data = array('ptid' => $ptid, 'cid' => $cid, 'uid' => $uid, 'author' => xarVarPrepForDisplay($author), 'authorlist' => $authorlist, 'id' => $id, 'title' => xarVarPrepForDisplay($title), 'numitems' => $numitems, 'extpid' => $extpid, 'extname' => $extname, 'extrealm' => $extrealm, 'extmodule' => $extmodule, 'extcomponent' => $extcomponent, 'extlevel' => $extlevel, 'extinstance' => xarVarPrepForDisplay(join(':', $newinstance)));
    // Get publication types
    $data['pubtypes'] = xarModAPIFunc('publications', 'user', 'get_pubtypes');
    $catlist = array();
    if (!empty($ptid)) {
        $basecats = xarModAPIFunc('categories', 'user', 'getallcatbases', array('module' => 'publications', 'itemtype' => $ptid));
        foreach ($basecats as $catid) {
            $catlist[$catid['id']] = 1;
        }
        if (empty($data['pubtypes'][$ptid]['config']['owner']['label'])) {
            $data['showauthor'] = 0;
        } else {
            $data['showauthor'] = 1;
        }
    } else {
        foreach (array_keys($data['pubtypes']) as $pubid) {
            $basecats = xarModAPIFunc('categories', 'user', 'getallcatbases', array('module' => 'publications', 'itemtype' => $pubid));
            foreach ($basecats as $catid) {
                $catlist[$catid['id']] = 1;
            }
        }
        $data['showauthor'] = 1;
    }
    $seencid = array();
    if (!empty($cid)) {
        $seencid[$cid] = 1;
    }
    $data['cids'] = $cids;
    $data['cats'] = $catlist;
    $data['refreshlabel'] = xarML('Refresh');
    $data['applylabel'] = xarML('Finish and Apply to Privilege');
    return $data;
}
Beispiel #8
0
function publications_admin_display($args)
{
    // Get parameters from user
    // this is used to determine whether we come from a pubtype-based view or a
    // categories-based navigation
    // Note we support both id and itemid
    if (!xarVarFetch('name', 'str', $name, '', XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('ptid', 'id', $ptid, NULL, XARVAR_DONT_SET)) {
        return;
    }
    if (!xarVarFetch('itemid', 'id', $itemid, NULL, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('id', 'id', $id, NULL, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('page', 'int:1', $page, NULL, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('translate', 'int:1', $translate, 1, XARVAR_NOT_REQUIRED)) {
        return;
    }
    if (!xarVarFetch('layout', 'str:1', $layout, 'detail', XARVAR_NOT_REQUIRED)) {
        return;
    }
    // Override xarVarFetch
    extract($args);
    //The itemid var takes precedence if it exiata
    if (isset($itemid)) {
        $id = $itemid;
    }
    # --------------------------------------------------------
    #
    # If no ID supplied, try getting the id of the default page.
    #
    if (empty($id)) {
        $id = xarModVars::get('publications', 'defaultpage');
    }
    # --------------------------------------------------------
    #
    # Get the ID of the translation if required
    #
    // First save the "untranslated" id
    xarVarSetCached('Blocks.publications', 'current_base_id', $id);
    if ($translate) {
        $id = xarMod::apiFunc('publications', 'user', 'gettranslationid', array('id' => $id));
    }
    # --------------------------------------------------------
    #
    # If still no ID, check if we are trying to display a pubtype
    #
    if (empty($name) && empty($ptid) && empty($id)) {
        // Nothing to be done
        $id = xarModVars::get('publications', 'notfoundpage');
    } elseif (empty($id)) {
        // We're missing an id but can get a pubtype: jump to the pubtype view
        xarController::redirect(xarModURL('publications', 'user', 'view'));
    }
    # --------------------------------------------------------
    #
    # If still no ID, we have come to the end of the line
    #
    if (empty($id)) {
        return xarResponse::NotFound();
    }
    # --------------------------------------------------------
    #
    # We have an ID, now first get the page
    #
    // Here we get the publication type first, and then from that the page
    // Perhaps more efficient to get the page directly?
    $ptid = xarMod::apiFunc('publications', 'user', 'getitempubtype', array('itemid' => $id));
    // An empty publication type means the page does not exist
    if (empty($ptid)) {
        return xarResponse::NotFound();
    }
    /*    if (empty($name) && empty($ptid)) return xarResponse::NotFound();
    
        if(empty($ptid)) {
            $publication_type = DataObjectMaster::getObjectList(array('name' => 'publications_types'));
            $where = 'name = ' . $name;
            $items = $publication_type->getItems(array('where' => $where));
            $item = current($items);
            $ptid = $item['id'];
        }
    */
    $pubtypeobject = DataObjectMaster::getObject(array('name' => 'publications_types'));
    $pubtypeobject->getItem(array('itemid' => $ptid));
    $data['object'] = DataObjectMaster::getObject(array('name' => $pubtypeobject->properties['name']->value));
    //    $id = xarMod::apiFunc('publications','user','gettranslationid',array('id' => $id));
    $itemid = $data['object']->getItem(array('itemid' => $id));
    # --------------------------------------------------------
    #
    # Are we allowed to see this page?
    #
    $accessconstraints = unserialize($data['object']->properties['access']->value);
    $access = DataPropertyMaster::getProperty(array('name' => 'access'));
    $allow = $access->check($accessconstraints['display']);
    $nopublish = time() < $data['object']->properties['start_date']->value || time() > $data['object']->properties['end_date']->value && !$data['object']->properties['no_end']->value;
    // If no access, then bail showing a forbidden or an empty page
    if (!$allow || $nopublish) {
        if ($accessconstraints['display']['failure']) {
            return xarResponse::Forbidden();
        } else {
            return xarTplModule('publications', 'user', 'empty');
        }
    }
    # --------------------------------------------------------
    #
    # If this is a redirect page, then send it on its way now
    #
    $redirect_type = $data['object']->properties['redirect_flag']->value;
    if ($redirect_type == 1) {
        // This is a simple redirect to another page
        try {
            $url = $data['object']->properties['redirect_url']->value;
            // Check if this is a Xaraya function
            $pos = strpos($url, 'xar');
            if ($pos === 0) {
                eval('$url = ' . $url . ';');
            }
            xarController::redirect($url, 301);
        } catch (Exception $e) {
            return xarResponse::NotFound();
        }
    } elseif ($redirect_type == 2) {
        // This displays a page of a different module
        // If this is from a link of a redirect child page, use the child param as new URL
        if (!xarVarFetch('child', 'str', $child, NULL, XARVAR_NOT_REQUIRED)) {
            return;
        }
        if (!empty($child)) {
            // Turn entities into amps
            $url = urldecode($child);
        } else {
            $url = $data['object']->properties['proxy_url']->value;
        }
        // Bail if the URL is bad
        try {
            // Check if this is a Xaraya function
            $pos = strpos($url, 'xar');
            if ($pos === 0) {
                eval('$url = ' . $url . ';');
            }
            $params = parse_url($url);
            $params['query'] = preg_replace('/&amp;/', '&', $params['query']);
        } catch (Exception $e) {
            return xarResponse::NotFound();
        }
        // If this is an external link, show it without further processing
        if (!empty($params['host']) && $params['host'] != xarServer::getHost() && $params['host'] . ":" . $params['port'] != xarServer::getHost()) {
            xarController::redirect($url, 301);
        } else {
            parse_str($params['query'], $info);
            $other_params = $info;
            unset($other_params['module']);
            unset($other_params['type']);
            unset($other_params['func']);
            unset($other_params['child']);
            try {
                $page = xarMod::guiFunc($info['module'], 'user', $info['func'], $other_params);
            } catch (Exception $e) {
                return xarResponse::NotFound();
            }
            // Debug
            // echo xarModURL($info['module'],'user',$info['func'],$other_params);
            # --------------------------------------------------------
            #
            # For proxy pages: the transform of the subordinate function's template
            #
            // Find the URLs in submits
            $pattern = '/(action)="([^"\\r\\n]*)"/';
            preg_match_all($pattern, $page, $matches);
            $pattern = array();
            $replace = array();
            foreach ($matches[2] as $match) {
                $pattern[] = '%</form%';
                $replace[] = '<input type="hidden" name="return_url" id="return_url" value="' . urlencode(xarServer::getCurrentURL()) . '"/><input type="hidden" name="child" value="' . urlencode($match) . '"/></form';
            }
            $page = preg_replace($pattern, $replace, $page);
            $pattern = '/(action)="([^"\\r\\n]*)"/';
            $page = preg_replace_callback($pattern, create_function('$matches', 'return $matches[1]."=\\"".xarServer::getCurrentURL()."\\"";'), $page);
            // Find the URLs in links
            $pattern = '/(href)="([^"\\r\\n]*)"/';
            $page = preg_replace_callback($pattern, create_function('$matches', 'return $matches[1]."=\\"".xarServer::getCurrentURL(array("child" => urlencode($matches[2])))."\\"";'), $page);
            return $page;
        }
    }
    # --------------------------------------------------------
    #
    # If this is a bloccklayout page, then process it
    #
    if ($data['object']->properties['pagetype']->value == 2) {
        // Get a copy of the compiler
        sys::import('xaraya.templating.compiler');
        $blCompiler = XarayaCompiler::instance();
        // Get the data fields
        $fields = array();
        $sourcefields = array('title', 'description', 'summary', 'body1', 'body2', 'body3', 'body4', 'body5', 'notes');
        $prefix = strlen('publications.') - 1;
        foreach ($data['object']->properties as $prop) {
            if (in_array(substr($prop->source, $prefix), $sourcefields)) {
                $fields[] = $prop->name;
            }
        }
        // Run each template field through the compiler
        foreach ($fields as $field) {
            try {
                $tplString = '<xar:template xmlns:xar="http://xaraya.com/2004/blocklayout">';
                $tplString .= xarMod::apiFunc('publications', 'user', 'prepareforbl', array('string' => $data['object']->properties[$field]->value));
                $tplString .= '</xar:template>';
                $tplString = $blCompiler->compilestring($tplString);
                // We don't allow passing $data to the template for now
                $tpldata = array();
                $tplString = xarTplString($tplString, $tpldata);
            } catch (Exception $e) {
                var_dump($tplString);
            }
            $data['object']->properties[$field]->value = $tplString;
        }
    }
    # --------------------------------------------------------
    #
    # Get the complete tree for this section of pages. We need this for blocks etc.
    #
    $tree = xarMod::apiFunc('publications', 'user', 'getpagestree', array('tree_contains_pid' => $id, 'key' => 'id', 'status' => 'ACTIVE,FRONTPAGE,PLACEHOLDER'));
    // If this page is of type PLACEHOLDER, then look in its descendents
    if ($data['object']->properties['state']->value == 5) {
        // Scan for a descendent that is ACTIVE or FRONTPAGE
        if (!empty($tree['pages'][$id]['child_keys'])) {
            foreach ($tree['pages'][$id]['child_keys'] as $scan_key) {
                // If the page is displayable, then treat it as the new page.
                if ($tree['pages'][$scan_key]['status'] == 3 || $tree['pages'][$scan_key]['status'] == 4) {
                    $id = $tree['pages'][$scan_key]['id'];
                    $id = xarMod::apiFunc('publications', 'user', 'gettranslationid', array('id' => $id));
                    $itemid = $data['object']->getItem(array('itemid' => $id));
                    break;
                }
            }
        }
    }
    # --------------------------------------------------------
    #
    # Additional data
    #
    // Pass the layout to the template
    $data['layout'] = $layout;
    // Get the settings for this publication type;
    $data['settings'] = xarModAPIFunc('publications', 'user', 'getsettings', array('ptid' => $ptid));
    // The name of this object
    $data['objectname'] = $data['object']->name;
    # --------------------------------------------------------
    #
    # Set the theme if needed
    #
    if (!empty($data['object']->properties['theme']->value)) {
        xarTplSetThemeName($data['object']->properties['theme']->value);
    }
    # --------------------------------------------------------
    #
    # Set the page template from the pubtype if needed
    #
    if (!empty($data['settings']['page_template'])) {
        $pagename = $data['settings']['page_template'];
        $position = strpos($pagename, '.');
        if ($position === false) {
            $pagetemplate = $pagename;
        } else {
            $pagetemplate = substr($pagename, 0, $position);
        }
        xarTpl::setPageTemplateName($pagetemplate);
    }
    // It can be overridden by the page itself
    if (!empty($data['object']->properties['page_template']->value)) {
        $pagename = $data['object']->properties['page_template']->value;
        $position = strpos($pagename, '.');
        if ($position === false) {
            $pagetemplate = $pagename;
        } else {
            $pagetemplate = substr($pagename, 0, $position);
        }
        xarTpl::setPageTemplateName($pagetemplate);
    }
    # --------------------------------------------------------
    #
    # Cache data for blocks
    #
    // Now we can cache all this data away for the blocks.
    // The blocks should have access to most of the same data as the page.
    xarVarSetCached('Blocks.publications', 'pagedata', $tree);
    // The 'serialize' hack ensures we have a proper copy of the
    // paga data, which is a self-referencing array. If we don't
    // do this, then any changes we make will affect the stored version.
    $data = unserialize(serialize($data));
    // Save some values. These are used by blocks in 'automatic' mode.
    xarVarSetCached('Blocks.publications', 'current_id', $id);
    xarVarSetCached('Blocks.publications', 'ptid', $ptid);
    xarVarSetCached('Blocks.publications', 'author', $data['object']->properties['author']->value);
    # --------------------------------------------------------
    #
    # Make the properties available to the template
    #
    $data['properties'] =& $data['object']->properties;
    return $data;
    /*
        // TEST - highlight search terms
        if(!xarVarFetch('q',     'str',  $q,     NULL, XARVAR_NOT_REQUIRED)) {return;}
    */
    // Override if needed from argument array (e.g. preview)
    extract($args);
    // Defaults
    if (!isset($page)) {
        $page = 1;
    }
    // via arguments only
    if (!isset($preview)) {
        $preview = 0;
    }
    /*
        if ($preview) {
            if (!isset($publication)) {
                return xarML('Invalid publication');
            }
            $id = $publication->properties['id']->value;
        } elseif (!isset($id) || !is_numeric($id) || $id < 1) {
            return xarML('Invalid publication ID');
        }
    */
    /*    // Get publication
        if (!$preview) {
            $publication = xarModAPIFunc('publications',
                                    'user',
                                    'get',
                                    array('id' => $id,
                                          'withcids' => true));
        }
    
        if (!is_array($publication)) {
            $msg = xarML('Failed to retrieve publication in #(3)_#(1)_#(2).php', 'userapi', 'get', 'publications');
            throw new DataNotFoundException(null, $msg);
        }
        // Get publication types
        $pubtypes = xarModAPIFunc('publications','user','get_pubtypes');
    
        // Check that the publication type is valid, otherwise use the publication's pubtype
        if (!empty($ptid) && !isset($pubtypes[$ptid])) {
            $ptid = $publication['pubtype_id'];
        }
    
    */
    // keep original ptid (if any)
    //    $ptid = $publication['pubtype_id'];
    //    $pubtype_id = $publication->properties['itemtype']->value;
    //    $owner = $publication->properties['author']->value;
    /*    if (!isset($publication['cids'])) {
            $publication['cids'] = array();
        }
        $cids = $publication['cids'];
    */
    // Get the publication settings for this publication type
    if (empty($ptid)) {
        $settings = unserialize(xarModVars::get('publications', 'settings'));
    } else {
        $settings = unserialize(xarModVars::get('publications', 'settings.' . $ptid));
    }
    // show the number of publications for each publication type
    if (!isset($show_pubcount)) {
        if (!isset($settings['show_pubcount']) || !empty($settings['show_pubcount'])) {
            $show_pubcount = 1;
            // default yes
        } else {
            $show_pubcount = 0;
        }
    }
    // show the number of publications for each category
    if (!isset($show_catcount)) {
        if (empty($settings['show_catcount'])) {
            $show_catcount = 0;
            // default no
        } else {
            $show_catcount = 1;
        }
    }
    // Initialize the data array
    $data = $publication->getFieldValues();
    $data['ptid'] = $ptid;
    // navigation pubtype
    $data['pubtype_id'] = $pubtype_id;
    // publication pubtype
    // TODO: improve the case where we have several icons :)
    $data['topic_icons'] = '';
    $data['topic_images'] = array();
    $data['topic_urls'] = array();
    $data['topic_names'] = array();
    /*
        if (count($cids) > 0) {
            if (!xarModAPILoad('categories', 'user')) return;
            $catlist = xarModAPIFunc('categories',
                                    'user',
                                    'getcatinfo',
                                    array('cids' => $cids));
            foreach ($catlist as $cat) {
                $link = xarModURL('publications','user','view',
                                 array(//'state' => array(PUBLICATIONS_STATE_FRONTPAGE,PUBLICATIONS_STATE_APPROVED).
                                       'ptid' => $ptid,
                                       'catid' => $cat['cid']));
                $name = xarVarPrepForDisplay($cat['name']);
    
                $data['topic_urls'][] = $link;
                $data['topic_names'][] = $name;
    
                if (!empty($cat['image'])) {
                    $image = xarTplGetImage($cat['image'],'categories');
                    $data['topic_icons'] .= '<a href="'. $link .'">'.
                                            '<img src="'. $image .
                                            '" alt="'. $name .'" />'.
                                            '</a>';
                    $data['topic_images'][] = $image;
    
                    break;
                }
            }
        }
    */
    // multi-page output for 'body' field (mostly for sections at the moment)
    $themeName = xarVarGetCached('Themes.name', 'CurrentTheme');
    if ($themeName != 'print') {
        if (strstr($publication->properties['body']->value, '<!--pagebreak-->')) {
            if ($preview) {
                $publication['body'] = preg_replace('/<!--pagebreak-->/', '<hr/><div style="text-align: center;">' . xarML('Page Break') . '</div><hr/>', $publication->properties['body']->value);
                $data['previous'] = '';
                $data['next'] = '';
            } else {
                $pages = explode('<!--pagebreak-->', $publication->properties['body']->value);
                // For documents with many pages, the pages can be
                // arranged in blocks.
                $pageBlockSize = 10;
                // Get pager information: one item per page.
                $pagerinfo = xarTplPagerInfo(empty($page) ? 1 : $page, count($pages), 1, $pageBlockSize);
                // Retrieve current page and total pages from the pager info.
                // These will have been normalised to ensure they are in range.
                $page = $pagerinfo['currentpage'];
                $numpages = $pagerinfo['totalpages'];
                // Discard everything but the current page.
                $publication['body'] = $pages[$page - 1];
                unset($pages);
                if ($page > 1) {
                    // Don't count page hits after the first page.
                    xarVarSetCached('Hooks.hitcount', 'nocount', 1);
                }
                // Pass in the pager info so a complete custom pager
                // can be created in the template if required.
                $data['pagerinfo'] = $pagerinfo;
                // Get the rendered pager.
                // The pager template (last parameter) could be an
                // option for the publication type.
                $urlmask = xarModURL('publications', 'user', 'display', array('ptid' => $ptid, 'id' => $id, 'page' => '%%'));
                $data['pager'] = xarTplGetPager($page, $numpages, $urlmask, 1, $pageBlockSize, 'multipage');
                // Next two assignments for legacy templates.
                // TODO: deprecate them?
                $data['next'] = xarTplGetPager($page, $numpages, $urlmask, 1, $pageBlockSize, 'multipagenext');
                $data['previous'] = xarTplGetPager($page, $numpages, $urlmask, 1, $pageBlockSize, 'multipageprev');
            }
        } else {
            $data['previous'] = '';
            $data['next'] = '';
        }
    } else {
        $publication['body'] = preg_replace('/<!--pagebreak-->/', '', $publication['body']);
    }
    // TEST
    if (isset($prevnextart)) {
        $settings['prevnextart'] = $prevnextart;
    }
    if (!empty($settings['prevnextart']) && $preview == 0) {
        if (!array_key_exists('defaultsort', $settings)) {
            $settings['defaultsort'] = 'id';
        }
        $prevart = xarModAPIFunc('publications', 'user', 'getprevious', array('id' => $id, 'ptid' => $ptid, 'sort' => $settings['defaultsort'], 'state' => array(PUBLICATIONS_STATE_FRONTPAGE, PUBLICATIONS_STATE_APPROVED), 'enddate' => time()));
        if (!empty($prevart['id'])) {
            //Make all previous publication info available to template
            $data['prevartinfo'] = $prevart;
            $data['prevart'] = xarModURL('publications', 'user', 'display', array('ptid' => $prevart['pubtype_id'], 'id' => $prevart['id']));
        } else {
            $data['prevart'] = '';
        }
        $nextart = xarModAPIFunc('publications', 'user', 'getnext', array('id' => $id, 'ptid' => $ptid, 'sort' => $settings['defaultsort'], 'state' => array(PUBLICATIONS_STATE_FRONTPAGE, PUBLICATIONS_STATE_APPROVED), 'enddate' => time()));
        if (!empty($nextart['id'])) {
            //Make all next art info available to template
            $data['nextartinfo'] = $nextart;
            $data['nextart'] = xarModURL('publications', 'user', 'display', array('ptid' => $nextart['pubtype_id'], 'id' => $nextart['id']));
        } else {
            $data['nextart'] = '';
        }
    } else {
        $data['prevart'] = '';
        $data['nextart'] = '';
    }
    // Display publication
    unset($publication);
    // temp. fix to include dynamic data fields without changing templates
    if (xarModIsHooked('dynamicdata', 'publications', $pubtype_id)) {
        list($properties) = xarModAPIFunc('dynamicdata', 'user', 'getitemfordisplay', array('module' => 'publications', 'itemtype' => $pubtype_id, 'itemid' => $id, 'preview' => $preview));
        if (!empty($properties) && count($properties) > 0) {
            foreach (array_keys($properties) as $field) {
                $data[$field] = $properties[$field]->getValue();
                // POOR mans flagging for transform hooks
                try {
                    $configuration = $properties[$field]->configuration;
                    if (substr($configuration, 0, 10) == 'transform:') {
                        $data['transform'][] = $field;
                    }
                } catch (Exception $e) {
                }
                // TODO: clean up this temporary fix
                $data[$field . '_output'] = $properties[$field]->showOutput();
            }
        }
    }
    // Let any transformation hooks know that we want to transform some text.
    // You'll need to specify the item id, and an array containing all the
    // pieces of text that you want to transform (e.g. for autolinks, wiki,
    // smilies, bbcode, ...).
    $data['itemtype'] = $pubtype_id;
    // TODO: what about transforming DDfields ?
    // <mrb> see above for a hack, needs to be a lot better.
    // Summary is always included, is that handled somewhere else? (publication config says i can ex/include it)
    // <mikespub> publications config allows you to call transforms for the publications summaries in the view function
    if (!isset($title_transform)) {
        if (empty($settings['title_transform'])) {
            $data['transform'][] = 'summary';
            $data['transform'][] = 'body';
            $data['transform'][] = 'notes';
        } else {
            $data['transform'][] = 'title';
            $data['transform'][] = 'summary';
            $data['transform'][] = 'body';
            $data['transform'][] = 'notes';
        }
    }
    $data = xarModCallHooks('item', 'transform', $id, $data, 'publications');
    return xarTplModule('publications', 'user', 'display', $data);
    if (!empty($data['title'])) {
        // CHECKME: <rabbit> Strip tags out of the title - the <title> tag shouldn't have any other tags in it.
        $title = strip_tags($data['title']);
        xarTplSetPageTitle(xarVarPrepForDisplay($title), xarVarPrepForDisplay($pubtypes[$data['itemtype']]['description']));
        // Save some variables to (temporary) cache for use in blocks etc.
        xarVarSetCached('Comments.title', 'title', $data['title']);
    }
    /*
        if (!empty($q)) {
        // TODO: split $q into search terms + add style (cfr. handlesearch in search module)
            foreach ($data['transform'] as $field) {
                $data[$field] = preg_replace("/$q/","<span class=\"xar-search-match\">$q</span>",$data[$field]);
            }
        }
    */
    // Navigation links
    $data['publabel'] = xarML('Publication');
    $data['publinks'] = array();
    //xarModAPIFunc('publications','user','getpublinks',
    //    array('state' => array(PUBLICATIONS_STATE_FRONTPAGE,PUBLICATIONS_STATE_APPROVED),
    //          'count' => $show_pubcount));
    if (isset($show_map)) {
        $settings['show_map'] = $show_map;
    }
    if (!empty($settings['show_map'])) {
        $data['maplabel'] = xarML('View Publication Map');
        $data['maplink'] = xarModURL('publications', 'user', 'viewmap', array('ptid' => $ptid));
    }
    if (isset($show_archives)) {
        $settings['show_archives'] = $show_archives;
    }
    if (!empty($settings['show_archives'])) {
        $data['archivelabel'] = xarML('View Archives');
        $data['archivelink'] = xarModURL('publications', 'user', 'archive', array('ptid' => $ptid));
    }
    if (isset($show_publinks)) {
        $settings['show_publinks'] = $show_publinks;
    }
    if (!empty($settings['show_publinks'])) {
        $data['show_publinks'] = 1;
    } else {
        $data['show_publinks'] = 0;
    }
    $data['show_catcount'] = $show_catcount;
    // Tell the hitcount hook not to display the hitcount, but to save it
    // in the variable cache.
    if (xarModIsHooked('hitcount', 'publications', $pubtype_id)) {
        xarVarSetCached('Hooks.hitcount', 'save', 1);
        $data['dohitcount'] = 1;
    } else {
        $data['dohitcount'] = 0;
    }
    // Tell the ratings hook to save the rating in the variable cache.
    if (xarModIsHooked('ratings', 'publications', $pubtype_id)) {
        xarVarSetCached('Hooks.ratings', 'save', 1);
        $data['doratings'] = 1;
    } else {
        $data['doratings'] = 0;
    }
    // Retrieve the current hitcount from the variable cache
    if ($data['dohitcount'] && xarVarIsCached('Hooks.hitcount', 'value')) {
        $data['counter'] = xarVarGetCached('Hooks.hitcount', 'value');
    } else {
        $data['counter'] = '';
    }
    // Retrieve the current rating from the variable cache
    if ($data['doratings'] && xarVarIsCached('Hooks.ratings', 'value')) {
        $data['rating'] = intval(xarVarGetCached('Hooks.ratings', 'value'));
    } else {
        $data['rating'] = '';
    }
    // Save some variables to (temporary) cache for use in blocks etc.
    xarVarSetCached('Blocks.publications', 'title', $data['title']);
    // Generating keywords from the API now instead of setting the entire
    // body into the cache.
    $keywords = xarModAPIFunc('publications', 'user', 'generatekeywords', array('incomingkey' => $data['body']));
    xarVarSetCached('Blocks.publications', 'body', $keywords);
    xarVarSetCached('Blocks.publications', 'summary', $data['summary']);
    xarVarSetCached('Blocks.publications', 'id', $id);
    xarVarSetCached('Blocks.publications', 'ptid', $ptid);
    xarVarSetCached('Blocks.publications', 'cids', $cids);
    xarVarSetCached('Blocks.publications', 'owner', $owner);
    if (isset($data['author'])) {
        xarVarSetCached('Blocks.publications', 'author', $data['author']);
    }
    // TODO: add this to publications configuration ?
    //if ($shownavigation) {
    $data['id'] = $id;
    $data['cids'] = $cids;
    xarVarSetCached('Blocks.categories', 'module', 'publications');
    xarVarSetCached('Blocks.categories', 'itemtype', $ptid);
    xarVarSetCached('Blocks.categories', 'itemid', $id);
    xarVarSetCached('Blocks.categories', 'cids', $cids);
    if (!empty($ptid) && !empty($pubtypes[$ptid]['description'])) {
        xarVarSetCached('Blocks.categories', 'title', $pubtypes[$ptid]['description']);
    }
    // optional category count
    if ($show_catcount && !empty($ptid)) {
        $pubcatcount = xarModAPIFunc('publications', 'user', 'getpubcatcount', array('state' => array(PUBLICATIONS_STATE_FRONTPAGE, PUBLICATIONS_STATE_APPROVED), 'ptid' => $ptid));
        if (!empty($pubcatcount[$ptid])) {
            xarVarSetCached('Blocks.categories', 'catcount', $pubcatcount[$ptid]);
        }
    } else {
        //    xarVarSetCached('Blocks.categories','catcount',array());
    }
    //}
    // Module template depending on publication type
    $template = $pubtypes[$pubtype_id]['name'];
    // Page template depending on publication type (optional)
    // Note : this cannot be overridden in templates
    if (empty($preview) && !empty($settings['page_template'])) {
        xarTplSetPageTemplateName($settings['page_template']);
    }
    // Specific layout within a template (optional)
    if (isset($layout)) {
        $data['layout'] = $layout;
    }
    $pubtypeobject = DataObjectMaster::getObject(array('name' => 'publications_types'));
    $pubtypeobject->getItem(array('itemid' => $ptid));
    $data['object'] = DataObjectMaster::getObject(array('name' => $pubtypeobject->properties['name']->value));
    $id = xarMod::apiFunc('publications', 'user', 'getranslationid', array('id' => $id));
    $data['object']->getItem(array('itemid' => $id));
    return xarTplModule('publications', 'user', 'display', $data, $template);
}