示例#1
0
 public function display(array $data = array())
 {
     $data = $this->getContent();
     // see if we're currently displaying an article
     if (xarVarIsCached('Blocks.publications', 'id')) {
         $curid = xarVarGetCached('Blocks.publications', 'id');
     } else {
         $curid = -1;
     }
     if (!empty($data['dynamictitle'])) {
         if ($data['toptype'] == 'rating') {
             $data['title'] = xarML('Top Rated');
         } elseif ($data['toptype'] == 'hits') {
             $data['title'] = xarML('Top');
         } else {
             $data['title'] = xarML('Latest');
         }
     }
     if (!empty($data['nocatlimit'])) {
         // don't limit by category
         $cid = 0;
         $cidsarray = array();
     } else {
         if (!empty($data['catfilter'])) {
             // use admin defined category
             $cidsarray = array($data['catfilter']);
             $cid = $data['catfilter'];
         } else {
             // use the current category
             // Jonn: this currently only works with one category at a time
             // it could be reworked to support multiple cids
             if (xarVarIsCached('Blocks.publications', 'cids')) {
                 $curcids = xarVarGetCached('Blocks.publications', 'cids');
                 if (!empty($curcids)) {
                     if ($curid == -1) {
                         //$cid = $curcids[0]['name'];
                         $cid = $curcids[0];
                         $cidsarray = array($curcids[0]);
                     } else {
                         $cid = $curcids[0];
                         $cidsarray = array($curcids[0]);
                     }
                 } else {
                     $cid = 0;
                     $cidsarray = array();
                 }
             } else {
                 // pull from all categories
                 $cid = 0;
                 $cidsarray = array();
             }
         }
         //echo $includechildren;
         if (!empty($data['includechildren']) && !empty($cidsarray[0]) && !strstr($cidsarray[0], '_')) {
             $cidsarray[0] = '_' . $cidsarray[0];
         }
         if (!empty($cid)) {
             // if we're viewing all items below a certain category, i.e. catid = _NN
             $cid = str_replace('_', '', $cid);
             $thiscategory = xarModAPIFunc('categories', 'user', 'getcat', array('cid' => $cid, 'return_itself' => 'return_itself'));
         }
         if (!empty($cidsarray) && isset($thiscategory[0]['name']) && !empty($data['dynamictitle'])) {
             $data['title'] .= ' ' . $thiscategory[0]['name'];
         }
     }
     // Get publication types
     // MarieA - moved to always get pubtypes.
     $publication_types = xarModAPIFunc('publications', 'user', 'get_pubtypes');
     if (!empty($data['nopublimit'])) {
         //don't limit by publication type
         $ptid = 0;
         if (!empty($data['dynamictitle'])) {
             $data['title'] .= ' ' . xarML('Content');
         }
     } else {
         // MikeC: Check to see if admin has specified that only a specific
         // Publication Type should be displayed.  If not, then default to original TopItems configuration.
         if ($data['pubtype_id'] == 0) {
             if (xarVarIsCached('Blocks.publications', 'ptid')) {
                 $ptid = xarVarGetCached('Blocks.publications', 'ptid');
             }
             if (empty($ptid)) {
                 // default publication type
                 $ptid = xarModVars::get('publications', 'defaultpubtype');
             }
         } else {
             // MikeC: Admin Specified a publication type, use it.
             $ptid = $data['pubtype_id'];
         }
         if (!empty($data['dynamictitle'])) {
             if (!empty($ptid) && isset($publication_types[$ptid]['description'])) {
                 $data['title'] .= ' ' . xarVarPrepForDisplay($publication_types[$ptid]['description']);
             } else {
                 $data['title'] .= ' ' . xarML('Content');
             }
         }
     }
     // frontpage or approved state
     if (empty($data['pubstate'])) {
         $statearray = array(2, 3);
     } elseif (!is_array($data['pubstate'])) {
         $statearray = preg_split('/,/', $data['pubstate']);
     } else {
         $statearray = $data['pubstate'];
     }
     // get cids for security check in getall
     $fields = array('id', 'title', 'pubtype_id', 'cids');
     if ($data['toptype'] == 'rating' && xarModIsHooked('ratings', 'publications', $ptid)) {
         array_push($fields, 'rating');
         $sort = 'rating';
     } elseif ($data['toptype'] == 'hits' && xarModIsHooked('hitcount', 'publications', $ptid)) {
         array_push($fields, 'counter');
         $sort = 'hits';
     } else {
         array_push($fields, 'create_date');
         $sort = 'date';
     }
     if (!empty($data['showsummary'])) {
         array_push($fields, 'summary');
     }
     if (!empty($data['showdynamic']) && xarModIsHooked('dynamicdata', 'publications', $ptid)) {
         array_push($fields, 'dynamicdata');
     }
     $publications = xarModAPIFunc('publications', 'user', 'getall', array('ptid' => $ptid, 'cids' => $cidsarray, 'andcids' => 'false', 'state' => $statearray, 'create_date' => time(), 'fields' => $fields, 'sort' => $sort, 'numitems' => $data['numitems']));
     if (!isset($publications) || !is_array($publications) || count($publications) == 0) {
         return;
     }
     $items = array();
     foreach ($publications as $article) {
         $article['title'] = xarVarPrepHTMLDisplay($article['title']);
         if ($article['id'] != $curid) {
             // Use the filtered category if set, and not including children
             $article['link'] = xarModURL('publications', 'user', 'display', array('itemid' => $article['id'], 'catid' => !empty($data['linkcat']) && !empty($data['catfilter']) ? $data['catfilter'] : NULL));
         } else {
             $article['link'] = '';
         }
         if (!empty($data['showvalue'])) {
             if ($data['toptype'] == 'rating') {
                 if (!empty($article['rating'])) {
                     $article['value'] = intval($article['rating']);
                 } else {
                     $article['value'] = 0;
                 }
             } elseif ($data['toptype'] == 'hits') {
                 if (!empty($article['counter'])) {
                     $article['value'] = $article['counter'];
                 } else {
                     $article['value'] = 0;
                 }
             } else {
                 // TODO: make user-dependent
                 if (!empty($article['create_date'])) {
                     //$article['value'] = strftime("%Y-%m-%d", $article['create_date']);
                     $article['value'] = xarLocaleGetFormattedDate('short', $article['create_date']);
                 } else {
                     $article['value'] = 0;
                 }
             }
         } else {
             $article['value'] = 0;
         }
         // MikeC: Bring the summary field back as $desc
         if (!empty($data['showsummary'])) {
             $article['summary'] = xarVarPrepHTMLDisplay($article['summary']);
             $article['transform'] = array('summary', 'title');
             $article = xarModCallHooks('item', 'transform', $article['id'], $article, 'publications');
         } else {
             $article['summary'] = '';
         }
         // MarieA: Bring the pubtype description back as $descr
         if (!empty($data['nopublimit'])) {
             $article['pubtypedescr'] = $publication_types[$article['pubtype_id']]['description'];
             //jojodee: while we are here bring the pubtype name back as well
             $article['pubtypename'] = $publication_types[$article['pubtype_id']]['name'];
         }
         // this will also pass any dynamic data fields (if any)
         $items[] = $article;
     }
     $data['items'] = $items;
     if (!empty($data['dynamictitle'])) {
         $this->setTitle($data['title']);
     }
     return $data;
 }
示例#2
0
 public function display()
 {
     $data = $this->getContent();
     // frontpage or approved state
     if (empty($data['pubstate'])) {
         $statearray = $this->state;
     } elseif (!is_array($data['pubstate'])) {
         $statearray = explode(',', $data['pubstate']);
     } else {
         $statearray = $data['pubstate'];
     }
     if (empty($data['locale'])) {
         $lang = null;
     } elseif ($data['locale'] == 'current') {
         $lang = xarMLSGetCurrentLocale();
     } else {
         $lang = $data['locale'];
     }
     // get cids for security check in getall
     $fields = array('id', 'title', 'body', 'notes', 'pubtype_id', 'cids', 'owner');
     if (!empty($data['showpubdate'])) {
         array_push($fields, 'pubdate');
     }
     if (!empty($data['showsummary'])) {
         array_push($fields, 'summary');
     }
     if (!empty($data['showauthor'])) {
         array_push($fields, 'owner');
     }
     if (!empty($data['alttitle'])) {
         $blockinfo['title'] = $data['alttitle'];
     }
     if (empty($data['pubtype_id'])) {
         $data['pubtype_id'] = 0;
     }
     if (!empty($data['catfilter'])) {
         // use admin defined category
         $cidsarray = array($data['catfilter']);
         $cid = $data['catfilter'];
     } else {
         $cid = 0;
         $cidsarray = array();
     }
     // check if dynamicdata is hooked for all pubtypes or the current one (= defaults to 0 anyway here)
     if (!empty($data['showdynamic']) && xarModIsHooked('dynamicdata', 'publications', $data['pubtype_id'])) {
         array_push($fields, 'dynamicdata');
     }
     if (empty($data['numitems'])) {
         $data['numitems'] = 1;
     }
     $publications = xarModAPIFunc('publications', 'user', 'getrandom', array('ptid' => $data['pubtype_id'], 'cids' => $cidsarray, 'andcids' => false, 'state' => $statearray, 'locale' => $lang, 'numitems' => $data['numitems'], 'fields' => $fields, 'unique' => true));
     if (!isset($publications) || !is_array($publications) || count($publications) == 0) {
         return;
     } else {
         foreach (array_keys($publications) as $key) {
             // for template compatibility :-(
             if (!empty($publications[$key]['author']) && !empty($data['showauthor'])) {
                 $publications[$key]['authorname'] = $publications[$key]['author'];
             }
             $data['items'][] = $publications[$key];
         }
     }
     return;
     $data;
 }
示例#3
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;
}
示例#4
0
/**
 * get overview of all publications
 * Note : the following parameters are all optional
 *
 * @param $args['numitems'] number of publications to get
 * @param $args['sort'] sort order ('create_date','title','hits','rating','author','id','summary','notes',...)
 * @param $args['startnum'] starting article number
 * @param $args['ids'] array of article ids to get
 * @param $args['owner'] the ID of the author
 * @param $args['ptid'] publication type ID (for news, sections, reviews, ...)
 * @param $args['state'] array of requested status(es) for the publications
 * @param $args['search'] search parameter(s)
 * @param $args['searchfields'] array of fields to search in
 * @param $args['searchtype'] start, end, like, eq, gt, ... (TODO)
 * @param $args['cids'] array of category IDs for which to get publications (OR/AND)
 *                      (for all categories don?t set it)
 * @param $args['andcids'] true means AND-ing categories listed in cids
 * @param $args['create_date'] publications published in a certain year (YYYY), month (YYYY-MM) or day (YYYY-MM-DD)
 * @param $args['startdate'] publications published at startdate or later
 *                           (unix timestamp format)
 * @param $args['enddate'] publications published before enddate
 *                         (unix timestamp format)
 * @param $args['fields'] array with all the fields to return per publication
 *                        Default list is : 'id','title','summary','owner',
 *                        'create_date','pubtype_id','notes','state','body1'
 *                        Optional fields : 'cids','author','counter','rating','dynamicdata'
 * @param $args['extra'] array with extra fields to return per article (in addition
 *                       to the default list). So you can EITHER specify *all* the
 *                       fields you want with 'fields', OR take all the default
 *                       ones and add some optional fields with 'extra'
 * @param $args['where'] additional where clauses (e.g. myfield gt 1234)
 * @param $args['locale'] language/locale (if not using multi-sites, categories etc.)
 * @return array Array of publications, or false on failure
 */
function publications_userapi_getall($args)
{
    // Get arguments from argument array
    extract($args);
    // Optional argument
    if (!isset($startnum)) {
        $startnum = 1;
    }
    if (empty($cids)) {
        $cids = array();
    }
    if (!isset($andcids)) {
        $andcids = false;
    }
    if (empty($ptid)) {
        $ptid = null;
    }
    // Default fields in publications (for now)
    $columns = array('id', 'name', 'title', 'description', 'summary', 'body1', 'owner', 'pubtype_id', 'notes', 'state', 'start_date');
    // Optional fields in publications (for now)
    // + 'cids' = list of categories an article belongs to
    // + 'author' = user name of owner
    // + 'counter' = number of times this article was displayed (hitcount)
    // + 'rating' = rating for this article (ratings)
    // + 'dynamicdata' = dynamic data fields for this article (dynamicdata)
    // + 'relevance' = relevance for this article (MySQL full-text search only)
    // $optional = array('cids','author','counter','rating','dynamicdata','relevance');
    if (!isset($fields)) {
        $fields = $columns;
    }
    if (isset($extra) && is_array($extra) && count($extra) > 0) {
        $fields = array_merge($fields, $extra);
    }
    if (empty($sort)) {
        if (!empty($search) && !empty($searchtype) && substr($searchtype, 0, 8) == 'fulltext') {
            if ($searchtype == 'fulltext boolean' && !in_array('relevance', $fields)) {
                // add the relevance to the field list for sorting
                $fields[] = 'relevance';
            }
            // let the database sort by relevance (= default for fulltext)
            $sortlist = array();
        } else {
            // default sort by create_date
            $sortlist = array('create_date');
        }
    } elseif (is_array($sort)) {
        $sortlist = $sort;
    } else {
        $sortlist = explode(',', $sort);
    }
    $publications = array();
    // Security check
    if (!xarSecurityCheck('ViewPublications')) {
        return;
    }
    // Fields requested by the calling function
    $required = array();
    foreach ($fields as $field) {
        $required[$field] = 1;
    }
    // mandatory fields for security
    $required['id'] = 1;
    $required['title'] = 1;
    $required['pubtype_id'] = 1;
    $required['create_date'] = 1;
    $required['owner'] = 1;
    // not to be confused with author (name) :-)
    // force cids as required when categories are given
    if (count($cids) > 0) {
        $required['cids'] = 1;
    }
    // TODO: put all this in dynamic data and retrieve everything via there (including hooked stuff)
    // Database information
    $dbconn = xarDB::getConn();
    // Get the field names and LEFT JOIN ... ON ... parts from publications
    // By passing on the $args, we can let leftjoin() create the WHERE for
    // the publications-specific columns too now
    $publicationsdef = xarModAPIFunc('publications', 'user', 'leftjoin', $args);
    // TODO : how to handle the case where name is empty, but uname isn't
    if (!empty($required['owner'])) {
        // Load API
        if (!xarModAPILoad('roles', 'user')) {
            return;
        }
        // Get the field names and LEFT JOIN ... ON ... parts from users
        $usersdef = xarModAPIFunc('roles', 'user', 'leftjoin');
        if (empty($usersdef)) {
            return;
        }
    }
    $regid = xarMod::getRegID('publications');
    if (!empty($required['cids'])) {
        // Load API
        if (!xarModAPILoad('categories', 'user')) {
            return;
        }
        // Get the LEFT JOIN ... ON ...  and WHERE (!) parts from categories
        $categoriesdef = xarModAPIFunc('categories', 'user', 'leftjoin', array('cids' => $cids, 'andcids' => $andcids, 'itemtype' => isset($ptid) ? $ptid : null, 'modid' => $regid));
        if (empty($categoriesdef)) {
            return;
        }
    }
    if (!empty($required['counter']) && xarModIsHooked('hitcount', 'publications', $ptid)) {
        // Load API
        if (!xarModAPILoad('hitcount', 'user')) {
            return;
        }
        // Get the LEFT JOIN ... ON ...  and WHERE (!) parts from hitcount
        $hitcountdef = xarModAPIFunc('hitcount', 'user', 'leftjoin', array('modid' => $regid, 'itemtype' => isset($ptid) ? $ptid : null));
    }
    if (!empty($required['rating']) && xarModIsHooked('ratings', 'publications', $ptid)) {
        // Load API
        if (!xarModAPILoad('ratings', 'user')) {
            return;
        }
        // Get the LEFT JOIN ... ON ...  and WHERE (!) parts from ratings
        $ratingsdef = xarModAPIFunc('ratings', 'user', 'leftjoin', array('modid' => $regid, 'itemtype' => isset($ptid) ? $ptid : null));
    }
    // Create the SELECT part
    $select = array();
    foreach ($required as $field => $val) {
        // we'll handle this later
        if ($field == 'cids') {
            continue;
        } elseif ($field == 'dynamicdata') {
            continue;
        } elseif ($field == 'owner') {
            $select[] = $usersdef['name'];
        } elseif ($field == 'counter') {
            if (!empty($hitcountdef['hits'])) {
                $select[] = $hitcountdef['hits'];
            }
        } elseif ($field == 'rating') {
            if (!empty($ratingsdef['rating'])) {
                $select[] = $ratingsdef['rating'];
            }
        } else {
            $select[] = $publicationsdef[$field];
        }
    }
    // FIXME: <rabbitt> PostgreSQL requires that all fields in an 'Order By' be in the SELECT
    //        this has been added to remove the error that not having it creates
    // FIXME: <mikespub> Oracle doesn't allow having the same field in a query twice if you
    //        don't specify an alias (at least in sub-queries, which is what SelectLimit uses)
    //    if (!in_array($publicationsdef['create_date'], $select)) {
    //        $select[] = $publicationsdef['create_date'];
    //    }
    // we need distinct for multi-category OR selects where publications fit in more than 1 category
    if (count($cids) > 0) {
        $query = 'SELECT DISTINCT ' . join(', ', $select);
    } else {
        $query = 'SELECT ' . join(', ', $select);
    }
    // Create the FROM ... [LEFT JOIN ... ON ...] part
    $from = $publicationsdef['table'];
    $addme = 0;
    if (!empty($required['owner'])) {
        // Add the LEFT JOIN ... ON ... parts from users
        $from .= ' LEFT JOIN ' . $usersdef['table'];
        $from .= ' ON ' . $usersdef['field'] . ' = ' . $publicationsdef['owner'];
        $addme = 1;
    }
    if (!empty($required['counter']) && isset($hitcountdef)) {
        // add this for SQL compliance when there are multiple JOINs
        // bug 4429: sqlite doesnt like the parentheses
        if ($addme && $dbconn->databaseType != 'sqlite') {
            $from = '(' . $from . ')';
        }
        // Add the LEFT JOIN ... ON ... parts from hitcount
        $from .= ' LEFT JOIN ' . $hitcountdef['table'];
        $from .= ' ON ' . $hitcountdef['field'] . ' = ' . $publicationsdef['id'];
        $addme = 1;
    }
    if (!empty($required['rating']) && isset($ratingsdef)) {
        // add this for SQL compliance when there are multiple JOINs
        // bug 4429: sqlite doesnt like the parentheses
        if ($addme && $dbconn->databaseType != 'sqlite') {
            $from = '(' . $from . ')';
        }
        // Add the LEFT JOIN ... ON ... parts from ratings
        $from .= ' LEFT JOIN ' . $ratingsdef['table'];
        $from .= ' ON ' . $ratingsdef['field'] . ' = ' . $publicationsdef['id'];
        $addme = 1;
    }
    if (count($cids) > 0) {
        // add this for SQL compliance when there are multiple JOINs
        // bug 4429: sqlite doesnt like the parentheses
        if ($addme && $dbconn->databaseType != 'sqlite') {
            $from = '(' . $from . ')';
        }
        // Add the LEFT JOIN ... ON ... parts from categories
        $from .= ' LEFT JOIN ' . $categoriesdef['table'];
        $from .= ' ON ' . $categoriesdef['field'] . ' = ' . $publicationsdef['id'];
        if (!empty($categoriesdef['more']) && $dbconn->databaseType != 'sqlite') {
            $from = '(' . $from . ')';
            $from .= $categoriesdef['more'];
        }
    }
    $query .= ' FROM ' . $from;
    // TODO: check the order of the conditions for brain-dead databases ?
    // Create the WHERE part
    $where = array();
    // we rely on leftjoin() to create the necessary publications clauses now
    if (!empty($publicationsdef['where'])) {
        $where[] = $publicationsdef['where'];
    }
    if (!empty($required['counter']) && !empty($hitcountdef['where'])) {
        $where[] = $hitcountdef['where'];
    }
    if (!empty($required['rating']) && !empty($ratingsdef['where'])) {
        $where[] = $ratingsdef['where'];
    }
    if (count($cids) > 0) {
        // we rely on leftjoin() to create the necessary categories clauses
        $where[] = $categoriesdef['where'];
    }
    if (count($where) > 0) {
        $query .= ' WHERE ' . join(' AND ', $where);
    }
    // TODO: support other non-publications fields too someday ?
    // Create the ORDER BY part
    if (count($sortlist) > 0) {
        $sortparts = array();
        $seenid = 0;
        foreach ($sortlist as $criteria) {
            // ignore empty sort criteria
            if (empty($criteria)) {
                continue;
            }
            // split off trailing ASC or DESC
            if (preg_match('/^(.+)\\s+(ASC|DESC)\\s*$/i', $criteria, $matches)) {
                $criteria = trim($matches[1]);
                $sortorder = strtoupper($matches[2]);
            } else {
                $sortorder = '';
            }
            if ($criteria == 'title') {
                $sortparts[] = $publicationsdef['title'] . ' ' . (!empty($sortorder) ? $sortorder : 'ASC');
                //            } elseif ($criteria == 'create_date' || $criteria == 'date') {
                //                $sortparts[] = $publicationsdef['create_date'] . ' ' . (!empty($sortorder) ? $sortorder : 'DESC');
            } elseif ($criteria == 'hits' && !empty($hitcountdef['hits'])) {
                $sortparts[] = $hitcountdef['hits'] . ' ' . (!empty($sortorder) ? $sortorder : 'DESC');
            } elseif ($criteria == 'rating' && !empty($ratingsdef['rating'])) {
                $sortparts[] = $ratingsdef['rating'] . ' ' . (!empty($sortorder) ? $sortorder : 'DESC');
            } elseif ($criteria == 'owner' && !empty($usersdef['name'])) {
                $sortparts[] = $usersdef['name'] . ' ' . (!empty($sortorder) ? $sortorder : 'ASC');
            } elseif ($criteria == 'relevance' && !empty($publicationsdef['relevance'])) {
                $sortparts[] = 'relevance' . ' ' . (!empty($sortorder) ? $sortorder : 'DESC');
            } elseif ($criteria == 'id') {
                $sortparts[] = $publicationsdef['id'] . ' ' . (!empty($sortorder) ? $sortorder : 'ASC');
                $seenid = 1;
                // other publications fields, e.g. summary, notes, ...
            } elseif (!empty($publicationsdef[$criteria])) {
                $sortparts[] = $publicationsdef[$criteria] . ' ' . (!empty($sortorder) ? $sortorder : 'ASC');
            } else {
                // ignore unknown sort fields
            }
        }
        // add sorting by id for unique sort order
        if (count($sortparts) < 2 && empty($seenid)) {
            $sortparts[] = $publicationsdef['id'] . ' DESC';
        }
        $query .= ' ORDER BY ' . join(', ', $sortparts);
    } elseif (!empty($search) && !empty($searchtype) && substr($searchtype, 0, 8) == 'fulltext') {
        // For fulltext, let the database return the publications by relevance here (= default)
        // For fulltext in boolean mode, add MATCH () ... AS relevance ... ORDER BY relevance DESC (cfr. leftjoin)
        if (!empty($required['relevance']) && $searchtype == 'fulltext boolean') {
            $query .= ' ORDER BY relevance DESC, ' . $publicationsdef['create_date'] . ' DESC, ' . $publicationsdef['id'] . ' DESC';
        }
    } else {
        // default is 'create_date'
        $query .= ' ORDER BY ' . $publicationsdef['create_date'] . ' DESC, ' . $publicationsdef['id'] . ' DESC';
    }
    //echo $query;
    // Run the query - finally :-)
    if (isset($numitems) && is_numeric($numitems)) {
        $result =& $dbconn->SelectLimit($query, $numitems, $startnum - 1);
    } else {
        $result =& $dbconn->Execute($query);
    }
    if (!$result) {
        return;
    }
    $itemids_per_type = array();
    // Put publications into result array
    for (; !$result->EOF; $result->MoveNext()) {
        $data = $result->fields;
        $item = array();
        // loop over all required fields again
        foreach ($required as $field => $val) {
            if ($field == 'cids' || $field == 'dynamicdata' || $val != 1) {
                continue;
            }
            $value = array_shift($data);
            if ($field == 'rating') {
                $value = intval($value);
            }
            $item[$field] = $value;
        }
        // check security - don't generate an exception here
        if (empty($required['cids']) && !xarSecurityCheck('ViewPublications', 0, 'Publication', "{$item['pubtype_id']}:All:{$item['owner']}:{$item['id']}")) {
            continue;
        }
        $publications[] = $item;
        if (!empty($required['dynamicdata'])) {
            $pubtype = $item['pubtype_id'];
            if (!isset($itemids_per_type[$pubtype])) {
                $itemids_per_type[$pubtype] = array();
            }
            $itemids_per_type[$pubtype][] = $item['id'];
        }
    }
    $result->Close();
    if (!empty($required['cids']) && count($publications) > 0) {
        // Get all the categories at once
        $ids = array();
        foreach ($publications as $article) {
            $ids[] = $article['id'];
        }
        // Load API
        if (!xarModAPILoad('categories', 'user')) {
            return;
        }
        // Get the links for the Array of iids we have
        $cids = xarModAPIFunc('categories', 'user', 'getlinks', array('iids' => $ids, 'reverse' => 1, 'modid' => $regid));
        // Inserting the corresponding Category ID in the Publication Description
        $delete = array();
        $cachesec = array();
        foreach ($publications as $key => $article) {
            if (isset($cids[$article['id']]) && count($cids[$article['id']]) > 0) {
                $publications[$key]['cids'] = $cids[$article['id']];
                foreach ($cids[$article['id']] as $cid) {
                    if (!xarSecurityCheck('ViewPublications', 0, 'Publication', "{$article['pubtype_id']}:{$cid}:{$article['owner']}:{$article['id']}")) {
                        $delete[$key] = 1;
                        break;
                    }
                    if (!isset($cachesec[$cid])) {
                        // TODO: combine with ViewCategoryLink check when we can combine module-specific
                        // security checks with "parent" security checks transparently ?
                        $cachesec[$cid] = xarSecurityCheck('ReadCategories', 0, 'Category', "All:{$cid}");
                    }
                    if (!$cachesec[$cid]) {
                        $delete[$key] = 1;
                        break;
                    }
                }
            } else {
                if (!xarSecurityCheck('ViewPublications', 0, 'Publication', "{$article['pubtype_id']}:All:{$article['owner']}:{$article['id']}")) {
                    $delete[$key] = 1;
                    continue;
                }
            }
        }
        if (count($delete) > 0) {
            foreach ($delete as $key => $val) {
                unset($publications[$key]);
            }
        }
    }
    if (!empty($required['dynamicdata']) && count($publications) > 0) {
        foreach ($itemids_per_type as $pubtype => $itemids) {
            if (!xarModIsHooked('dynamicdata', 'publications', $pubtype)) {
                continue;
            }
            list($properties, $items) = xarModAPIFunc('dynamicdata', 'user', 'getitemsforview', array('module' => 'publications', 'itemtype' => $pubtype, 'itemids' => $itemids, 'state' => 1));
            if (empty($properties) || count($properties) == 0) {
                continue;
            }
            foreach ($publications as $key => $article) {
                // otherwise publications (of different pub types) with dd properties having the same
                // names reset previously set values to empty string for each iteration based on the pubtype
                if ($article['pubtype_id'] != $pubtype) {
                    continue;
                }
                foreach (array_keys($properties) as $name) {
                    if (isset($items[$article['id']]) && isset($items[$article['id']][$name])) {
                        $value = $items[$article['id']][$name];
                    } else {
                        $value = $properties[$name]->default;
                    }
                    $publications[$key][$name] = $value;
                    // TODO: clean up this temporary fix
                    if (!empty($value)) {
                        $publications[$key][$name . '_output'] = $properties[$name]->showOutput(array('value' => $value));
                    }
                }
            }
        }
    }
    return $publications;
}
示例#5
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);
}
示例#6
0
 public function display()
 {
     $data = $this->getContent();
     // defaults
     $featuredid = $data['featuredid'];
     $fields = array('id', 'title', 'cids');
     $fields[] = 'dynamicdata';
     // Initialize arrays
     $data['feature'] = array();
     $data['items'] = array();
     // Setup featured item
     if ($featuredid > 0) {
         if (xarModIsHooked('uploads', 'publications', $data['pubtype_id'])) {
             xarVarSetCached('Hooks.uploads', 'ishooked', 1);
         }
         if ($featart = xarModAPIFunc('publications', 'user', 'getall', array('ids' => array($featuredid), 'extra' => array('cids', 'dynamicdata')))) {
             foreach ($featart as $featuredart) {
                 $fieldlist = array('id', 'title', 'summary', 'owner', 'pubdate', 'pubtype_id', 'notes', 'state', 'body', 'cids');
                 $featuredlink = xarModURL('publications', 'user', 'display', array('id' => $featuredart['id'], 'itemtype' => !empty($data['linkpubtype']) ? $featuredart['pubtype_id'] : NULL, 'catid' => !empty($data['linkcat']) && !empty($data['catfilter']) ? $data['catfilter'] : NULL));
                 if (empty($data['showfeaturedbod'])) {
                     $data['showfeaturedbod'] = false;
                 }
                 if (!isset($featuredart['cids'])) {
                     $featuredart['cids'] = "";
                 }
                 $feature = array('featuredname' => $featuredart['name'], 'featuredlabel' => $featuredart['title'], 'featuredlink' => $featuredlink, 'alttitle' => $data['alttitle'], 'altsummary' => $data['altsummary'], 'showfeaturedsum' => $data['showfeaturedsum'], 'showfeaturedbod' => $data['showfeaturedbod'], 'featureddesc' => $featuredart['summary'], 'featuredcids' => $featuredart['cids'], 'pubtype_id' => $featuredart['pubtype_id'], 'featuredid' => $featuredart['id'], 'featureddate' => $featuredart['start_date']);
                 // Get rid of the default fields so all we have left are the DD ones
                 foreach ($fieldlist as $field) {
                     if (isset($featuredart[$field])) {
                         unset($featuredart[$field]);
                     }
                 }
                 // now add the DD fields to the featuredart
                 $feature = array_merge($featuredart, $feature);
                 $data['feature'][] = $feature;
             }
         }
         // Setup additional items
         $fields = array('id', 'title', 'pubtype_id', 'cids');
         // Added the 'summary' field to the field list.
         if (!empty($data['showsummary'])) {
             $fields[] = 'summary';
         }
         if ($data['toptype'] == 'rating') {
             $fields[] = 'rating';
             $sort = 'rating';
         } elseif ($data['toptype'] == 'hits') {
             $fields[] = 'counter';
             $sort = 'hits';
         } elseif ($data['toptype'] == 'date') {
             $fields[] = 'pubdate';
             $sort = 'date';
         } else {
             $sort = $data['toptype'];
         }
         if (!empty($data['moreitems'])) {
             $publications = xarModAPIFunc('publications', 'user', 'getall', array('ids' => $data['moreitems'], 'enddate' => time(), 'fields' => $fields, 'sort' => $sort));
             // See if we're currently displaying an article
             if (xarVarIsCached('Blocks.publications', 'id')) {
                 $curid = xarVarGetCached('Blocks.publications', 'id');
             } else {
                 $curid = -1;
             }
             foreach ($publications as $article) {
                 if ($article['id'] != $curid) {
                     $link = xarModURL('publications', 'user', 'display', array('id' => $article['id'], 'itemtype' => !empty($vars['linkpubtype']) ? $article['pubtype_id'] : NULL, 'catid' => !empty($data['linkcat']) && !empty($data['catfilter']) ? $data['catfilter'] : NULL));
                 } else {
                     $link = '';
                 }
                 $count = '';
                 // TODO: find a nice clean way to show all sort types
                 if ($data['showvalue']) {
                     if ($data['toptype'] == 'rating') {
                         $count = intval($article['rating']);
                     } elseif ($data['toptype'] == 'hits') {
                         $count = $article['counter'];
                     } elseif ($data['toptype'] == 'date') {
                         // TODO: make user-dependent
                         if (!empty($article['pubdate'])) {
                             $count = strftime("%Y-%m-%d", $article['pubdate']);
                         } else {
                             $count = 0;
                         }
                     } else {
                         $count = 0;
                     }
                 } else {
                     $count = 0;
                 }
                 if (isset($article['cids'])) {
                     $cids = $article['cids'];
                 } else {
                     $cids = '';
                 }
                 if (isset($article['pubdate'])) {
                     $pubdate = $article['pubdate'];
                 } else {
                     $pubdate = '';
                 }
                 // Pass $desc to items[] array so that the block template can render it
                 $data['items'][] = array('label' => $article['title'], 'link' => $link, 'count' => $count, 'cids' => $cids, 'pubdate' => $pubdate, 'desc' => !empty($data['showsummary']) && !empty($article['summary']) ? $article['summary'] : '', 'id' => $article['id']);
             }
         }
     }
     if (empty($data['feature']) && empty($data['items'])) {
         // Nothing to display.
         return;
     }
     return $data;
 }